convert to using a civix-generated entity

This commit is contained in:
2019-08-19 17:48:04 -04:00
parent b27c080d18
commit 092cb2a184
9 changed files with 309 additions and 80 deletions

View File

@ -0,0 +1,160 @@
<?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
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' => 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,
];
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 = CRM_Utils_Rule::cleanMoney($grantBudget['balance_amount']);
$amountGranted = CRM_Utils_Rule::cleanMoney($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) {
$errors["multifund_amount[$k]"] = ts("The annual budget for this grant is {$grantBudget['budget']}. Grants totaling {$grantBudget['total_amount_granted']} have been made. {$grantBudget['balance_amount']} 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

@ -0,0 +1,238 @@
<?php
/**
* @package CRM
* @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:7aad27e2f51ebfb640dd921e054f55c9)
*/
/**
* Database access object for the GrantBudget entity.
*/
class CRM_AnnualGrantBudgets_DAO_GrantBudget extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
public static $_tableName = 'civicrm_grant_budget';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var bool
*/
public static $_log = TRUE;
/**
* Unique GrantBudget ID
*
* @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;
/**
* Class constructor.
*/
public function __construct() {
$this->__table = 'civicrm_grant_budget';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
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(), '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
*
* @return array
*/
public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = [
'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_AnnualGrantBudgets_DAO_GrantBudget',
'localizable' => 1,
],
'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
'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_AnnualGrantBudgets_DAO_GrantBudget',
'localizable' => 1,
'html' => [
'type' => 'Select',
],
'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
],
],
'fiscal_year' => [
'name' => 'fiscal_year',
'type' => CRM_Utils_Type::T_INT,
'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_AnnualGrantBudgets_DAO_GrantBudget',
'localizable' => 1,
'html' => [
'type' => 'Select',
],
'pseudoconstant' => [
'callback' => 'CRM_Grant_BAO_GrantBudget::getFiscalyear',
],
],
'budget' => [
'name' => 'budget',
'type' => CRM_Utils_Type::T_MONEY,
'title' => CRM_AnnualGrantBudgets_ExtensionUtil::ts('Grant Annual Budget'),
'description' => CRM_AnnualGrantBudgets_ExtensionUtil::ts('Grant Annual Budget'),
'required' => TRUE,
'precision' => [
20,
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',
],
],
];
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()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
/**
* Returns if this table needs to be logged
*
* @return bool
*/
public function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
public static function &import($prefix = FALSE) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'grant_budget', $prefix, []);
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
public static function &export($prefix = FALSE) {
$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 = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}