Compare commits

...

18 Commits

Author SHA1 Message Date
Jon Goldberg 38b48eefe9
fix grantbudget to handle different currency formats 2020-05-19 11:57:56 -04:00
Jon Goldberg ed86787d20
remove final references to old DAO/BAO 2019-08-20 13:52:02 -04:00
Jon Goldberg 87888691dc
implement the is_reserved lock 2019-08-19 18:59:03 -04:00
Jon Goldberg 4cf1c728e1
add note and lock to entity definition 2019-08-19 17:59:58 -04:00
Jon Goldberg 570d858b17
remove entitytype definition from extension; we're using .mgd.php files now 2019-08-19 17:54:24 -04:00
Jon Goldberg 092cb2a184
convert to using a civix-generated entity 2019-08-19 17:48:04 -04:00
Jon Goldberg b27c080d18
first steps toward supporting lock and note 2019-08-19 17:16:11 -04:00
Jon Goldberg 3534930f22
support totals on grant budget screen 2019-08-19 17:06:17 -04:00
Jon Goldberg 956c1e90c6
don't double-count grant when editing a grant 2019-07-19 15:22:13 -04:00
Jon Goldberg cf1a4923bc
permission fix 2019-07-08 15:05:14 -04:00
Jon Goldberg 4e3ffa7ee0
reduce permissions to edit grant budget 2019-07-08 14:53:03 -04:00
Jon Goldberg 836c86c042
Fix incorrect calculation of grant budgets over multiple years 2019-07-08 13:47:31 -04:00
Jon Goldberg 0edd576388
rewrite validation to support multifund 2019-06-18 20:06:11 -04:00
Jon Goldberg f05a93ddc5
remove hardcoded account relationship ID 2019-06-18 19:12:48 -04:00
Jon Goldberg e00085d701
rewrite budget screen to be multifund-aware 2019-06-18 18:56:47 -04:00
Jon Goldberg 75cee740f7
move grant budgets menu to grants menu, remove need for Administer CiviCRM permission 2019-06-18 14:48:28 -04:00
Jon Goldberg 15159960b2
minor fixes/typos 2018-10-22 15:13:08 -04:00
Jon Goldberg 4ee54f4764
set grant scholarship check date to money_transfer_date 2018-09-14 10:30:03 -04:00
13 changed files with 611 additions and 225 deletions

View File

@ -0,0 +1,165 @@
<?php
class CRM_AnnualGrantBudgets_BAO_GrantBudget extends CRM_AnnualGrantBudgets_DAO_GrantBudget {
/**
* Build Fiscal year option list.
*
*/
public static function getFiscalyear() {
$from = date("Y", strtotime(date('Y') . ' - ' . GRANT_SCHOLARSHIP_YEAR_DIFF . ' years'));
$to = date("Y", strtotime(date('Y') . ' + ' . GRANT_SCHOLARSHIP_YEAR_DIFF . ' years'));
return array_combine(range($to, $from), range($to, $from));
}
/**
* Get grant budget for fiscal year and financial type.
*
* @param $params array
*
* @return array
*/
public static function getGrantBudget($params) {
$returnTotals = $params['return_totals'];
$totals = [];
$fiscalYear = $params['fiscal_year'];
if (empty($fiscalYear)) {
$fiscalYear = date('Y');
}
$grantBudget = [];
$paidStatusID = CRM_Core_PseudoConstant::getKey(
'CRM_Grant_DAO_Grant', 'status_id', 'Paid'
);
$accountRelationshipId = civicrm_api3('OptionValue', 'getvalue', [
'return' => "value",
'option_group_id' => "account_relationship",
'name' => "Grant Expense Account is",
]);
$config = CRM_Core_Config::singleton();
$mkTime = mktime(0, 0, 0, $config->fiscalYearStart['M'], $config->fiscalYearStart['d'], $fiscalYear);
$fiscalStartDate = date('Y-m-d', $mkTime);
$fiscalEndDate = date('Y-m-d', strtotime($fiscalStartDate . '+ 1 year'));
$qParams = [
1 => [$fiscalYear, 'String'],
2 => [$fiscalStartDate, 'String'],
3 => [$fiscalEndDate, 'String'],
4 => [$paidStatusID, 'Integer'],
5 => [$accountRelationshipId, 'Integer'],
];
$where = '';
if (!empty($params['financial_type_id'])) {
$where = 'WHERE cft.id = %6';
$qParams[6] = [$params['financial_type_id'], 'Integer'];
}
$grantBudgetTableName = CRM_AnnualGrantBudgets_DAO_GrantBudget::getTableName();
$sql = "SELECT cgb.id, cft.name, IFNULL(cgb.budget, 0) AS budget,
SUM(CASE WHEN cg.id IS NULL THEN 0 ELSE IFNULL(trxn.total_amount, 0) END) as total_amount_granted,
cft.id AS financial_type_id, cgb.note, cgb.is_reserved
FROM civicrm_financial_type cft
INNER JOIN " . GRANT_SCHOLARSHIP_CUSTOM_TABLE_NAME . " gs
ON gs.entity_id = cft.id
AND gs." . GRANT_SCHOLARSHIP_CUSTOM_FIELD . " = 1
LEFT JOIN " . $grantBudgetTableName . " cgb
ON cgb.financial_type_id = cft.id AND cgb.fiscal_year = %1
LEFT JOIN civicrm_entity_financial_account cefa
ON cefa.entity_table = 'civicrm_financial_type' AND cft.id = cefa.entity_id AND account_relationship = %5
LEFT JOIN civicrm_financial_trxn trxn ON trxn.from_financial_account_id = cefa.financial_account_id
LEFT JOIN civicrm_entity_financial_trxn ceft on trxn.id = ceft.financial_trxn_id AND ceft.entity_table = 'civicrm_grant'
LEFT JOIN civicrm_grant cg
ON cg.id = ceft.entity_id AND cg.status_id IN (%4)
AND cg." . GRANT_DATE_CHECK_FIELD . " >= %2
AND cg." . GRANT_DATE_CHECK_FIELD . " < %3
{$where}
GROUP BY cft.id
ORDER BY cft.name";
$result = CRM_Core_DAO::executeQuery($sql, $qParams);
while ($result->fetch()) {
$grantBudget[] = [
'id' => $result->id,
'name' => $result->name,
'budget' => $result->budget,
'total_amount_granted' => $result->total_amount_granted,
'balance_amount' => $result->budget - $result->total_amount_granted,
'financial_type_id' => $result->financial_type_id,
'note' => $result->note,
'is_reserved' => $result->is_reserved,
];
if ($returnTotals) {
$totals['budget'] += $result->budget;
$totals['total_amount_granted'] += $result->total_amount_granted;
$totals['balance_amount'] += $result->budget - $result->total_amount_granted;
}
}
if ($returnTotals) {
// Format as money.
foreach ($totals as $k => $v) {
$totals[$k] = CRM_Utils_Money::format($v);
}
return $totals;
}
return $grantBudget;
}
/**
* Validate grant.
*
* @param $params array
* @param $grantId Integer
*
* @return array An array of errors
*/
public static function checkBudget($params, $grantId) {
$year = date('Y', strtotime($params[GRANT_DATE_CHECK_FIELD]));
foreach ($params['financial_account'] as $k => $financialAccount) {
if (!$financialAccount) {
break;
}
$financialTypeId = self::getFinancialTypeFromGrantExpenseAccount($financialAccount);
$grantBudget = civicrm_api3('GrantBudget', 'getbudget', [
'financial_type_id' => $financialTypeId,
'fiscal_year' => $year,
])['values'][0];
if ($grantBudget) {
$balanceAmount = $grantBudget['balance_amount'];
$amountGranted = $params['multifund_amount'][$k];
// If there's a $grantId, we're updating an existing grant. Make sure we don't
// double-count this money on validation.
if ($grantId) {
$oldGrantLineItem = civicrm_api3('EntityFinancialTrxn', 'get', [
'sequential' => 1,
'return' => ["financial_trxn_id.total_amount", "financial_trxn_id.trxn_date"],
'entity_table' => "civicrm_grant",
'entity_id' => $grantId,
'financial_trxn_id.from_financial_account_id' => $financialAccount,
])['values'][0];
if ($oldGrantLineItem && $year == date('Y', strtotime($oldGrantLineItem['financial_trxn_id.trxn_date']))) {
$amountGranted -= $oldGrantLineItem['financial_trxn_id.total_amount'];
}
}
if ($balanceAmount < $amountGranted) {
$budgetDisplay = CRM_Utils_Money::format($grantBudget['budget']);
$totalGrantedDisplay = CRM_Utils_Money::format($grantBudget['total_amount_granted']);
$balanceDisplay = CRM_Utils_Money::format($grantBudget['balance_amount']);
$errors["multifund_amount[$k]"] = ts("The annual budget for this grant is $budgetDisplay. Grants totaling $totalGrantedDisplay have been made. $balanceDisplay remains.");
}
}
}
return $errors;
}
public static function getFinancialTypeFromGrantExpenseAccount($accountId) {
$financialTypeId = civicrm_api3('EntityFinancialAccount', 'getvalue', [
'return' => "entity_id",
'account_relationship' => "Grant Expense Account is",
'financial_account_id' => $accountId,
'entity_table' => "civicrm_financial_type",
]);
return $financialTypeId;
}
}

View File

@ -1,67 +1,83 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* @copyright CiviCRM LLC (c) 2004-2019
*
* Generated from /home/jon/local/agbud8/htdocs/web/sites/all/civicrm/extensions/org.agbu.annualgrantbudgets/xml/schema/CRM/AnnualGrantBudgets/GrantBudget.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:e21dfb56b654dd78e0ead9af1ba5bf77)
* (GenCodeChecksum:36ad4daebed0e606747c4c8c53269a42)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Grant_BAO_GrantBudget constructor.
* Database access object for the GrantBudget entity.
*/
class CRM_Grant_DAO_GrantBudget extends CRM_Core_DAO {
class CRM_AnnualGrantBudgets_DAO_GrantBudget extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_grant_budget';
public static $_tableName = 'civicrm_grant_budget';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
* @var bool
*/
static $_log = TRUE;
public static $_log = TRUE;
/**
* Unique GrantBudget ID
*
* @var int unsigned
* @var int
*/
public $id;
/**
* FK to Financial Type
*
* @var int
*/
public $financial_type_id;
/**
* Fiscal year
*
* @var int
*/
public $fiscal_year;
/**
* Grant Annual Budget
*
* @var float
*/
public $budget;
/**
* Note
*
* @var string
*/
public $note;
/**
* Is this budget item locked for non-administrators?
*
* @var bool
*/
public $is_reserved;
/**
* Class constructor.
*/
public function __construct() {
$this->__table = 'civicrm_grant_budget';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
@ -70,12 +86,13 @@ class CRM_Grant_DAO_GrantBudget extends CRM_Core_DAO {
*/
public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financialtypeid', 'civicrm_financial_type', 'id');
Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_type_id', 'civicrm_financial_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
@ -87,25 +104,27 @@ class CRM_Grant_DAO_GrantBudget extends CRM_Core_DAO {
'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'description' => CRM_AnnualGrantBudgets_ExtensionUtil::ts('Unique GrantBudget ID'),
'required' => TRUE,
'where' => 'civicrm_grant_budget.id',
'table_name' => 'civicrm_grant_budget',
'entity' => 'GrantBudget',
'bao' => 'CRM_Grant_BAO_GrantBudget',
'localizable' => 0,
'bao' => 'CRM_AnnualGrantBudgets_DAO_GrantBudget',
'localizable' => 1,
],
'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Financial Type Id'),
'description' => 'FK to Financial Type',
'title' => CRM_AnnualGrantBudgets_ExtensionUtil::ts('Financial Type Id'),
'description' => CRM_AnnualGrantBudgets_ExtensionUtil::ts('FK to Financial Type'),
'required' => TRUE,
'import' => TRUE,
'where' => 'civicrm_grant_budget.financial_type_id',
'export' => FALSE,
'table_name' => 'civicrm_grant_budget',
'entity' => 'GrantBudget',
'bao' => 'CRM_Grant_BAO_GrantBudget',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
'bao' => 'CRM_AnnualGrantBudgets_DAO_GrantBudget',
'localizable' => 1,
'html' => [
'type' => 'Select',
],
@ -113,52 +132,92 @@ class CRM_Grant_DAO_GrantBudget extends CRM_Core_DAO {
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
]
],
],
'fiscal_year' => [
'name' => 'fiscal_year',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Fiscal year'),
'description' => 'Fiscal year',
'title' => CRM_AnnualGrantBudgets_ExtensionUtil::ts('Fiscal Year'),
'description' => CRM_AnnualGrantBudgets_ExtensionUtil::ts('Fiscal year'),
'required' => TRUE,
'import' => TRUE,
'where' => 'civicrm_grant_budget.fiscal_year',
'export' => FALSE,
'table_name' => 'civicrm_grant_budget',
'entity' => 'GrantBudget',
'bao' => 'CRM_Grant_BAO_GrantBudget',
'localizable' => 0,
'bao' => 'CRM_AnnualGrantBudgets_DAO_GrantBudget',
'localizable' => 1,
'html' => [
'type' => 'Select',
],
'pseudoconstant' => [
'callback' => 'CRM_Grant_BAO_GrantBudget::getFiscalyear',
]
'callback' => 'CRM_AnnualGrantBudgets_BAO_GrantBudge::getFiscalyear',
],
],
'budget' => [
'name' => 'budget',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Grant Annual Budget'),
'description' => 'Grant Annual Budget.',
'title' => CRM_AnnualGrantBudgets_ExtensionUtil::ts('Grant Annual Budget'),
'description' => CRM_AnnualGrantBudgets_ExtensionUtil::ts('Grant Annual Budget'),
'required' => TRUE,
'precision' => [
20,
2
2,
],
'import' => TRUE,
'where' => 'civicrm_grant_budget.budget',
'export' => TRUE,
'default' => '0.00',
'table_name' => 'civicrm_grant_budget',
'entity' => 'GrantBudget',
'bao' => 'CRM_AnnualGrantBudgets_DAO_GrantBudget',
'localizable' => 1,
'html' => [
'type' => 'Text',
],
],
'note' => [
'name' => 'note',
'type' => CRM_Utils_Type::T_STRING,
'title' => CRM_AnnualGrantBudgets_ExtensionUtil::ts('Note'),
'description' => CRM_AnnualGrantBudgets_ExtensionUtil::ts('Note'),
'required' => FALSE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'import' => TRUE,
'where' => 'civicrm_grant_budget.note',
'export' => TRUE,
'table_name' => 'civicrm_grant_budget',
'entity' => 'GrantBudget',
'bao' => 'CRM_Grant_BAO_GrantBudget',
'localizable' => 0,
'bao' => 'CRM_AnnualGrantBudgets_DAO_GrantBudget',
'localizable' => 1,
'html' => [
'type' => 'Text',
],
],
'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => CRM_AnnualGrantBudgets_ExtensionUtil::ts('Is Reserved'),
'description' => CRM_AnnualGrantBudgets_ExtensionUtil::ts('Is this budget item locked for non-administrators?'),
'import' => TRUE,
'where' => 'civicrm_grant_budget.is_reserved',
'export' => TRUE,
'default' => '0',
'table_name' => 'civicrm_grant_budget',
'entity' => 'GrantBudget',
'bao' => 'CRM_AnnualGrantBudgets_DAO_GrantBudget',
'localizable' => 1,
'html' => [
'type' => 'CheckBox',
],
],
];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
@ -171,14 +230,16 @@ class CRM_Grant_DAO_GrantBudget extends CRM_Core_DAO {
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
public static function getTableName() {
return self::$_tableName;
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
/**
* Returns if this table needs to be logged
*
@ -187,6 +248,7 @@ class CRM_Grant_DAO_GrantBudget extends CRM_Core_DAO {
public function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
@ -198,6 +260,7 @@ class CRM_Grant_DAO_GrantBudget extends CRM_Core_DAO {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'grant_budget', $prefix, []);
return $r;
}
/**
* Returns the list of fields that can be exported
*
@ -209,8 +272,13 @@ class CRM_Grant_DAO_GrantBudget extends CRM_Core_DAO {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'grant_budget', $prefix, []);
return $r;
}
/**
* Returns the list of indices
*
* @param bool $localize
*
* @return array
*/
public static function indices($localize = TRUE) {
$indices = [];

View File

@ -60,14 +60,13 @@ class CRM_AnnualGrantBudgets_Upgrader extends CRM_AnnualGrantBudgets_Upgrader_Ba
*
* @return TRUE on success
* @throws Exception
*
public function upgrade_4200() {
$this->ctx->log->info('Applying update 4200');
CRM_Core_DAO::executeQuery('UPDATE foo SET bar = "whiz"');
CRM_Core_DAO::executeQuery('DELETE FROM bang WHERE willy = wonka(2)');
*/
public function upgrade_1000() {
$this->ctx->log->info('Add notes and lock field to annual grant budget');
\CRM_Upgrade_Incremental_Base::addColumn($this->ctx, 'civicrm_grant_budget', 'note', "varchar(255) COMMENT 'Note'");
\CRM_Upgrade_Incremental_Base::addColumn($this->ctx, 'civicrm_grant_budget', 'is_reserved', "tinyint(4) DEFAULT 0 COMMENT 'Is this grant budget locked?'");
return TRUE;
} // */
}
/**
* Example: Run an external SQL script.

View File

@ -1,119 +0,0 @@
<?php
class CRM_Grant_BAO_GrantBudget extends CRM_Grant_DAO_GrantBudget {
/**
* Build Fiscal year option list.
*
*/
public static function getFiscalyear() {
$from = date("Y", strtotime(date('Y') . ' - ' . GRANT_SCHOLARSHIP_YEAR_DIFF . ' years'));
$to = date("Y", strtotime(date('Y') . ' + ' . GRANT_SCHOLARSHIP_YEAR_DIFF . ' years'));
return array_combine(range($to, $from), range($to, $from));
}
/**
* Get grant budget for fiscal year and financial type.
*
* @param $params array
*
* @return array
*/
public static function getGrantBudget($params) {
$fiscalYear = $params['fiscal_year'];
if (empty($fiscalYear)) {
$fiscalYear = date('Y');
}
$grantBudget = [];
$paidStatusID = CRM_Core_PseudoConstant::getKey(
'CRM_Grant_DAO_Grant',
'status_id',
'Paid'
);
$config = CRM_Core_Config::singleton();
$mkTime = mktime(0, 0, 0, $config->fiscalYearStart['M'], $config->fiscalYearStart['d'], $fiscalYear);
$fiscalStartDate = date('Y-m-d', $mkTime);
$fiscalEndDate = date('Y-m-d', strtotime($fiscalStartDate . '+ 1 year'));
$qParams = [
1 => [$fiscalYear, 'String'],
2 => [$fiscalStartDate, 'String'],
3 => [$fiscalEndDate, 'String'],
4 => [$paidStatusID, 'Integer'],
];
$where = '';
if (!empty($params['financial_type_id'])) {
$where = 'WHERE cft.id = %5';
$qParams[5] = [$params['financial_type_id'], 'Integer'];
}
$grantBudgetTableName = CRM_Grant_DAO_GrantBudget::getTableName();
$sql = "SELECT cgb.id, cft.name, IFNULL(cgb.budget, 0) AS budget,
SUM(IFNULL(cg." . GRANT_AMOUNT_CHECK_FIELD . ", 0)) as total_amount_granted,
cft.id AS financial_type_id
FROM civicrm_financial_type cft
INNER JOIN " . GRANT_SCHOLARSHIP_CUSTOM_TABLE_NAME . " gs
ON gs.entity_id = cft.id
AND gs." . GRANT_SCHOLARSHIP_CUSTOM_FIELD . " = 1
LEFT JOIN " . $grantBudgetTableName . " cgb
ON cgb.financial_type_id = cft.id AND cgb.fiscal_year = %1
LEFT JOIN civicrm_grant cg
ON cg.financial_type_id = cft.id AND cg.status_id IN (%4)
AND cg." . GRANT_DATE_CHECK_FIELD . " >= %2
AND cg." . GRANT_DATE_CHECK_FIELD . " < %3
{$where}
GROUP BY cft.id
ORDER BY cft.name";
$result = CRM_Core_DAO::executeQuery($sql, $qParams);
while ($result->fetch()) {
$grantBudget[] = [
'id' => $result->id,
'name' => $result->name,
'budget' => CRM_Utils_Money::format($result->budget),
'total_amount_granted' => CRM_Utils_Money::format($result->total_amount_granted),
'balance_amount' => CRM_Utils_Money::format(($result->budget - $result->total_amount_granted)),
'financial_type_id' => $result->financial_type_id,
];
}
return $grantBudget;
}
/**
* Validate grant.
*
* @param $params array
*
* @return bool
*/
public static function checkBudget($params, $grantId) {
$year = date('Y', strtotime($params[GRANT_DATE_CHECK_FIELD]));
$grantBudget = civicrm_api3('GrantBudget', 'getbudget', [
'financial_type_id' => $params['financial_type_id'],
'fiscal_year' => $year,
]);
$grantBudget = reset($grantBudget['values']);
$isError = FALSE;
if ($grantBudget) {
$balanceAmount = CRM_Utils_Rule::cleanMoney($grantBudget['balance_amount']);
$amountGranted = CRM_Utils_Rule::cleanMoney($params[GRANT_AMOUNT_CHECK_FIELD]);
if ($grantId) {
$oldGrantValues = civicrm_api3('Grant', 'getsingle', [
'return' => [GRANT_AMOUNT_CHECK_FIELD, 'financial_type_id', GRANT_DATE_CHECK_FIELD],
'id' => $grantId,
]);
if ($oldGrantValues['financial_type_id'] == $params['financial_type_id']
&& $year == date('Y', strtotime($oldGrantValues[GRANT_DATE_CHECK_FIELD]))
) {
$amountGranted -= $oldGrantValues[GRANT_AMOUNT_CHECK_FIELD];
}
}
if ($balanceAmount < $amountGranted) {
$isError = TRUE;
}
}
return [$isError, $grantBudget];
}
}

View File

@ -9,7 +9,7 @@ class CRM_Grant_Page_AnnualBudgets extends CRM_Core_Page_Basic {
* Classname of BAO.
*/
public function getBAOName() {
return 'CRM_Grant_BAO_GrantBudget';
return 'CRM_AnnualGrantBudgets_BAO_GrantBudget';
}
/**
@ -40,7 +40,7 @@ class CRM_Grant_Page_AnnualBudgets extends CRM_Core_Page_Basic {
$fiscalYear = date('Y');
}
$fiscalYearOptions = '';
foreach (CRM_Grant_BAO_GrantBudget::getFiscalyear() as $key => $value) {
foreach (CRM_AnnualGrantBudgets_BAO_GrantBudget::getFiscalyear() as $key => $value) {
$extra = '';
if ($key == $fiscalYear) {
$extra = 'selected="selected"';

View File

@ -263,16 +263,17 @@ function _annualgrantbudgets_civix_find_files($dir, $pattern) {
*/
function _annualgrantbudgets_civix_civicrm_managed(&$entities) {
$mgdFiles = _annualgrantbudgets_civix_find_files(__DIR__, '*.mgd.php');
sort($mgdFiles);
foreach ($mgdFiles as $file) {
$es = include $file;
foreach ($es as $e) {
if (empty($e['module'])) {
$e['module'] = E::LONG_NAME;
}
$entities[] = $e;
if (empty($e['params']['version'])) {
$e['params']['version'] = '3';
}
$entities[] = $e;
}
}
}
@ -453,6 +454,14 @@ function _annualgrantbudgets_civix_civicrm_alterSettingsFolders(&$metaDataFolder
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_entityTypes
*/
function _annualgrantbudgets_civix_civicrm_entityTypes(&$entityTypes) {
$entityTypes = array_merge($entityTypes, []);
$entityTypes = array_merge($entityTypes, array (
'CRM_AnnualGrantBudgets_DAO_GrantBudget' =>
array (
'name' => 'GrantBudget',
'class' => 'CRM_AnnualGrantBudgets_DAO_GrantBudget',
'table' => 'civicrm_grant_budget',
),
));
}

View File

@ -8,7 +8,8 @@ define('GRANT_SCHOLARSHIP_CUSTOM_FIELD', 'is_grant_scholarship');
define('GRANT_SCHOLARSHIP_CUSTOM_TABLE_NAME', 'civicrm_value_grant_scholarship');
define('GRANT_SCHOLARSHIP_YEAR_DIFF', 10);
define('GRANT_DATE_CHECK_FIELD', 'decision_date');
define('GRANT_AMOUNT_CHECK_FIELD', 'amount_granted');
define('GRANT_AMOUNT_CHECK_FIELD', 'total_amount');
/**
* Implements hook_civicrm_config().
*
@ -104,10 +105,10 @@ function annualgrantbudgets_civicrm_managed(&$entities) {
'title' => ts('Grant Scholarship'),
'extends' => 'FinancialType',
'style' => 'Inline',
'collapse_display' => TRUE,
'collapse_display' => 1,
'is_active' => TRUE,
'is_multiple' => FALSE,
'collapse_adv_display' => FALSE,
'collapse_adv_display' => 0,
'is_reserved' => TRUE,
'table_name' => GRANT_SCHOLARSHIP_CUSTOM_TABLE_NAME,
],
@ -179,11 +180,6 @@ function annualgrantbudgets_civicrm_alterSettingsFolders(&$metaDataFolders = NUL
*/
function annualgrantbudgets_civicrm_entityTypes(&$entityTypes) {
_annualgrantbudgets_civix_civicrm_entityTypes($entityTypes);
$entityTypes[] = [
'name' => 'GrantBudget',
'class' => 'CRM_Grant_DAO_GrantBudget',
'table' => 'civicrm_grant_budget',
];
}
/**
@ -193,13 +189,12 @@ function annualgrantbudgets_civicrm_entityTypes(&$entityTypes) {
*
*/
function annualgrantbudgets_civicrm_navigationMenu(&$menu) {
_annualgrantbudgets_civix_insert_navigation_menu($menu, 'Administer/CiviGrant', [
_annualgrantbudgets_civix_insert_navigation_menu($menu, 'Grants', [
'label' => ts('Grant Budget', ['domain' => 'org.agbu.annualgrantbudgets']),
'name' => 'grant_annual_budget',
'url' => CRM_Utils_System::url('civicrm/grant/annual/budgets', 'reset=1&action=browse', TRUE),
'active' => 1,
'permission_operator' => 'OR',
'permission' => 'access CiviGrant,administer CiviCRM',
'permission' => 'access CiviGrant',
]);
_annualgrantbudgets_civix_navigationMenu($menu);
}
@ -224,24 +219,26 @@ function annualgrantbudgets_civicrm_apiWrappers(&$wrappers, $apiRequest) {
*/
function annualgrantbudgets_civicrm_validateForm($formName, &$fields, &$files, &$form, &$errors) {
if ($formName == 'CRM_Grant_Form_Grant' && !($form->_action & CRM_Core_Action::DELETE)) {
if (empty($fields['financial_type_id'])
|| empty($fields['status_id'])
|| empty($fields[GRANT_DATE_CHECK_FIELD])
|| empty($fields[GRANT_AMOUNT_CHECK_FIELD])
if (empty($fields['financial_type_id']) || empty($fields['status_id']) || empty($fields[GRANT_DATE_CHECK_FIELD])
) {
return;
}
$paidStatusID = CRM_Core_PseudoConstant::getKey(
'CRM_Grant_DAO_Grant',
'status_id',
'Paid'
'CRM_Grant_DAO_Grant', 'status_id', 'Paid'
);
if ($paidStatusID != $fields['status_id']) {
return;
}
list($isError, $grantBudget) = CRM_Grant_BAO_GrantBudget::checkBudget($fields, $form->getVar('_id'));
if ($isError) {
$errors[GRANT_AMOUNT_CHECK_FIELD] = ts("The annual budget for this grant is {$grantBudget['budget']}. Grants totaling {$grantBudget['total_amount_granted']} have been made. {$grantBudget['balance_amount']} remains.");
}
$budgetErrors = CRM_AnnualGrantBudgets_BAO_GrantBudget::checkBudget($fields, $form->getVar('_id'));
$errors = array_merge($errors, $budgetErrors);
}
}
function annualgrantbudgets_civicrm_alterAPIPermissions($entity, $action, &$params, &$permissions) {
// Editing the budget should be possible with just "Access CiviGrant".
$permissions['grant_budget']['create'] = array('access CiviGrant');
$permissions['grant_budget']['update'] = array('access CiviGrant');
// They also need to be able to look up financial accounts to assign them.
$permissions['financial_account']['getlist'] = array('access CiviGrant');
$permissions['financial_account']['get'] = array('access CiviGrant');
}

View File

@ -55,7 +55,7 @@ function civicrm_api3_grant_budget_delete($params) {
* Array of deleted values.
*/
function civicrm_api3_grant_budget_getbudget($params) {
$result = CRM_Grant_BAO_GrantBudget::getGrantBudget($params);
$result = CRM_AnnualGrantBudgets_BAO_GrantBudget::getGrantBudget($params);
return civicrm_api3_create_success($result, $params, 'GrantBudget', 'get');
}
@ -70,4 +70,9 @@ function _civicrm_api3_grant_budget_getbudget_spec(&$spec) {
'title' => ts('Fiscal Year'),
'type' => CRM_Utils_Type::T_INT,
];
$spec['return_totals'] = [
'api.required' => 0,
'title' => ts('Return Totals?'),
'type' => CRM_Utils_Type::T_BOOLEAN,
];
}

View File

@ -1,15 +1,97 @@
CREATE TABLE IF NOT EXISTS `civicrm_grant_budget` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Primary ID',
`financial_type_id` int(10) UNSIGNED NOT NULL COMMENT 'FK to Financial Type.',
`fiscal_year` int(10) UNSIGNED NOT NULL COMMENT 'Fiscal Year',
`budget` decimal(20,2) DEFAULT '0.00' COMMENT 'Grant annual budget',
PRIMARY KEY (`id`),
KEY `FK_civicrm_grant_budget_financial_type_id` (`financial_type_id`),
UNIQUE KEY `UI_financial_type_id_fiscal_year` (`financial_type_id`,`fiscal_year`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- +--------------------------------------------------------------------+
-- | CiviCRM version 5 |
-- +--------------------------------------------------------------------+
-- | Copyright CiviCRM LLC (c) 2004-2019 |
-- +--------------------------------------------------------------------+
-- | This file is a part of CiviCRM. |
-- | |
-- | CiviCRM is free software; you can copy, modify, and distribute it |
-- | under the terms of the GNU Affero General Public License |
-- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
-- | |
-- | CiviCRM is distributed in the hope that it will be useful, but |
-- | WITHOUT ANY WARRANTY; without even the implied warranty of |
-- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
-- | See the GNU Affero General Public License for more details. |
-- | |
-- | You should have received a copy of the GNU Affero General Public |
-- | License and the CiviCRM Licensing Exception along |
-- | with this program; if not, contact CiviCRM LLC |
-- | at info[AT]civicrm[DOT]org. If you have questions about the |
-- | GNU Affero General Public License or the licensing of CiviCRM, |
-- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
-- +--------------------------------------------------------------------+
--
-- Generated from schema.tpl
-- DO NOT EDIT. Generated by CRM_Core_CodeGen
--
-- +--------------------------------------------------------------------+
-- | CiviCRM version 5 |
-- +--------------------------------------------------------------------+
-- | Copyright CiviCRM LLC (c) 2004-2019 |
-- +--------------------------------------------------------------------+
-- | This file is a part of CiviCRM. |
-- | |
-- | CiviCRM is free software; you can copy, modify, and distribute it |
-- | under the terms of the GNU Affero General Public License |
-- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
-- | |
-- | CiviCRM is distributed in the hope that it will be useful, but |
-- | WITHOUT ANY WARRANTY; without even the implied warranty of |
-- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
-- | See the GNU Affero General Public License for more details. |
-- | |
-- | You should have received a copy of the GNU Affero General Public |
-- | License and the CiviCRM Licensing Exception along |
-- | with this program; if not, contact CiviCRM LLC |
-- | at info[AT]civicrm[DOT]org. If you have questions about the |
-- | GNU Affero General Public License or the licensing of CiviCRM, |
-- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
-- +--------------------------------------------------------------------+
--
-- Constraints for table `civicrm_grant_budget`
-- Generated from drop.tpl
-- DO NOT EDIT. Generated by CRM_Core_CodeGen
--
ALTER TABLE `civicrm_grant_budget`
ADD CONSTRAINT `FK_civicrm_grant_budget_financial_type_id` FOREIGN KEY (`financial_type_id`) REFERENCES `civicrm_financial_type` (`id`) ON DELETE CASCADE;
-- /*******************************************************
-- *
-- * Clean up the exisiting tables
-- *
-- *******************************************************/
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `civicrm_grant_budget`;
SET FOREIGN_KEY_CHECKS=1;
-- /*******************************************************
-- *
-- * Create new tables
-- *
-- *******************************************************/
-- /*******************************************************
-- *
-- * civicrm_grant_budget
-- *
-- * FIXME
-- *
-- *******************************************************/
CREATE TABLE `civicrm_grant_budget` (
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'Unique ScholarshipBudget ID',
`financial_type_id` int unsigned NOT NULL COMMENT 'FK to Financial Type',
`fiscal_year` int unsigned NOT NULL COMMENT 'Fiscal year',
`budget` decimal(20,2) NOT NULL DEFAULT 0.00 COMMENT 'Scholarship Annual Budget',
`note` varchar(255) NULL COMMENT 'Note',
`is_reserved` tinyint DEFAULT 0 COMMENT 'Is this budget item locked for non-administrators?'
,
PRIMARY KEY (`id`)
, CONSTRAINT FK_civicrm_grant_budget_financial_type_id FOREIGN KEY (`financial_type_id`) REFERENCES `civicrm_financial_type`(`id`)
) ;

38
sql/auto_uninstall.sql Normal file
View File

@ -0,0 +1,38 @@
-- +--------------------------------------------------------------------+
-- | CiviCRM version 5 |
-- +--------------------------------------------------------------------+
-- | Copyright CiviCRM LLC (c) 2004-2019 |
-- +--------------------------------------------------------------------+
-- | This file is a part of CiviCRM. |
-- | |
-- | CiviCRM is free software; you can copy, modify, and distribute it |
-- | under the terms of the GNU Affero General Public License |
-- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
-- | |
-- | CiviCRM is distributed in the hope that it will be useful, but |
-- | WITHOUT ANY WARRANTY; without even the implied warranty of |
-- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
-- | See the GNU Affero General Public License for more details. |
-- | |
-- | You should have received a copy of the GNU Affero General Public |
-- | License and the CiviCRM Licensing Exception along |
-- | with this program; if not, contact CiviCRM LLC |
-- | at info[AT]civicrm[DOT]org. If you have questions about the |
-- | GNU Affero General Public License or the licensing of CiviCRM, |
-- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
-- +--------------------------------------------------------------------+
--
-- Generated from drop.tpl
-- DO NOT EDIT. Generated by CRM_Core_CodeGen
--
-- /*******************************************************
-- *
-- * Clean up the exisiting tables
-- *
-- *******************************************************/
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `civicrm_grant_budget`;
SET FOREIGN_KEY_CHECKS=1;

View File

@ -1,4 +1,9 @@
<div class="crm-content-block crm-block">
{* Check to see if this user can lock/unlock items *}
{if call_user_func(array('CRM_Core_Permission','check'), 'Administer CiviCRM')}
{assign var='canLock' value='crm-editable'}
{/if}
<label>{ts}Fiscal Year: {/ts}</label>
<select name="fiscal_year" type="text" id="fiscal_year" class="crm-form-select required crm-select2 six">
{$fiscal_year_options}
@ -6,25 +11,45 @@
</br></br>
<table cellpadding="0" cellspacing="0" border="0" class="row-highlight">
<thead class="sticky">
<th>{ts}Endowement{/ts}</th>
<th>{ts}Endowment{/ts}</th>
<th>{ts}Annual Budget{/ts}</th>
<th>{ts}Amount Awarded{/ts}</th>
<th>{ts}Amound Remaining{/ts}</th>
<th>{ts}Amount Remaining{/ts}</th>
<th>{ts}Locked?{/ts}</th>
<th>{ts}Note{/ts}</th>
</thead>
{crmAPI var='result' entity='GrantBudget' action='getbudget' fiscal_year=$fiscalYear}
{crmAPI var='totals' entity='GrantBudget' action='getbudget' fiscal_year=$fiscalYear return_totals=1}
<tr id="GrantBudget-totals" class="crm-entity">
<td><strong>Totals:</strong></td>
{foreach from=$totals.values item=total}
<td><strong>{$total}</strong></td>
{/foreach}
</tr>
{foreach from=$result.values item=row}
{if $row.id}
{assign var='rowId' value=$row.id}
{if !$row.is_reserved}
{assign var='canEdit' value='crm-editable'}
{/if}
{else}
{capture assign=rowId}{$row.financial_type_id}_{$fiscalYear}{/capture}
{/if}
<tr id="GrantBudget-{$rowId}" class="crm-entity {cycle values="odd-row,even-row"}">
<td>{$row.name}</td>
<td class="crm-editable" data-field="budget" data-type="text">{$row.budget}</td>
<td class="{$canEdit}" data-field="budget" data-type="text">{$row.budget}</td>
<td>{$row.total_amount_granted}</td>
<td>{$row.balance_amount}</td>
<td class="{$canLock}" data-field="is_reserved" data-type="boolean">{if $row.is_reserved eq 1} {ts}Yes{/ts} {else} {ts}No{/ts} {/if}</td>
<td class="{$canEdit}" data-field="note" data-type="text">{$row.note}</td>
</tr>
{/foreach}
<tr id="GrantBudget-totals" class="crm-entity">
<td><strong>Totals:</strong></td>
{foreach from=$totals.values item=total}
<td><strong>{$total}</strong></td>
{/foreach}
</tr>
</table>
{crmButton p="civicrm" q="reset=1" class="cancel" icon="times"}{ts}Done{/ts}{/crmButton}
</div>

View File

@ -0,0 +1,11 @@
<?php
// This file declares a new entity type. For more details, see "hook_civicrm_entityTypes" at:
// http://wiki.civicrm.org/confluence/display/CRMDOC/Hook+Reference
return array (
0 =>
array (
'name' => 'GrantBudget',
'class' => 'CRM_AnnualGrantBudgets_DAO_GrantBudget',
'table' => 'civicrm_grant_budget',
),
);

View File

@ -0,0 +1,106 @@
<?xml version="1.0" encoding="iso-8859-1" ?>
<table>
<base>CRM/AnnualGrantBudgets</base>
<class>GrantBudget</class>
<name>civicrm_grant_budget</name>
<comment>FIXME</comment>
<log>true</log>
<field>
<name>id</name>
<type>int unsigned</type>
<required>true</required>
<comment>Unique GrantBudget ID</comment>
<localizable>true</localizable>
</field>
<primaryKey>
<name>id</name>
<autoincrement>true</autoincrement>
</primaryKey>
<field>
<name>financial_type_id</name>
<title>Financial Type Id</title>
<type>int unsigned</type>
<comment>FK to Financial Type</comment>
<required>true</required>
<import>true</import>
<export>false</export>
<localizable>false</localizable>
<pseudoconstant>
<table>civicrm_financial_type</table>
<keyColumn>id</keyColumn>
<labelColumn>name</labelColumn>
</pseudoconstant>
<html>
<type>Select</type>
</html>
</field>
<foreignKey>
<name>financial_type_id</name>
<table>civicrm_financial_type</table>
<key>id</key>
</foreignKey>
<field>
<name>fiscal_year</name>
<title>Fiscal Year</title>
<type>int unsigned</type>
<comment>Fiscal year</comment>
<required>true</required>
<import>true</import>
<export>false</export>
<localizable>false</localizable>
<pseudoconstant>
<callback>CRM_AnnualGrantBudgets_BAO_GrantBudge::getFiscalyear</callback>
</pseudoconstant>
<html>
<type>Select</type>
</html>
</field>
<field>
<name>budget</name>
<title>Grant Annual Budget</title>
<type>decimal</type>
<comment>Grant Annual Budget</comment>
<required>true</required>
<import>true</import>
<export>true</export>
<localizable>false</localizable>
<default>0.00</default>
<html>
<type>Text</type>
</html>
</field>
<field>
<name>note</name>
<title>Note</title>
<type>varchar</type>
<length>255</length>
<comment>Note</comment>
<required>false</required>
<import>true</import>
<export>true</export>
<localizable>false</localizable>
<html>
<type>Text</type>
</html>
</field>
<field>
<name>is_reserved</name>
<title>Is Reserved</title>
<type>boolean</type>
<comment>Is this budget item locked for non-administrators?</comment>
<import>true</import>
<export>true</export>
<localizable>false</localizable>
<default>0</default>
<html>
<type>CheckBox</type>
</html>
</field>
</table>