diff --git a/CRM/Grant/BAO/GrantPayment.php b/CRM/Grant/BAO/GrantPayment.php index e5764bae7aceac23e333d9f76161971cf0003eb5..073f36267ecb81ba0053ecbb598a1fc3a498b0d5 100755 --- a/CRM/Grant/BAO/GrantPayment.php +++ b/CRM/Grant/BAO/GrantPayment.php @@ -36,7 +36,9 @@ class CRM_Grant_BAO_GrantPayment extends CRM_Grant_DAO_GrantPayment { - + const + STOP = 1, + REPRINT = 2; /** * static field for all the grant information that we can potentially export * @var array @@ -93,7 +95,7 @@ class CRM_Grant_BAO_GrantPayment extends CRM_Grant_DAO_GrantPayment { 'data_type' => CRM_Utils_Type::T_INT ), 'payment_number' => array( - 'title' => 'Payment Number', + 'title' => 'Check Number', 'name' => 'payment_number', 'data_type' => CRM_Utils_Type::T_INT ), @@ -170,26 +172,19 @@ class CRM_Grant_BAO_GrantPayment extends CRM_Grant_DAO_GrantPayment { * @static * @return object */ - static function add(&$params, &$ids) { - + static function add(&$params, &$ids = []) { if (empty($params)) { return; } - if (isset( $params['total_amount'])) { + if (isset($params['total_amount'])) { $params[$field] = CRM_Utils_Rule::cleanMoney($params['total_amount']); } // convert dates to mysql format - $dates = array( - 'payment_date', - 'payment_created_date' - ); - - foreach ($dates as $date) { - if (isset($params[$date])) { - $params[$date] = CRM_Utils_Date::processDate($params[$date], NULL, TRUE); - } + if (isset($params['payment_created_date'])) { + $params['payment_created_date'] = CRM_Utils_Date::processDate($params['payment_created_date'], NULL, TRUE); } + $grantPayment = new CRM_Grant_DAO_GrantPayment(); $grantPayment->id = CRM_Utils_Array::value('id', $ids); @@ -321,9 +316,7 @@ class CRM_Grant_BAO_GrantPayment extends CRM_Grant_DAO_GrantPayment { $grantDao->fetch(); if (!$grantDao->N) { - if ($params['messageTemplateID']) { - CRM_Core_Error::fatal(ts('No such message template.')); - } + CRM_Core_Error::fatal(ts('No such message template.')); } $subject = $grantDao->subject; $html = $grantDao->html; diff --git a/CRM/Grant/BAO/GrantProgram.php b/CRM/Grant/BAO/GrantProgram.php index 2f04a413f3a4d3f004a69bbf8033aa025849a20b..18a1022a4bde1d244396247fc932fb2cd5002706 100755 --- a/CRM/Grant/BAO/GrantProgram.php +++ b/CRM/Grant/BAO/GrantProgram.php @@ -309,14 +309,12 @@ WHERE civicrm_contact.id = $id "; if (CRM_Utils_Array::value('is_auto_email', $values)) { list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID); if (isset($email)) { - $grantStatuses = CRM_Core_OptionGroup::values('grant_status', FALSE, FALSE, FALSE, NULL, 'name'); - $grantStatuses = $grantStatuses[$values['status_id']]; - $valueName = strtolower($grantStatuses); - if ($grantStatuses == 'Awaiting Information') { - $explode = explode(' ', $grantStatuses); + $valueName = strtolower($grantStatus); + if ($grantStatus == 'Awaiting Information') { + $explode = explode(' ', $grantStatuse); $valueName = strtolower($explode[0]) . '_info'; } - elseif (strstr($grantStatuses, 'Approved')) { + elseif (strstr($grantStatus, 'Approved')) { $valueName = strtolower('Approved'); } $sendTemplateParams = array( @@ -451,4 +449,121 @@ WHERE civicrm_contact.id = $id "; ); CRM_Activity_BAO_Activity::create($params); } + + public static function getAssetFinancialAccountID() { + $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' ")); + return CRM_Core_DAO::singleValueQuery( + "SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", + [1 => [$relationTypeId, 'Integer']] + ); + } + + public static function convertNumberToWords($number) { + $hyphen = '-'; + $conjunction = ' and '; + $separator = ', '; + $negative = 'negative '; + $decimal = ' and '; + $dictionary = array( + 0 => 'zero', + 1 => 'one', + 2 => 'two', + 3 => 'three', + 4 => 'four', + 5 => 'five', + 6 => 'six', + 7 => 'seven', + 8 => 'eight', + 9 => 'nine', + 10 => 'ten', + 11 => 'eleven', + 12 => 'twelve', + 13 => 'thirteen', + 14 => 'fourteen', + 15 => 'fifteen', + 16 => 'sixteen', + 17 => 'seventeen', + 18 => 'eighteen', + 19 => 'nineteen', + 20 => 'twenty', + 30 => 'thirty', + 40 => 'fourty', + 50 => 'fifty', + 60 => 'sixty', + 70 => 'seventy', + 80 => 'eighty', + 90 => 'ninety', + 100 => 'hundred', + 1000 => 'thousand', + 1000000 => 'million', + 1000000000 => 'billion', + 1000000000000 => 'trillion', + 1000000000000000 => 'quadrillion', + 1000000000000000000 => 'quintillion' + ); + + if (!is_numeric($number)) { + return FALSE; + } + + if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) { + // overflow + trigger_error( + 'convertNumberToWords only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX, + E_USER_WARNING + ); + return FALSE; + } + + if ($number < 0) { + return $negative . self::convertNumberToWords(abs($number)); + } + + $string = $fraction = NULL; + + if (strpos($number, '.') !== FALSE) { + list($number, $fraction) = explode('.', $number); + } + + switch (TRUE) { + case $number < 21: + $string = $dictionary[$number]; + break; + case $number < 100: + $tens = ((int) ($number / 10)) * 10; + $units = $number % 10; + $string = $dictionary[$tens]; + if ($units) { + $string .= $hyphen . $dictionary[$units]; + } + break; + case $number < 1000: + $hundreds = $number / 100; + $remainder = $number % 100; + $string = $dictionary[$hundreds] . ' ' . $dictionary[100]; + if ($remainder) { + + $string .= $conjunction . self::convertNumberToWords(abs($remainder)); + } + break; + default: + $baseUnit = pow(1000, floor(log($number, 1000))); + $numBaseUnits = (int) ($number / $baseUnit); + $remainder = $number % $baseUnit; + $string = self::convertNumberToWords($numBaseUnits) . ' ' . $dictionary[$baseUnit]; + if ($remainder) { + $string .= $remainder < 100 ? $conjunction : $separator; + $string .= self::convertNumberToWords($remainder); + } + break; + } + + if (NULL !== $fraction && is_numeric($fraction)) { + $string .= $decimal; + $string .= $fraction . '/100'; + } + + return $string; + } + } diff --git a/CRM/Grant/BAO/PaymentSearch.php b/CRM/Grant/BAO/PaymentSearch.php index edbb3454c7a90729ccf6ffef13ea71663ba952e2..09fa7b9ee4327412f4e4e0eeef2e873bbf0abd8f 100755 --- a/CRM/Grant/BAO/PaymentSearch.php +++ b/CRM/Grant/BAO/PaymentSearch.php @@ -1,4 +1,4 @@ -_params =& $params; @@ -64,7 +64,7 @@ class CRM_Grant_BAO_PaymentSearch { } if (empty($returnProperties)) { $this->_returnProperties = self::defaultReturnProperties($mode); - } + } else { $this->_returnProperties =& $returnProperties; } @@ -75,7 +75,7 @@ class CRM_Grant_BAO_PaymentSearch { $this->_smartGroupCache = $smartGroupCache; $this->_displayRelationshipType = $displayRelationshipType; $this->setOperator($operator); - + if ($fields) { $this->_fields =& $fields; $this->_search = FALSE; @@ -88,11 +88,11 @@ class CRM_Grant_BAO_PaymentSearch { } function initialize() { - $this->_select = array(); - $this->_element = array(); + $this->_select = array(); + $this->_element = array(); $this->_tables = array(); $this->_whereTables = array(); - $this->_where = array(); + $this->_where = array(); $this->_qill = array(); $this->_options = array(); $this->_cfIDs = array(); @@ -100,7 +100,7 @@ class CRM_Grant_BAO_PaymentSearch { $this->_having = array(); $this->_customQuery = NULL; - $this->select(); + $this->select(); $this->element(); if (!empty($this->_params)) { $this->buildParamsLookup(); @@ -108,7 +108,7 @@ class CRM_Grant_BAO_PaymentSearch { $this->_whereClause = $this->whereClause(); $this->_tables = array('civicrm_payment' => 1); $this->_whereTables = array('civicrm_payment' => 1); - + $this->_fromClause = "FROM civicrm_payment"; $this->_simpleFromClause = "FROM civicrm_payment"; } @@ -126,19 +126,19 @@ class CRM_Grant_BAO_PaymentSearch { } $this->_cfIDs[$cfID][] = $value; } - + if (!array_key_exists($value[0], $this->_paramLookup)) { $this->_paramLookup[$value[0]] = array(); } $this->_paramLookup[$value[0]][] = $value; } } - + function whereClause() { $this->_where[0] = array(); $this->_qill[0] = array(); $config = CRM_Core_Config::singleton(); - + if (!empty( $this->_params)) { foreach (array_keys($this->_params) as $id) { @@ -157,10 +157,10 @@ class CRM_Grant_BAO_PaymentSearch { } $this->_qill = CRM_Utils_Array::crmArrayMerge($this->_qill , $this->_customQuery->_qill); } - + $clauses = array(); $andClauses = array(); - + $validClauses = 0; if (!empty($this->_where)) { foreach ($this->_where as $grouping => $values) { @@ -169,22 +169,22 @@ class CRM_Grant_BAO_PaymentSearch { $validClauses++; } } - + if (!empty($this->_where[0])) { $andClauses[] = ' ( ' . implode(" AND", $this->_where[0]) . ' ) '; } if (!empty($clauses)) { $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) '; } - + if ($validClauses > 1) { $this->_useDistinct = TRUE; } } - + return implode(' AND ', $andClauses); } - + function whereClauseSingle(&$values) { switch ($values[0]) { case 'payment_status_id': @@ -200,7 +200,7 @@ class CRM_Grant_BAO_PaymentSearch { $this->payment_number($values); return; case 'amount': - $this->amount($values); + $this->amount($values); return; case 'payment_created_date_low': case 'payment_created_date_high': @@ -209,74 +209,74 @@ class CRM_Grant_BAO_PaymentSearch { } } - + function payment_status(&$values) { list($name, $op, $value, $grouping, $wildcard) = $values; - + if (!$op) { $op = '='; } - $n = trim($value); + $n = trim($value); if (strtolower($n) == 'odd') { $this->_where[$grouping][] = " ( civicrm_payment.payment_status_id % 2 = 1 )"; $this->_qill[$grouping][] = ts( 'Payment Status Id is odd' ); - } + } else if (strtolower($n) == 'even') { $this->_where[$grouping][] = " ( civicrm_payment.payment_status_id % 2 = 0 )"; $this->_qill[$grouping][] = ts('Payment Status Id is even'); - } + } else { $value = strtolower(CRM_Core_DAO::escapeString($n)); $value = "'$value'"; - + $this->_where[$grouping][] = " ( civicrm_payment.payment_status_id $op $value )"; $paymentStatus = CRM_Core_OptionGroup::values('payment'); $n =$paymentStatus[$n]; $this->_qill[$grouping][] = ts('Payment Status') . " $op '$n'"; } - $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; + $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; } function payableName(&$values) { list($name, $op, $value, $grouping, $wildcard) = $values; $op = 'LIKE'; $newName = $name; - $name = trim($value); - + $name = trim($value); + if (empty($name)) { return; } $config = CRM_Core_Config::singleton(); - $sub = array(); + $sub = array(); //By default, $sub elements should be joined together with OR statements (don't change this variable). $subGlue = ' OR '; $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower'; - + if (substr($name, 0, 1) == '"' && substr($name, -1, 1) == '"') { - //If name is encased in double quotes, the value should be taken to be the string in entirety and the + //If name is encased in double quotes, the value should be taken to be the string in entirety and the $value = substr($name, 1, -1); $value = $strtolower(CRM_Core_DAO::escapeString($value)); $wc = ( $newName == 'payable_to_name') ? 'LOWER(civicrm_payment.payable_to_name)' : 'LOWER(civicrm_payment.payable_to_name)'; $sub[] = " ( $wc = '%$value%' ) "; - } + } else if (strpos($name, ',') !== FALSE) { - // if we have a comma in the string, search for the entire string + // if we have a comma in the string, search for the entire string $value = $strtolower(CRM_Core_DAO::escapeString($name)); if ($wildcard) { if ($config->includeWildCardInName) { $value = "'%$value%'"; - } + } else { $value = "'$value%'"; } $op = 'LIKE'; - } + } else { $value = "'%$value%'"; } @@ -284,11 +284,11 @@ class CRM_Grant_BAO_PaymentSearch { $wc = ($op != 'LIKE') ? "LOWER(civicrm_payment.payable_to_name)" : "civicrm_payment.payable_to_name"; } $sub[] = " ( $wc $op $value )"; - } + } else { //Else, the string should be treated as a series of keywords to be matched with match ANY/ match ALL depending on Civi config settings (see CiviAdmin) - - // The Civi configuration setting can be overridden if the string *starts* with the case insenstive strings 'AND:' or 'OR:' + + // The Civi configuration setting can be overridden if the string *starts* with the case insenstive strings 'AND:' or 'OR:' // TO THINK ABOUT: what happens when someone searches for the following "AND: 'a string in quotes'"? - probably nothing - it would make the AND OR variable reduntant because there is only one search string? // Check to see if the $subGlue is overridden in the search text @@ -300,7 +300,7 @@ class CRM_Grant_BAO_PaymentSearch { $name = substr($name, 3); $subGlue = ' OR '; } - + $firstChar = substr($name, 0, 1); $lastChar = substr($name, -1, 1); $quotes = array("'", '"'); @@ -309,27 +309,27 @@ class CRM_Grant_BAO_PaymentSearch { $name = substr($name, 1); $name = substr($name, 0, -1); $pieces = array($name); - } + } else { $pieces = explode(' ', $name); } - foreach ($pieces as $piece) { + foreach ($pieces as $piece) { $value = $strtolower(CRM_Core_DAO::escapeString(trim($piece))); if (strlen($value)) { // Added If as a sanitization - without it, when you do an OR search, any string with // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will // return all contacts because it will include a condition similar to "OR contact - // name LIKE '%'". It might be better to replace this with array_filter. + // name LIKE '%'". It might be better to replace this with array_filter. $fieldsub = array(); if ($wildcard) { if ($config->includeWildCardInName) { $value = "'%$value%'"; - } + } else { $value = "'$value%'"; } $op = 'LIKE'; - } + } else { $value = "'%$value%'"; } @@ -341,29 +341,29 @@ class CRM_Grant_BAO_PaymentSearch { // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields } } - } + } $sub = ' ( ' . implode($subGlue, $sub) . ' ) '; $this->_where[$grouping][] = $sub; $this->_qill[$grouping][] = ts('Payee Name like') . " - '$name'"; - $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; + $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; } function paymentDates($values) { list($name, $op, $value, $grouping, $wildcard) = $values; - + if (($name == 'payment_created_date_low') || ($name == 'payment_created_date_high')) { - - $this->dateQueryBuilder( + + $this->dateQueryBuilder( $values, - 'civicrm_payment', - 'payment_created_date', - 'payment_created_date', - ts('Date') + 'civicrm_payment', + 'payment_created_date', + 'payment_created_date', + ts('Date') ); - } + } } - + function &getWhereValues($name, $grouping) { $result = NULL; foreach ($this->_params as $id => $values) { @@ -374,13 +374,13 @@ class CRM_Grant_BAO_PaymentSearch { return $result; } - function dateQueryBuilder( + function dateQueryBuilder( &$values, - $tableName, - $fieldName, - $dbFieldName, + $tableName, + $fieldName, + $dbFieldName, $fieldTitle, - $appendTimeStamp = TRUE + $appendTimeStamp = TRUE ) { list($name, $op, $value, $grouping, $wildcard) = $values; @@ -416,7 +416,7 @@ class CRM_Grant_BAO_PaymentSearch { $secondDate = CRM_Utils_Date::processDate($secondValue); } - } + } else if ($name == $fieldName . '_high') { $firstOP = '<='; $firstPhrase = 'less than or equal to'; @@ -455,11 +455,11 @@ class CRM_Grant_BAO_PaymentSearch { ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' ) "; - $this->_qill[$grouping][] = + $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\""; - } + } else { $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'"; $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\""; @@ -477,7 +477,7 @@ class CRM_Grant_BAO_PaymentSearch { } $format = CRM_Utils_Date::customFormat($date); - + if ($date) { $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'"; if ($tableName == 'civicrm_log' && @@ -487,7 +487,7 @@ class CRM_Grant_BAO_PaymentSearch { $addedDateQuery = 'select id from civicrm_log group by entity_id order by id'; $this->_where[$grouping][] = "civicrm_log.id IN ( {$addedDateQuery} )"; } - } + } else { $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op"; } @@ -498,70 +498,70 @@ class CRM_Grant_BAO_PaymentSearch { function amount(&$values) { list($name, $op, $value, $grouping, $wildcard) = $values; - + if (!$op) { $op = '='; } - $n = trim($value); + $n = trim($value); if (strtolower($n) == 'odd') { $this->_where[$grouping][] = " ( civicrm_payment.amount % 2 = 1 )"; $this->_qill[$grouping][] = ts('Payment Amount is odd'); - } + } elseif (strtolower($n) == 'even') { $this->_where[$grouping][] = " ( civicrm_payment.amount % 2 = 0 )"; $this->_qill[$grouping][] = ts('Payment Amount is even'); - } + } else { $value = strtolower(CRM_Core_DAO::escapeString($n)); $value = "'$value'"; - + $this->_where[$grouping][] = " ( civicrm_payment.amount $op $value )"; $this->_qill[$grouping][] = ts( 'Payment Amount' ) . " $op '$n'"; - } - $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; + } + $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; } function payment_number(&$values) { list($name, $op, $value, $grouping, $wildcard) = $values; - + if (!$op) { $op = '='; } - $n = trim($value); + $n = trim($value); if (strtolower($n) == 'odd') { $this->_where[$grouping][] = " ( civicrm_payment.payment_number % 2 = 1 )"; $this->_qill[$grouping][] = ts( 'Payment Batch Number is odd' ); - } + } elseif (strtolower($n) == 'even') { $this->_where[$grouping][] = " ( civicrm_payment.payment_number % 2 = 0 )"; $this->_qill[$grouping][] = ts('Payment Batch Number is even'); - } + } else { $value = strtolower(CRM_Core_DAO::escapeString($n)); $value = "'$value'"; - + $this->_where[$grouping][] = " ( civicrm_payment.payment_number $op $value )"; - $this->_qill[$grouping][] = ts('Payment Number') . " $op '$n'"; + $this->_qill[$grouping][] = ts('Check Number') . " $op '$n'"; } - - $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; + + $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; } - + function payment_batch_number(&$values) { list($name, $op, $value, $grouping, $wildcard) = $values; - + if (!$op) { $op = '='; } - $n = trim($value); + $n = trim($value); if (strtolower($n) == 'odd') { $this->_where[$grouping][] = " ( civicrm_payment.payment_batch_number % 2 = 1 )"; $this->_qill[$grouping][] = ts('Payment Batch Number is odd'); - } + } elseif (strtolower($n) == 'even') { $this->_where[$grouping][] = " ( civicrm_payment.payment_batch_number % 2 = 0 )"; $this->_qill[$grouping][] = ts('Payment Batch Number is even'); - } + } else { $value = strtolower(CRM_Core_DAO::escapeString($n)); $value = "'$value'"; @@ -570,32 +570,32 @@ class CRM_Grant_BAO_PaymentSearch { $this->_qill[$grouping][] = ts('Payment Batch Number') . " $op '$n'"; } - $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; + $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; } function grantID(&$values) { $this->_where[$grouping][] = " ( civicrm_entity_payment.entity_id = $values )"; - $this->_tables['civicrm_entity_payment'] = $this->_whereTables['civicrm_entity_payment'] = 1; + $this->_tables['civicrm_entity_payment'] = $this->_whereTables['civicrm_entity_payment'] = 1; } - /** - * build select for CiviGrant - * - * @return void - * @access public + /** + * build select for CiviGrant + * + * @return void + * @access public */ - function select() { - $this->_select['id'] = 'civicrm_payment.id as id'; - $this->_select['payable_to_name'] = 'civicrm_payment.payable_to_name as payable_to_name'; - $this->_select['payment_batch_number'] = 'civicrm_payment.payment_batch_number as payment_batch_number'; - $this->_select['payment_number'] = 'civicrm_payment.payment_number as payment_number'; - $this->_select['payment_status_id'] = 'civicrm_payment.payment_status_id as payment_status_id'; - $this->_select['payment_created_date'] = 'civicrm_payment.payment_created_date as payment_created_date'; - $this->_select['amount'] = 'civicrm_payment.amount as amount'; + function select() { + $this->_select['id'] = 'p.id as id'; + $this->_select['payable_to_name'] = 'cc.display_name as payable_to_name'; + $this->_select['payment_batch_number'] = 'b.id as payment_batch_number'; + $this->_select['payment_status_id'] = 'p.payment_status_id'; + $this->_select['payment_created_date'] = 'p.payment_created_date'; + $this->_select['amount'] = 'ft.total_amount as amount'; + $this->_select['payment_number'] = 'ft.check_number as payment_number'; return $this->_select; } - - function element() { + + function element() { $this->_element['id'] = 1; $this->_element['payable_to_name'] = 1; $this->_element['payment_batch_number'] = 1; @@ -606,14 +606,14 @@ class CRM_Grant_BAO_PaymentSearch { return $this->_select; return $this->_element; } - - /** + + /** * Given a list of conditions in params generate the required * where clause - * - * @return void - * @access public - */ + * + * @return void + * @access public + */ static function where(&$query) { foreach (array_keys($query->_params) as $id) { if (substr($query->_params[$id][0], 0, 6) == 'grant_') { @@ -621,7 +621,7 @@ class CRM_Grant_BAO_PaymentSearch { } } } - + /** * getter for the qill object * @@ -631,9 +631,9 @@ class CRM_Grant_BAO_PaymentSearch { function qill() { return (isset($this->_qill)) ? $this->_qill : ""; } - + static function defaultReturnProperties($mode, - $includeCustomFields = TRUE + $includeCustomFields = TRUE ) { $properties = NULL; if ($mode & CRM_Grant_BAO_PaymentSearch::MODE_GRANT_PAYMENT) { @@ -653,41 +653,50 @@ class CRM_Grant_BAO_PaymentSearch { /** * add all the elements shared between grant search and advanaced search * - * @access public + * @access public * @return void * @static - */ - + */ + static function addShowHide(&$showHide) { $showHide->addHide('grantForm'); $showHide->addShow('grantForm_show'); } - + static function searchAction(&$row, $id) { } static function tableNames(&$tables) { } - + + function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE) { $select = 'SELECT '; if (!$count) { if (! empty($this->_select)) { $select .= implode(', ', $this->_select); } - } + } else { $select .= "count( DISTINCT ".$this->_distinctComponentClause." ) "; } - $from = ''; - if (!empty($this->_fromClause)) { - $from = $this->_fromClause; - } + $from = " FROM civicrm_payment p + LEFT JOIN civicrm_financial_trxn ft ON ft.id = p.financial_trxn_id + LEFT JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_grant' + LEFT JOIN civicrm_grant g ON g.id = eft.entity_id + LEFT JOIN civicrm_entity_financial_trxn eft1 ON eft1.financial_trxn_id = ft.id AND eft1.entity_table = 'civicrm_financial_item' + LEFT JOIN civicrm_financial_item fi ON fi.id = eft1.entity_id + LEFT JOIN civicrm_grant_program gp ON gp.id = g.grant_program_id + LEFT JOIN civicrm_entity_batch eb ON eb.entity_id = ft.id AND eb.entity_table = 'civicrm_financial_trxn' + LEFT JOIN civicrm_batch b ON eb.batch_id = b.id + LEFT JOIN civicrm_contact cc ON cc.id = fi.contact_id + "; + $where = ''; if (!empty($this->_whereClause)) { $where = "WHERE {$this->_whereClause}"; } - + $having = ''; if (!empty($this->_having)) { foreach ($this->_having as $havingsets) { @@ -699,34 +708,34 @@ class CRM_Grant_BAO_PaymentSearch { } return array($select, $from, $where, $having); } - - function searchQuery( - $offset = 0, - $rowCount = 0, - $sort = NULL, - $count = FALSE, + + function searchQuery( + $offset = 0, + $rowCount = 0, + $sort = NULL, + $count = FALSE, $includeContactIds = FALSE, - $sortByChar = FALSE, + $sortByChar = FALSE, $groupContacts = FALSE, $returnQuery = FALSE, - $additionalWhereClause = NULL, + $additionalWhereClause = NULL, $sortOrder = NULL, $additionalFromClause = NULL, - $skipOrderAndLimit = FALSE + $skipOrderAndLimit = FALSE ) { - + list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts); $order = $orderBy = $limit = ''; if (!$count) { - + $config = CRM_Core_Config::singleton(); if ($config->includeOrderByClause || isset($this->_distinctComponentClause)) { - + if ($sort) { if (is_string($sort)) { $orderBy = $sort; - } + } else { $orderBy = trim($sort->orderBy()); } @@ -736,36 +745,40 @@ class CRM_Grant_BAO_PaymentSearch { $order .= " $sortOrder"; } } - } - elseif ($sortByChar) { - $order = " ORDER BY UPPER(LEFT(civicrm_payment.payable_to_name, 1)) asc"; - } + } + elseif ($sortByChar) { + $order = " ORDER BY UPPER(LEFT(cc.display_name, 1)) asc"; + } else { - $order = " ORDER BY civicrm_payment.payable_to_name asc, civicrm_payment.id"; + $order = " ORDER BY cc.display_name asc, ft.id"; } } if ($rowCount > 0 && $offset >= 0) { $limit = " LIMIT $offset, $rowCount "; - + if (isset($this->_distinctComponentClause)) { $limitSelect = "SELECT {$this->_distinctComponentClause}"; - } + } else { $limitSelect = ($this->_useDistinct) ? - 'SELECT DISTINCT(civicrm_payment.id) as id' : - 'SELECT civicrm_payment.id as id'; + 'SELECT DISTINCT(ft.id) as id' : + 'SELECT ft.id as id'; } } - $groupBy = 'GROUP BY civicrm_payment.id'; + $groupBy = 'GROUP BY ft.id'; $query = "$select $from $where $having $groupBy $order $limit"; } - + if ($count) { $query = "$select $from $where"; return CRM_Core_DAO::singleValueQuery($query); } - + elseif (empty($query)) { + $query = "$select $from $where $having $groupBy $order $limit"; + } + //CRM_Core_Error::debug_var('q', $query); + $dao = CRM_Core_DAO::executeQuery($query); if ($groupContacts) { $ids = array(); @@ -804,14 +817,14 @@ class CRM_Grant_BAO_PaymentSearch { } if (!$skipWhere) { - $skipWhere = array( - 'task', - 'radio_ts', + $skipWhere = array( + 'task', + 'radio_ts', 'uf_group_id', - 'component_mode', - 'qfKey', + 'component_mode', + 'qfKey', 'operator', - 'display_relationship_type' + 'display_relationship_type' ); } @@ -828,10 +841,10 @@ class CRM_Grant_BAO_PaymentSearch { if (!$useEquals && in_array($id, $likeNames)) { $result = array($id, 'LIKE', $values, 0, 1); - } + } elseif (is_string($values) && strpos($values, '%') !== FALSE) { $result = array($id, 'LIKE', $values, 0, 0); - } + } elseif ($id == 'group') { if (is_array($values)) { foreach ($values as $groupIds => $val) { @@ -843,7 +856,7 @@ class CRM_Grant_BAO_PaymentSearch { } } } - } + } else { $groupIds = explode(',', $values); unset($values); @@ -852,7 +865,7 @@ class CRM_Grant_BAO_PaymentSearch { } } $result = array($id, 'IN', $values, 0, 0); - } + } elseif ($id == 'contact_tags' || $id == 'tag') { if (!is_array($values)) { $tagIds = explode(',', $values); @@ -862,7 +875,7 @@ class CRM_Grant_BAO_PaymentSearch { } } $result = array($id, 'IN', $values, 0, 0); - } + } else { $result = array($id, '=', $values, 0, $wildcard); } @@ -876,4 +889,4 @@ class CRM_Grant_BAO_PaymentSearch { } $this->_operator = $operator; } -} \ No newline at end of file +} diff --git a/CRM/Grant/DAO/GrantPayment.php b/CRM/Grant/DAO/GrantPayment.php index 8640274aa6c4d5101dc6231485f7184ec813b6f6..55fa146e0abb3d1e7108f3e8d68aad9d75ab5521 100644 --- a/CRM/Grant/DAO/GrantPayment.php +++ b/CRM/Grant/DAO/GrantPayment.php @@ -86,30 +86,7 @@ class CRM_Grant_DAO_GrantPayment extends CRM_Core_DAO * @var int unsigned */ public $id; - /** - * Payment Batch Nnumber - * - * @var int unsigned - */ - public $payment_batch_number; - /** - * Payment Number - * - * @var int unsigned - */ - public $payment_number; - /** - * Financial Type ID - * - * @var int unsigned - */ - public $financial_type_id; - /** - * Contact ID - * - * @var int unsigned - */ - public $contact_id; + public $financial_trxn_id; /** * Payment Created Date. * @@ -122,35 +99,6 @@ class CRM_Grant_DAO_GrantPayment extends CRM_Core_DAO * @var date */ public $payment_date; - /** - * Payable To Name. - * - * @var string - */ - public $payable_to_name; - /** - * Payable To Address. - * - * @var string - */ - public $payable_to_address; - /** - * Requested grant amount, in default currency. - * - * @var float - */ - public $amount; - /** - * 3 character string, value from config setting or input via user. - * - * @var string - */ - public $currency; - /** - * Payment Reason. - * - * @var string - */ public $payment_reason; /** * Payment Status ID @@ -196,46 +144,13 @@ class CRM_Grant_DAO_GrantPayment extends CRM_Core_DAO 'dataPattern' => '', 'export' => true, ) , - 'payment_batch_number' => array( - 'name' => 'payment_batch_number', + 'financial_trxn_id' => array( + 'name' => 'financial_trxn_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Payment Batch Nnumber') , + 'title' => ts('Financial Trxn ID') , 'required' => true, 'import' => true, - 'where' => 'civicrm_payment.payment_batch_number', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - 'payment_number' => array( - 'name' => 'payment_number', - 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Payment Number') , - 'required' => true, - 'import' => true, - 'where' => 'civicrm_payment.payment_number', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - 'financial_type_id' => array( - 'name' => 'financial_type_id', - 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Financial Type ID') , - 'required' => true, - 'import' => true, - 'where' => 'civicrm_payment.financial_type_id', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - 'contact_id' => array( - 'name' => 'contact_id', - 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Contact ID') , - 'required' => true, - 'import' => true, - 'where' => 'civicrm_payment.contact_id', + 'where' => 'civicrm_payment.financial_trxn_id', 'headerPattern' => '', 'dataPattern' => '', 'export' => true, @@ -250,63 +165,6 @@ class CRM_Grant_DAO_GrantPayment extends CRM_Core_DAO 'dataPattern' => '', 'export' => true, ) , - 'payment_date' => array( - 'name' => 'payment_date', - 'type' => CRM_Utils_Type::T_DATE, - 'title' => ts('Payment Date') , - 'import' => true, - 'where' => 'civicrm_payment.payment_date', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - 'payable_to_name' => array( - 'name' => 'payable_to_name', - 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Payable To Name') , - 'maxlength' => 255, - 'size' => CRM_Utils_Type::HUGE, - 'import' => true, - 'where' => 'civicrm_payment.payable_to_name', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - 'payable_to_address' => array( - 'name' => 'payable_to_address', - 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Payable To Address') , - 'maxlength' => 255, - 'size' => CRM_Utils_Type::HUGE, - 'import' => true, - 'where' => 'civicrm_payment.payable_to_address', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - 'amount' => array( - 'name' => 'amount', - 'type' => CRM_Utils_Type::T_MONEY, - 'title' => ts('Amount') , - 'required' => true, - 'import' => true, - 'where' => 'civicrm_payment.amount', - 'headerPattern' => '', - 'dataPattern' => '/^\d+(\.\d{2})?$/', - 'export' => true, - ) , - 'currency' => array( - 'name' => 'currency', - 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Currency') , - 'maxlength' => 3, - 'size' => CRM_Utils_Type::FOUR, - 'import' => true, - 'where' => 'civicrm_payment.currency', - 'headerPattern' => '/cur(rency)?/i', - 'dataPattern' => '/^[A-Z]{3}$/i', - 'export' => true, - ) , 'payment_reason' => array( 'name' => 'payment_reason', 'type' => CRM_Utils_Type::T_STRING, @@ -323,6 +181,9 @@ class CRM_Grant_DAO_GrantPayment extends CRM_Core_DAO 'name' => 'payment_status_id', 'type' => CRM_Utils_Type::T_INT, 'title' => ts('Payment Status') , + 'pseudoconstant' => [ + 'optionGroupName' => 'grant_payment_status', + ] ) , 'replaces_payment_id' => array( 'name' => 'replaces_payment_id', diff --git a/CRM/Grant/Form/Task/GrantPayment.php b/CRM/Grant/Form/Task/GrantPayment.php index 0b627ad5754d90ab93482b304fe50b866fd51f97..74e8d09a5f684ab3a6cf5dac6a6a4c7e3e6cd23b 100755 --- a/CRM/Grant/Form/Task/GrantPayment.php +++ b/CRM/Grant/Form/Task/GrantPayment.php @@ -38,14 +38,12 @@ * This class generates form components for Payments * */ -class CRM_Grant_Form_Task_GrantPayment extends CRM_Core_Form -{ +class CRM_Grant_Form_Task_GrantPayment extends CRM_Core_Form { protected $_id = null; protected $_fields = null; - function preProcess( ) { - parent::preProcess( ); - $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this ); + function preProcess() { + $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this ); $this->_prid = CRM_Utils_Request::retrieve('prid', 'Positive', $this ); if ( $this->_prid ) { $session = CRM_Core_Session::singleton(); @@ -54,104 +52,308 @@ class CRM_Grant_Form_Task_GrantPayment extends CRM_Core_Form } } - function setDefaultValues( ) - { - $defaults = array(); - $paymentNumbers = CRM_Grant_BAO_GrantPayment::getMaxPayementBatchNumber( ); - $defaults['payment_date'] = strftime("%m/%d/%Y", strtotime( date('Y/m/d') )); - $defaults['payment_number'] = $paymentNumbers['payment_number'] + 1; - $defaults['payment_batch_number'] = $paymentNumbers['payment_batch_number'] + 1; - - return $defaults; + /** + * Get payment fields + */ + public function getPaymentFields() { + return array( + 'check_number' => array( + 'is_required' => TRUE, + 'add_field' => TRUE, + ), + 'trxn_id' => array( + 'add_field' => TRUE, + 'is_required' => FALSE, + ), + 'description' => array( + 'htmlType' => 'textarea', + 'name' => 'description', + 'title' => ts('Payment reason'), + 'is_required' => FALSE, + 'attributes' => [], + ), + 'trxn_date' => array( + 'htmlType' => 'datepicker', + 'name' => 'trxn_date', + 'title' => ts('Payment date to appear on cheques'), + 'is_required' => TRUE, + 'attributes' => array( + 'date' => 'yyyy-mm-dd', + 'time' => 24, + 'context' => 'create', + 'action' => 'create', + ), + ), + 'contribution_batch_id' => [ + 'htmlType' => 'select', + 'name' => 'contribution_batch_id', + 'title' => ts('Assign to Batch'), + 'attributes' => ['' => ts('None')] + CRM_Contribute_PseudoConstant::batch(), + 'is_required' => TRUE, + ], + ); } + /** * Function to build the form * * @return None * @access public */ - public function buildQuickForm( $check = false ) - { - parent::buildQuickForm( ); - if ( $this->_action & CRM_Core_Action::DELETE ) { - - $this->addButtons( array( - array ( 'type' => 'next', - 'name' => ts('Delete'), - 'isDefault' => true ), - - array ( 'type' => 'cancel', - 'name' => ts('Cancel') ), - ) - ); + public function buildQuickForm(){ + if ($this->_action & CRM_Core_Action::DELETE) { + $this->addButtons([ + [ + 'type' => 'next', + 'name' => ts('Delete'), + 'isDefault' => TRUE, + ], + [ + 'type' => 'cancel', + 'name' => ts('Cancel'), + ], + ]); return; } - $this->applyFilter('__ALL__','trim'); - $attributes = CRM_Core_DAO::getAttribute( 'CRM_Grant_DAO_GrantProgram' ); + $paymentFields = $this->getPaymentFields(); + $this->assign('paymentFields', $paymentFields); + foreach ($paymentFields as $name => $paymentField) { + if (!empty($paymentField['add_field'])) { + $attributes = array( + 'entity' => 'FinancialTrxn', + 'name' => $name, + 'context' => 'create', + 'action' => 'create', + ); + $this->addField($name, $attributes, $paymentField['is_required']); + } + else { + $this->add($paymentField['htmlType'], + $name, + $paymentField['title'], + $paymentField['attributes'], + $paymentField['is_required'] + ); + } + } - $this->_contributionTypes = CRM_Grant_BAO_GrantProgram::contributionTypes(); - $this->add('select', 'financial_type_id', ts( 'From account' ), - array( '' => ts( '- select -' ) ) + $this->_contributionTypes , true); + $buttonName = $this->_prid ? 'Reprint Checks and CSV Export' : 'Create Checks and CSV Export'; + $this->addButtons([ + [ + 'type' => 'upload', + 'name' => ts($buttonName), + 'isDefault' => TRUE, + ], + [ + 'type' => 'cancel', + 'name' => ts('Cancel'), + ], + ]); + } - $this->add( 'text', 'payment_batch_number', ts( 'Payment Batch number' ), - $attributes['label'], true ); + public function postProcess() { + $values = $this->controller->exportValues($this->_name); + $approvedGrants = $this->get('approvedGrants'); + $approvedGrantIDs = array_keys($approvedGrants); + $grantPrograms = CRM_Grant_BAO_GrantProgram::getGrantPrograms(); + $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); + $financialItemStatus = CRM_Core_PseudoConstant::accountOptionValues('financial_item_status'); + $checkID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'payment_instrument_id', 'Check'); + $mailParams = $printedRows = $files = []; + $totalAmount = $counter = 0; + $maxLimit = CRM_Utils_Array::value('Maximum number of checks per pdf file', CRM_Core_OptionGroup::values('grant_thresholds', TRUE)); + $config = CRM_Core_Config::singleton(); + $entityFileDAO = new CRM_Core_DAO_EntityFile(); - $this->add( 'text', 'payment_number', ts( 'Starting cheque number' ), - $attributes['label'], true ); + $dao = CRM_Core_DAO::executeQuery(sprintf(" + SELECT ft.id as ft_id, g.id as grant_id, fi.id as fi_id, g.financial_type_id, ft.to_financial_account_id, fi.currency, gp.is_auto_email, ft.total_amount, fi.contact_id, g.grant_program_id + FROM civicrm_entity_financial_trxn eft + INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND eft.entity_table = 'civicrm_grant' + INNER JOIN civicrm_grant g ON g.id = eft.entity_id + INNER JOIN civicrm_entity_financial_trxn eft1 ON eft1.financial_trxn_id = ft.id AND eft1.entity_table = 'civicrm_financial_item' + INNER JOIN civicrm_financial_item fi ON fi.id = eft1.entity_id + INNER JOIN civicrm_grant_program gp ON gp.id = g.grant_program_id + WHERE g.id IN (%s) GROUP BY ft.id ", implode(', ', $approvedGrantIDs))); + while($dao->fetch()) { + $totalAmount += $dao->total_amount; + $grantID = $dao->grant_id; + $financialTrxnParams = [ + 'from_financial_account_id' => $dao->to_financial_account_id, + 'to_financial_account_id' => CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($dao->financial_type_id, 'Asset Account is') ?: CRM_Grant_BAO_GrantProgram::getAssetFinancialAccountID(), + 'trxn_date' => CRM_Utils_Array::value('trxn_date', $values, date('YmdHis')), + 'trxn_id' => CRM_Utils_Array::value('trxn_id', $values), + 'total_amount' => $dao->total_amount, + 'currency' => $dao->currency, + 'check_number' => $values['check_number'], + 'payment_instrument_id' => $checkID, + 'status_id' => array_search('Completed', $contributionStatuses), + 'entity_table' => 'civicrm_grant', + 'entity_id' => $grantID, + ]; + $trxnID = civicrm_api3('FinancialTrxn', 'create', $financialTrxnParams)['id']; + + $description = CRM_Utils_Array::value('description', $values, $grantPrograms[$dao->grant_program_id]); + $financialParams = ['description' => $description, 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'), 'amount' => $dao->total_amount]; + $ids = ['id' => $dao->fi_id]; + $trxnIDs = ['id' => $trxnID]; + CRM_Financial_BAO_FinancialItem::create($financialParams, $ids, $trxnIDs); + + civicrm_api3('EntityBatch', 'create', [ + 'entity_table' => 'civicrm_financial_trxn', + 'entity_id' => $trxnID, + 'batch_id' => $values['contribution_batch_id'], + ]); + + if ($dao->is_auto_email) { + $mailParams = [ + 'is_auto_email' => TRUE, + 'amount_total' => $dao->total_amount, + 'grant_type_id' => $approvedGrants[$grantID]['grant_type_id'], + 'grant_program_id' => $approvedGrants[$grantID]['grant_program_id'], + 'contact_id' => $dao->contact_id, + 'tplParams' => ['grant' => ['grant_programs' => $grantPrograms[$dao->grant_program_id]]], + ]; + CRM_Grant_BAO_GrantProgram::sendMail($dao->contact_id, $mailParams, 'Paid', $grantID, 'Approved for Payment'); + } - $this->addDate( 'payment_date', ts('Payment date to appear on cheques'), false, array( 'formatType' => 'custom') ); - $buttonName = "Create Checks and CSV Export"; - if ( $this->_prid ) { - $buttonName = "Reprint Checks and CSV Export"; + $grantPaymentRecord = [ + 'financial_trxn_id' => $trxnID, + 'payment_created_date' => date('Y-m-d'), + 'payment_status_id' => CRM_Core_PseudoConstant::getKey('CRM_Grant_DAO_GrantPayment', 'payment_status_id', 'Printed'), + 'payment_reason' => $description, + ]; + CRM_Grant_BAO_GrantPayment::add($grantPaymentRecord); + + $printedRows[$grantID] = [ + 'contact_id' => $dao->contact_id, + 'financial_type_id' => $dao->financial_type_id, + 'payment_batch_number' => $values['contribution_batch_id'], + 'payment_number' => $values['check_number'], + 'payment_date' => date("Y-m-d", strtotime($values['trxn_date'])), + 'payment_created_date' => $grantPaymentRecord['payment_created_date'], + // TODO remove CRM_Grant_BAO_GrantProgram::getDisplayName + 'payable_to_name' => CRM_Contact_BAO_Contact::displayName($dao->contact_id), + 'payable_to_address' => CRM_Utils_Array::value('address', CRM_Grant_BAO_GrantProgram::getAddress($dao->contact_id, NULL, TRUE)), + 'amount' => $dao->total_amount, + 'curreny' => $dao->currency, + 'payment_reason' => CRM_Utils_Array::value('description', $values, $grantPrograms[$dao->grant_program_id]), + 'payment_status_id' => array_search('Completed', $contributionStatuses), + 'replaces_payment_id' => NULL, + 'payment_details' => sprintf( + '%s %s%s%s', + date("Y-m-d", strtotime($values['trxn_date'])), + $dao->grant_id, + CRM_Contact_BAO_Contact::displayName($dao->contact_id), + CRM_Utils_Money::format($dao->total_amount, NULL, NULL, FALSE) + ), + 'total_in_words' => CRM_Grant_BAO_GrantProgram::convertNumberToWords($dao->total_amount), + ]; + + CRM_Core_DAO::executeQuery(sprintf('UPDATE civicrm_grant SET status_id = %d WHERE id = %d', + $grantID, + array_search('Paid', CRM_Core_OptionGroup::values('grant_status')) + )); } - $this->addButtons(array( - array ( 'type' => 'upload', - 'name' => ts($buttonName), - 'isDefault' => true ), - array ( 'type' => 'cancel', - 'name' => ts('Cancel') ), - ) - ); - $this->addFormRule( array( 'CRM_Grant_Form_Task_GrantPayment', 'formRule' ), $this ); - } - - public function formRule( $params, $files, $self ) - { - $errors = array( ); - $date = date('m/d/Y', mktime(0, 0, 0, date("m")-6 , date("d")+1, date("Y")) ); - if( strtotime($params['payment_date'] < strtotime($date) ) ) - $errors['payment_date'] = ts( 'Payments may not be back-dated more than 6 months.' ); + if (empty($printedRows)) { + return; + } - if ( ! CRM_Utils_Rule::integer($params['payment_number'] ) ) - $errors['payment_number'] = ts( "'{$params['payment_number']}' is not integer value." ); + foreach (array_chunk($printedRows, $maxLimit, TRUE) as $payments) { + $this->assign('grantPayment', $payments); + $downloadNamePDF = implode('_', [ + check_plain('grantPayment'), + date('Ymdhis'), + $counter + ]) . '.pdf'; + $fileName = CRM_Utils_File::makeFileName($downloadNamePDF); + $files[] = $fileName = $config->customFileUploadDir . CRM_Grant_BAO_GrantPayment::makePDF($fileName, $payments); + $counter++; + } - if ( ! CRM_Utils_Rule::integer($params['payment_batch_number'] ) ) - $errors['payment_batch_number'] = ts( "'{$params['payment_batch_number']}' is not integer value." ); + $this->assign('grantPayment', $printedRows); + $downloadNameCSV = implode('_', [ + check_plain('grantPayment'), + date('Ymdhis') + ]) . '.csv'; + $fileName = CRM_Utils_File::makeFileName($downloadNameCSV); + CRM_Grant_BAO_GrantPayment::createCSV($config->customFileUploadDir . $fileName, $printedRows); + $files[] = $config->customFileUploadDir . $fileName; + $fileID = civicrm_api3('File', 'create', [ + 'name' => basename($fileName), + 'mime_type' => 'text/csv', + 'uri' => $fileName, + ])['id']; + $entityFileDAO->entity_table = 'civicrm_contact'; + $entityFileDAO->entity_id = CRM_Core_Session::getLoggedInContactID(); + $entityFileDAO->file_id = $fileID; + $entityFileDAO->save(); - if ( $params['payment_number'] < 1 ) - $errors['payment_number'] = ts( "Please enter valid payment number." ); + $this->assign('date', date('Y-m-d')); + $this->assign('time', date('H:i:s')); + $this->assign('batch_number', $values['contribution_batch_id']); + $this->assign('contact', CRM_Contact_BAO_Contact::displayName(CRM_Core_Session::getLoggedInContactID())); + $this->assign('total_payments', count($approvedGrantIDs)); + $this->assign('total_amount' , CRM_Utils_Money::format($totalAmount, NULL, NULL,FALSE)); + $this->assign('domain_name', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', CRM_Core_Config::domainID(), 'name')); + $checkFile = CRM_Utils_File::makeFileName(check_plain('CheckRegister') . '.pdf'); + $checkRegister = CRM_Grant_BAO_GrantPayment::makeReport($checkFile, $printedRows); + $files[] = $config->customFileUploadDir . $checkRegister; - if ( $params['payment_batch_number'] < 1 ) - $errors['payment_batch_number'] = ts( "Please enter valid payment batch number." ); + //make Zip + $zipFile = check_plain('GrantPayment') . '_' . date('Ymdhis') . '.zip'; + foreach($files as $file) { + $source[] = $config->customFileUploadDir . $file; + } - if ( CRM_Utils_Rule::integer( $params['payment_number'] ) ) - if ( CRM_Grant_BAO_GrantPayment::getPaymentNumber( $params['payment_number'] ) ) - $errors['payment_number'] = ts( "Payment number already exists." ); + $uri = $config->customFileUploadDir . $zipFile; + $zip = CRM_Financial_BAO_ExportFormat::createZip($files, $uri); + $fileID = civicrm_api3('File', 'create', [ + 'name' => basename($fileName), + 'mime_type' => 'application/zip', + 'uri' => $zipFile, + ])['id']; + $entityFileDAO->entity_table = 'civicrm_contact'; + $entityFileDAO->entity_id = CRM_Core_Session::getLoggedInContactID(); + $entityFileDAO->file_id = $fileID; + $entityFileDAO->save(); - if ( CRM_Utils_Rule::integer( $params['payment_batch_number'] ) ) - if ( CRM_Grant_BAO_GrantPayment::getPaymentBatchNumber( $params['payment_batch_number'] ) ) - $errors['payment_batch_number'] = ts( "Payment batch number already exists." ); + $activityID = civicrm_api3('Activity', 'create', [ + 'source_contact_id' => CRM_Core_Session::getLoggedInContactID(), + 'activity_type_id' => 'grant_payment', + 'assignee_contact_id' => CRM_Core_Session::getLoggedInContactID(), + 'subject' => "Grant Payment", + 'status_id' => 'Completed', + 'priority_id' => 2, + ])['id']; + $params = array( + 'id' => $activityID, + 'attachFile_1' => array ( + 'uri' => $uri, + 'type' => 'text/csv', + 'location' => $uri, + 'upload_date' => date('YmdHis'), + ), + ); + CRM_Activity_BAO_Activity::create($params); - return empty($errors) ? true : $errors; + // download the zip file + CRM_Utils_System::setHttpHeader('Content-Type', 'application/zip'); + CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename=' . CRM_Utils_File::cleanFileName(basename($zipFile))); + CRM_Utils_System::setHttpHeader('Content-Length', '' . filesize($uri)); + ob_clean(); + flush(); + readfile($uri); + CRM_Utils_System::civiExit(); } + + /** * Function to process the form * * @access public * @return None - */ public function postProcess() { $details = $allGrants = $grantPayments = $grantAmount = array(); @@ -416,4 +618,5 @@ class CRM_Grant_Form_Task_GrantPayment extends CRM_Core_Form } CRM_Utils_System::redirect(CRM_Utils_System::url( 'civicrm/grant/payment/search', 'reset=1&bid='.$batchNumber.'&download='.$zipFile.'&force=1')); } + */ } diff --git a/CRM/Grant/Form/Task/Pay.php b/CRM/Grant/Form/Task/Pay.php index 7e79ee96815d1cfe9b323cc05397b3031f343185..c53c39019a5f7842d049e6f5b2ed71a6827a93f0 100755 --- a/CRM/Grant/Form/Task/Pay.php +++ b/CRM/Grant/Form/Task/Pay.php @@ -41,121 +41,76 @@ require_once 'CRM/Grant/Form/Task.php'; * participations. This class provides functionality for the actual * deletion. */ -class CRM_Grant_Form_Task_Pay extends CRM_Grant_Form_Task -{ - /** - * Are we operating in "single mode", i.e. deleting one - * specific participation? - * - * @var boolean - */ - protected $_single = false; +class CRM_Grant_Form_Task_Pay extends CRM_Grant_Form_Task { + /** + * Are we operating in "single mode", i.e. deleting one + * specific participation? + * + * @var boolean + */ + protected $_single = false; - /** - * build all the data structures needed to build the form - * - * @return void - * @access public - */ - function preProcess( ) - { - parent::preProcess( ); + function preProcess() { + parent::preProcess(); + if (!CRM_Core_Permission::check('create payments in CiviGrant')) { + CRM_Core_Error::fatal(ts( 'You do not have permission to access this page')); + } + } - //check permission for delete. - if ( !CRM_Core_Permission::checkActionPermission( 'CiviGrant', CRM_Core_Action::PAY ) ) { - CRM_Core_Error::fatal( ts( 'You do not have permission to access this page' ) ); - } - $grantStatus = CRM_Core_OptionGroup::values('grant_status', TRUE, FALSE, FALSE, NULL, 'name'); + function buildQuickForm() { + $message = []; + $paidGrantCount = civicrm_api3('Grant', 'getcount', [ + 'status_id' => 'Paid', + 'id' => ['IN' => $this->_grantIds] + ]); + $this->_approvedGrants = (array) civicrm_api3('Grant', 'get', [ + 'status_id' => 'Approved for Payment', + 'id' => ['IN' => $this->_grantIds] + ])['values']; - $paidGrants = $approvedGrants = array(); + $notApproved = count($this->_grantIds) - $paidGrantCount - count($this->_approvedGrants); - CRM_Core_PseudoConstant::populate($paidGrants, 'CRM_Grant_DAO_Grant', true, 'status_id', false, " id in (".implode ( ', ' , $this->_grantIds ).") AND status_id = {$grantStatus['Paid']}"); - CRM_Core_PseudoConstant::populate($approvedGrants, 'CRM_Grant_DAO_Grant', true, 'status_id', false, " id in (".implode ( ', ' , $this->_grantIds ).") AND status_id = {$grantStatus['Approved for Payment']}"); - - $this->_paidGrants = $paidGrants; - $this->_notApproved = count($this->_grantIds) - count( $this->_paidGrants ) - count( $approvedGrants ); + $currencyCount = count(array_flip(CRM_Utils_Array::collect('currency', $this->_approvedGrants))); + if (count($this->_approvedGrants)) { + if ($paidGrantCount) { + $message[] = sprintf("
%d of the %d selected grants have already been paid.", $paidGrantCount, count($this->_grantIds)); + } + if ($notApproved) { + $message[] = sprintf("%d of the %d selected grants are not eligible.", $notApproved, count($this->_grantIds)); + } + if ($currencyCount > 1) { + $message[] = sprintf("%d of the %d grants have different currency of same user.", $currencyCount, count($this->_grantIds)); + } + $message[] = 'Would you like to proceed to paying the ' . count($this->_approvedGrants) . ' eligible or approved for payment but unpaid grants?'; + CRM_Core_Session::setStatus(ts(implode('
', $message)), 'Payment Details', 'no-popup'); - foreach ( $approvedGrants as $key => $value ) { - $grantProgram = new CRM_Grant_DAO_Grant( ); - $grantArray = array( 'id' => $key ); - $grantProgram->copyValues( $grantArray ); - $grantProgram->find( true ); - $currencyDetails[$grantProgram->contact_id][$grantProgram->currency] = $key; - } - //$this->_currency = $currencyDetails; - $curency = 0; - if ( !empty( $currencyDetails ) ) { - foreach ( $currencyDetails as $key => $value ) { - if ( count($value) > 1 ) { - foreach ( $value as $unsetKey => $unsetVal ) { - unset( $approvedGrants[$unsetVal] ); - $curency++; - } - } - } - $this->_curency = $curency; - } - $this->_approvedGrants = $approvedGrants; + $this->addButtons( array( + array ( + 'type' => 'next', + 'name' => ts('Continue >>'), + 'spacing' => '          ', + 'isDefault' => true, + ), + array ( + 'type' => 'cancel', + 'name' => ts('Cancel'), + ), + ) + ); } - - /** - * Build the form - * - * @access public - * @return void - */ - function buildQuickForm( ) - { - $message = ""; - if (count($this->_approvedGrants)) { - if (count($this->_paidGrants)) { - $message = count( $this->_paidGrants ).' of the '.count($this->_grantIds).' selected grants have already been paid. '; - } - if ($this->_notApproved) { - $message .= $this->_notApproved.' of the '.count($this->_grantIds).' selected grants are not eligible. '; - } - if ($this->_curency) { - $message .= $this->_curency.' of '.count($this->_grantIds).' grants have different currency of same user. '; - } - if (count( $this->_approvedGrants )) { - $message .= 'Would you like to proceed to paying the '.count( $this->_approvedGrants ).' eligible or approved for payment but unpaid grants?'; - CRM_Core_Session::setStatus(ts($message), NULL, 'no-popup'); - } - - $this->addButtons( array( - array ( - 'type' => 'next', - 'name' => ts('Continue >>'), - 'spacing' => '          ', - 'isDefault' => true, - ), - array ( - 'type' => 'cancel', - 'name' => ts('Cancel'), - ), - ) - ); - } - else { - CRM_Core_Session::setStatus(ts('Please select at least one grant that has been approved for payment or eligible and not been paid.'), NULL, 'no-popup'); - $this->addButtons(array( - array ( - 'type' => 'cancel', - 'name' => ts('Cancel') ), - ) - ); - } + else { + CRM_Core_Session::setStatus(ts('Please select at least one grant that has been approved for payment or eligible and not been paid.'), NULL, 'no-popup'); + $this->addButtons(array( + array ( + 'type' => 'cancel', + 'name' => ts('Cancel') ), + ) + ); } + } - /** - * process the form after the input has been submitted and validated - * - * @access public - * @return None - */ - public function postProcess( ) - { - $this->set( 'approvedGrants', $this->_approvedGrants ); - $this->controller->resetPage( 'GrantPayment' ); - } + public function postProcess() { + $this->set('approvedGrants', $this->_approvedGrants); + $this->controller->resetPage('GrantPayment'); + } } diff --git a/CRM/Grant/Form/Task/Reprint.php b/CRM/Grant/Form/Task/Reprint.php index af69d617ca30ef18808865b4bd7ff69f7fdc9e11..216ac0bf77a47793014dd8daf5cca5ef3e789999 100755 --- a/CRM/Grant/Form/Task/Reprint.php +++ b/CRM/Grant/Form/Task/Reprint.php @@ -55,33 +55,24 @@ class CRM_Grant_Form_Task_Reprint extends CRM_Grant_Form_PaymentTask * @return void * @access public */ - function preProcess( ) + function preProcess( ) { parent::preProcess( ); - + if ( !CRM_Core_Permission::checkActionPermission( 'CiviGrant', CRM_Core_Action::PAY ) ) { CRM_Core_Error::fatal( ts( 'You do not have permission to access this page' ) ); } - - } - function setDefaultValues( ) - { - $defaults = array(); - $paymentNumbers = CRM_Grant_BAO_GrantPayment::getMaxPayementBatchNumber( ); - $defaults['payment_date'] = strftime("%m/%d/%Y", strtotime( date('Y/m/d') )); - $defaults['payment_number'] = $paymentNumbers['payment_number'] + 1; - $defaults['payment_batch_number'] = $paymentNumbers['payment_batch_number'] + 1; - return $defaults; } + /** * Build the form * * @access public * @return void */ - function buildQuickForm( ) - { + function buildQuickForm( ) + { require_once 'CRM/Core/OptionGroup.php'; $validStatus = array( 'Printed', 'Reprinted'); $paymentStatus = CRM_Core_OptionGroup::values( 'grant_payment_status' ); @@ -92,8 +83,8 @@ class CRM_Grant_Form_Task_Reprint extends CRM_Grant_Form_PaymentTask } $selectedPayments = count($this->_grantPaymentIds); foreach ( $this->_grantPaymentIds as $key => $paymentId ) { - $paymentDAO =& new CRM_Grant_DAO_GrantPayment(); - $paymentDAO->id = $paymentId; + $paymentDAO = new CRM_Grant_DAO_GrantPayment(); + $paymentDAO->id = $paymentId; $paymentDAO->find(true); if( array_key_exists( $paymentDAO->payment_status_id, $paymentStatus ) ) { unset($this->_grantPaymentIds[$key]); @@ -106,7 +97,7 @@ class CRM_Grant_Form_Task_Reprint extends CRM_Grant_Form_PaymentTask CRM_Core_Session::setStatus(ts( $stopped.' of the '.$selectedPayments.' selected grant payments have already been stopped. '.count($this->_grantPaymentIds).' of the '.count($this->_grantPaymentIds).' selected grant payments are printed or reprinted.'), NULL, 'no-popup'); $this->applyFilter('__ALL__','trim'); $attributes = CRM_Core_DAO::getAttribute( 'CRM_Grant_DAO_GrantProgram' ); - + $this->_contributionTypes = CRM_Grant_BAO_GrantProgram::contributionTypes(); $this->add('select', 'financial_type_id', ts( 'From account' ), array( '' => ts( '- select -' ) ) + $this->_contributionTypes , true); @@ -116,25 +107,25 @@ class CRM_Grant_Form_Task_Reprint extends CRM_Grant_Form_PaymentTask $this->add( 'text', 'payment_number', ts( 'Starting cheque number' ), $attributes['label'], true ); - + $this->addDate( 'payment_date', ts('Payment date to appear on cheques'), false, array( 'formatType' => 'custom') ); - - $this->addButtons(array( + + $this->addButtons(array( array ( 'type' => 'upload', - 'name' => ts('Reprint Checks'), + 'name' => ts('Reprint Checks'), 'isDefault' => true ), array ( 'type' => 'next', - 'name' => ts('Export to CSV'),), - array ( 'type' => 'cancel', - 'name' => ts('Cancel') ), - ) + 'name' => ts('Export to CSV'),), + array ( 'type' => 'cancel', + 'name' => ts('Cancel') ), + ) ); } else { CRM_Core_Session::setStatus(ts('Please select at least one grant payment that has been printed.'), NULL, 'no-popup'); - $this->addButtons(array( - array ( 'type' => 'cancel', - 'name' => ts('Cancel') ), - ) + $this->addButtons(array( + array ( 'type' => 'cancel', + 'name' => ts('Cancel') ), + ) ); } } @@ -145,8 +136,8 @@ class CRM_Grant_Form_Task_Reprint extends CRM_Grant_Form_PaymentTask * @access public * @return None */ - public function postProcess( ) - { + public function postProcess( ) + { $values = $this->controller->exportValues( $this->_name ); $makePdf = true; foreach ( $_POST as $buttonKey => $buttonValue ) { @@ -156,55 +147,55 @@ class CRM_Grant_Form_Task_Reprint extends CRM_Grant_Form_PaymentTask } $totalAmount = 0; foreach ( $this->_grantPaymentIds as $paymentId ) { - - $paymentDAO =& new CRM_Grant_DAO_GrantPayment(); - $paymentDAO->id = $paymentId; + + $paymentDAO = new CRM_Grant_DAO_GrantPayment(); + $paymentDAO->id = $paymentId; $paymentDAO->payment_status_id = CRM_Core_OptionGroup::getValue( 'grant_payment_status', 'Stopped', 'name' ); $paymentDAO->save(); - $paymentDAO =& new CRM_Grant_DAO_GrantPayment(); - $paymentDAO->id = $paymentId; + $paymentDAO = new CRM_Grant_DAO_GrantPayment(); + $paymentDAO->id = $paymentId; $paymentDAO->find(true); - + $payment['payment_batch_number'] = $values['payment_batch_number']; - $payment['financial_type_id'] = $values['financial_type_id']; + $payment['financial_type_id'] = $values['financial_type_id']; $payment['payment_number'] = $values['payment_number']; - $payment['contact_id'] = $paymentDAO->contact_id; + $payment['contact_id'] = $paymentDAO->contact_id; $payment['payment_created_date'] = date('m/d/Y'); $payment['payment_date'] = date("Y-m-d", strtotime($values['payment_date'])); $payment['payable_to_name'] = $paymentDAO->payable_to_name; - $payment['payable_to_address'] = $paymentDAO->payable_to_address; + $payment['payable_to_address'] = $paymentDAO->payable_to_address; $payment['amount'] = $paymentDAO->amount; - $payment['currency'] = $paymentDAO->currency; + $payment['currency'] = $paymentDAO->currency; $payment['payment_reason'] = $paymentDAO->payment_reason; $payment['payment_status_id'] = CRM_Core_OptionGroup::getValue( 'grant_payment_status', 'Reprinted', 'name' ); $payment['replaces_payment_id'] = $paymentId; - + $result = CRM_Grant_BAO_GrantPayment::add( $payment, $ids = array() ); - + $newPaymentId = $result->id; - - $entityDAO =& new CRM_Grant_DAO_EntityPayment(); + + $entityDAO = new CRM_Grant_DAO_EntityPayment(); $entityDAO->payment_id = $paymentId; $entityDAO->find(); - + while( $entityDAO->fetch() ) { - $newEntityDAO =& new CRM_Grant_DAO_EntityPayment(); + $newEntityDAO = new CRM_Grant_DAO_EntityPayment(); //$newEntityDAO->find( true ); $newEntityDAO->payment_id = $newPaymentId; $newEntityDAO->entity_table = 'civicrm_grant'; $newEntityDAO->entity_id = $entityDAO->entity_id; $newEntityDAO->save(); - $grantDAO =& new CRM_Grant_DAO_Grant(); + $grantDAO = new CRM_Grant_DAO_Grant(); $grantDAO->id = $entityDAO->entity_id; $grantDAO->find(true); - + if ( !empty( $payment_details[$newEntityDAO->payment_id] ) ) { $payment_details[$newEntityDAO->payment_id] .= ''.date("Y-m-d", strtotime($values['payment_date'])).''.$entityDAO->entity_id.''.CRM_Grant_BAO_GrantProgram::getDisplayName( $result->contact_id ).''.CRM_Utils_Money::format( $grantDAO->amount_granted,null, null,false ); } else { $payment_details[$newEntityDAO->payment_id] = date("Y-m-d", strtotime($values['payment_date'])).''.$entityDAO->entity_id.''.CRM_Grant_BAO_GrantProgram::getDisplayName( $result->contact_id ).''.CRM_Utils_Money::format( $grantDAO->amount_granted,null, null,false ); } } - + $grantPayment[$newEntityDAO->payment_id]['contact_id'] = $result->contact_id; $grantPayment[$newEntityDAO->payment_id]['financial_type_id'] = $values['financial_type_id']; $grantPayment[$newEntityDAO->payment_id]['payment_batch_number'] = $values['payment_batch_number']; @@ -218,7 +209,7 @@ class CRM_Grant_Form_Task_Reprint extends CRM_Grant_Form_PaymentTask $grantPayment[$newEntityDAO->payment_id]['payment_status_id' ] = 3; $grantPayment[$newEntityDAO->payment_id]['payment_reason' ] = $result->payment_reason; $grantPayment[$newEntityDAO->payment_id]['replaces_payment_id'] = $result->replaces_payment_id; - + foreach ( $grantPayment as $grantKey => $values ) { $row = array(); $grantValues = $values; @@ -228,7 +219,7 @@ class CRM_Grant_Form_Task_Reprint extends CRM_Grant_Form_PaymentTask $grantPayment[$grantKey]['total_in_words'] = $values['total_in_words'] = $grantValues['total_in_words'] = $amountInWords; $grantPayment[$grantKey]['amount'] = $values['amount']; } - + if ( $makePdf ) { $grantPayment[$newEntityDAO->payment_id]['payment_details'] = $payment_details[$newEntityDAO->payment_id]; $grantPayment[$newEntityDAO->payment_id]['payment_id'] = $values['payment_number']; @@ -238,9 +229,9 @@ class CRM_Grant_Form_Task_Reprint extends CRM_Grant_Form_PaymentTask $values['payment_number']++; $totalAmount += $result->amount; } - + require_once 'CRM/Grant/Form/Task/GrantPayment.php'; - + $downloadName = check_plain('grantPayment'); $downloadName .= '_'.date('Ymdhis'); $this->assign( 'date', date('Y-m-d')); @@ -252,13 +243,13 @@ class CRM_Grant_Form_Task_Reprint extends CRM_Grant_Form_PaymentTask $this->assign( 'total_payments', count($grantPayment) ); $this->assign( 'total_amount' , CRM_Utils_Money::format( $totalAmount, null, null,false ) ); $this->assign( 'domain_name', CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_Domain', CRM_Core_Config::domainID( ) , 'name' ) ); - + if( !$makePdf ) { $downloadName .= '.csv'; $fileName = CRM_Utils_File::makeFileName( $downloadName ); $config = CRM_Core_Config::singleton(); $file_name = $config->customFileUploadDir . $fileName; - CRM_Grant_BAO_GrantPayment::createCSV( $file_name, $grantPayment ); + CRM_Grant_BAO_GrantPayment::createCSV( $file_name, $grantPayment ); } else { $downloadName .= '.pdf'; $fileName = CRM_Utils_File::makeFileName( $downloadName ); @@ -269,39 +260,39 @@ class CRM_Grant_Form_Task_Reprint extends CRM_Grant_Form_PaymentTask $checkRegisterFile .= '.pdf'; $checkFile = CRM_Utils_File::makeFileName( $checkRegisterFile ); $checkRegister = CRM_Grant_BAO_GrantPayment::makeReport($checkFile, $grantPayment ); - - $fileDAO =& new CRM_Core_DAO_File(); + + $fileDAO = new CRM_Core_DAO_File(); $fileDAO->uri = $fileName; if ( $makePdf ) { $fileDAO->mime_type = 'application/pdf'; } else { $fileDAO->mime_type = 'text/x-csv'; } - $fileDAO->upload_date = date('Ymdhis'); + $fileDAO->upload_date = date('Ymdhis'); $fileDAO->save(); $grantPaymentFile = $fileDAO->id; - - $entityFileDAO =& new CRM_Core_DAO_EntityFile(); + + $entityFileDAO = new CRM_Core_DAO_EntityFile(); $entityFileDAO->entity_table = 'civicrm_contact'; $entityFileDAO->entity_id = $_SESSION[ 'CiviCRM' ][ 'userID' ]; $entityFileDAO->file_id = $grantPaymentFile; $entityFileDAO->save(); - - $fileDAO =& new CRM_Core_DAO_File(); + + $fileDAO = new CRM_Core_DAO_File(); $fileDAO->uri = $checkFile; $fileDAO->mime_type = 'application/pdf'; - $fileDAO->upload_date = date('Ymdhis'); + $fileDAO->upload_date = date('Ymdhis'); $fileDAO->save(); $grantPaymentCheckFile = $fileDAO->id; - - $entityFileDAO =& new CRM_Core_DAO_EntityFile(); + + $entityFileDAO = new CRM_Core_DAO_EntityFile(); $entityFileDAO->entity_table = 'civicrm_contact'; $entityFileDAO->entity_id = $_SESSION[ 'CiviCRM' ][ 'userID' ]; $entityFileDAO->file_id = $grantPaymentCheckFile; - $entityFileDAO->save(); + $entityFileDAO->save(); $activityStatus = CRM_Core_PseudoConstant::activityStatus('name'); $activityType = CRM_Core_PseudoConstant::activityType(); - $params = array( + $params = array( 'source_contact_id' => $_SESSION['CiviCRM']['userID'], 'activity_type_id' => array_search('Grant Payment', $activityType), 'assignee_contact_id' => array($_SESSION['CiviCRM']['userID']), @@ -316,5 +307,3 @@ class CRM_Grant_Form_Task_Reprint extends CRM_Grant_Form_PaymentTask CRM_Utils_System::redirect(CRM_Utils_System::url( 'civicrm/grant/payment/search', 'reset=1&bid='.$values['payment_batch_number'].'&download='.$fileName.'&force=1')); } } - - diff --git a/CRM/Grant/Selector/PaymentSearch.php b/CRM/Grant/Selector/PaymentSearch.php index 98f260a6c0bb6fd6394b3ab6f5a57df862b4c58d..8d7678e71fa002693f996e88c098aac52edbc9d0 100755 --- a/CRM/Grant/Selector/PaymentSearch.php +++ b/CRM/Grant/Selector/PaymentSearch.php @@ -40,7 +40,7 @@ * */ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements CRM_Core_Selector_API { - + /** * This defines two actions- View and Edit. * @@ -62,7 +62,7 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements * @var array * @static */ - static $_properties = array( + static $_properties = array( 'id', 'payable_to_name', 'payment_batch_number', @@ -72,28 +72,28 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements 'amount', ); - /** - * are we restricting ourselves to a single contact - * - * @access protected - * @var boolean - */ + /** + * are we restricting ourselves to a single contact + * + * @access protected + * @var boolean + */ protected $_single = false; - /** - * are we restricting ourselves to a single contact - * - * @access protected - * @var boolean - */ + /** + * are we restricting ourselves to a single contact + * + * @access protected + * @var boolean + */ protected $_limit = null; /** * what context are we being invoked from - * - * @access protected + * + * @access protected * @var string - */ + */ protected $_context = null; /** @@ -103,7 +103,7 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements * @var array * @access protected */ - public $_queryParams; + public $_queryParams; /** * represent the type of selector @@ -113,18 +113,18 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements */ protected $_action; - /** - * The additional clause that we restrict the search with - * - * @var string - */ + /** + * The additional clause that we restrict the search with + * + * @var string + */ protected $_grantClause = null; - /** + /** * The query object - * - * @var string - */ + * + * @var string + */ protected $_query; /** @@ -132,7 +132,7 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements * * @param array $queryParams array of parameters for query * @param int $action - action of search basic or advanced. - * @param string $grantClause if the caller wants to further restrict the search + * @param string $grantClause if the caller wants to further restrict the search * @param boolean $single are we dealing only with one contact? * @param int $limit how many participations do we want returned * @@ -145,11 +145,11 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements $grantClause = NULL, $single = FALSE, $limit = NULL, - $context = 'search' + $context = 'search' ) { // submitted form values $this->_queryParams =& $queryParams; - + $this->_single = $single; $this->_limit = $limit; @@ -160,24 +160,24 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements // type of selector $this->_action = $action; - $this->_query = new CRM_Grant_BAO_PaymentSearch( - $this->_queryParams, - NULL, - NULL, - FALSE, + $this->_query = new CRM_Grant_BAO_PaymentSearch( + $this->_queryParams, + NULL, + NULL, + FALSE, FALSE, - CRM_Grant_BAO_PaymentSearch::MODE_GRANT_PAYMENT + CRM_Grant_BAO_PaymentSearch::MODE_GRANT_PAYMENT ); - - $this->_query->_distinctComponentClause = " civicrm_payment.id"; - $this->_query->_groupByComponentClause = " GROUP BY civicrm_payment.id"; - + + $this->_query->_distinctComponentClause = " ft.id"; + $this->_query->_groupByComponentClause = " GROUP BY ft.id"; + } /** * This method returns the links that are given for each search row. - * currently the links added for each row are - * + * currently the links added for each row are + * * - View * - Edit * @@ -185,10 +185,10 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements * @access public * */ - static function &links($key = NULL) { + static function &links($key = NULL) { $id = CRM_Utils_Request::retrieve('id', 'Integer', $this); $extraParams = ($key) ? "&key={$key}" : NULL; - + if (!(self::$_links)) { self::$_links = array( CRM_Core_Action::VIEW => array( @@ -196,38 +196,38 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements 'url' => 'civicrm/grant/payment', 'qs' => 'reset=1&id=%%id%%&action=view&context=%%cxt%%&selectedChild=grant' . $extraParams, 'title' => ts('View Grant'), - ), - CRM_Core_Action::STOP => array( + ), + 121 => array( 'name' => ts('Stop'), 'url' => 'civicrm/grant/payment', 'qs' => 'reset=1&action=stop&id=%%id%%&context=%%cxt%%' . $extraParams, 'title' => ts('Edit Grant'), ), - CRM_Core_Action::REPRINT => array( + 1212 => array( 'name' => ts('Reprint'), 'url' => 'civicrm/grant/payment', 'qs' => 'reset=1&action=reprint&id=%%id%%&context=%%cxt%%' . $extraParams, 'title' => ts('Edit Grant'), ), - CRM_Core_Action::WITHDRAW => array( + 12121 => array( 'name' => ts('Withdraw'), 'url' => 'civicrm/grant/payment', 'qs' => 'reset=1&action=withdraw&id=%%id%%&context=%%cxt%%' . $extraParams, 'title' => ts('Edit Grant'), ), ); - - self::$_links = self::$_links; + + self::$_links = self::$_links; } - - + + return self::$_links; - } - + } + /** * getter for array of the parameters required for creating pager. * - * @param + * @param * @access public */ function getPagerParams($action, &$params) { @@ -235,7 +235,7 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements $params['csvString'] = null; if ($this->_limit) { $params['rowCount'] = $this->_limit; - } + } else { $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT; } @@ -243,29 +243,29 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements $params['buttonTop'] = 'PagerTopButton'; $params['buttonBottom'] = 'PagerBottomButton'; } - + /** * Returns total number of rows for the query. * - * @param - * @return int Total number of rows + * @param + * @return int Total number of rows * @access public */ - function getTotalCount($action) { - return $this->_query->searchQuery( - 0, - 0, + function getTotalCount($action) { + return $this->_query->searchQuery( + 0, + 0, NULL, - TRUE, - FALSE, - FALSE, - FALSE, - FALSE, - $this->_grantClause + TRUE, + FALSE, + FALSE, + FALSE, + FALSE, + $this->_grantClause ); - + } - + /** * returns all the rows in the given offset and rowCount * * @param enum $action the action being performed @@ -276,22 +276,22 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements * * @return int the total number of rows for this action */ - function &getRows($action, $offset, $rowCount, $sort, $output = NULL) { - $result = $this->_query->searchQuery( - $offset, - $rowCount, + function &getRows($action, $offset, $rowCount, $sort, $output = NULL) { + $result = $this->_query->searchQuery( + $offset, + $rowCount, $sort, - FALSE, - FALSE, FALSE, - FALSE, - FALSE, - $this->_grantClause + FALSE, + FALSE, + FALSE, + FALSE, + $this->_grantClause ); - + // process the result of the query $rows = array(); - + //CRM-4418 check for view, edit, delete $permissions = array(CRM_Core_Permission::VIEW); if (CRM_Core_Permission::check('edit grants')) { @@ -300,18 +300,18 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements if (CRM_Core_Permission::check('delete in CiviGrant')) { $permissions[] = CRM_Core_Permission::DELETE; } - $mask = CRM_Core_Action::mask($permissions); - + $mask = CRM_Core_Action::mask($permissions); + while ($result->fetch()) { $row = array(); - + // the columns we are interested in foreach (self::$_properties as $property) { if (isset($result->$property)) { if ($property == 'payment_status_id') { $paymentStatus = CRM_Core_OptionGroup::values('grant_payment_status'); $row[$property] = $paymentStatus[$result->$property]; - } + } else { $row[$property] = $result->$property; } @@ -320,50 +320,50 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements if ($this->_context == 'search') { $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->id; } - $this->id = $result->id; + $this->id = $result->id; $link = self::links( $this->_key); if ( $result->payment_status_id == 2 || $result->payment_status_id == 4 ) { - unset($link[CRM_Core_Action::STOP]); - unset($link[CRM_Core_Action::REPRINT]); - unset($link[CRM_Core_Action::WITHDRAW]); + unset($link[121]); + unset($link[1212]); + unset($link[12121]); } - - $row['action'] = CRM_Core_Action::formLink( - $link, + + $row['action'] = CRM_Core_Action::formLink( + $link, $mask, - array( + array( 'id' => $result->id, - 'cxt' => $this->_context - ) + 'cxt' => $this->_context + ) ); $rows[] = $row; } return $rows; } - + /** * @return array $qill which contains an array of strings * @access public */ - + // the current internationalisation is bad, but should more or less work // for most of "European" languages - public function getQILL() { + public function getQILL() { return $this->_query->qill(); } - - /** - * returns the column headers as an array of tuples: - * (name, sortName (key to the sort array)) - * - * @param string $action the action being performed - * @param enum $output what should the result set include (web/email/csv) - * - * @return array the column headers that need to be displayed - * @access public - */ - public function &getColumnHeaders( $action = NULL, $output = NULL) { + + /** + * returns the column headers as an array of tuples: + * (name, sortName (key to the sort array)) + * + * @param string $action the action being performed + * @param enum $output what should the result set include (web/email/csv) + * + * @return array the column headers that need to be displayed + * @access public + */ + public function &getColumnHeaders( $action = NULL, $output = NULL) { if (!isset(self::$_columnHeaders)) { self::$_columnHeaders = array( array( @@ -377,7 +377,7 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements 'direction' => CRM_Utils_Sort::DONTCARE, ), array( - 'name' => ts('Payment Number'), + 'name' => ts('Check Number'), 'sort' => 'payment_number', 'direction' => CRM_Utils_Sort::DONTCARE, ), @@ -388,12 +388,12 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements ), array( 'name' => ts('Payee name'), - 'sort' => 'payable_to_name', + 'sort' => 'payable_to_name', 'direction' => CRM_Utils_Sort::DONTCARE, ), array( 'name' => ts('Amount'), - 'sort' => 'amount', + 'sort' => 'amount', 'direction' => CRM_Utils_Sort::DONTCARE, ), array('desc' => ts('Actions')), @@ -401,21 +401,19 @@ class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements } return self::$_columnHeaders; } - + function &getQuery() { return $this->_query; } - /** - * name of export file. - * - * @param string $output type of output - * @return string name of the file - */ - function getExportFileName($output = 'csv') { - return ts('CiviCRM Grant Search'); - } + /** + * name of export file. + * + * @param string $output type of output + * @return string name of the file + */ + function getExportFileName($output = 'csv') { + return ts('CiviCRM Grant Search'); + } } - - diff --git a/CRM/Grant/Words.php b/CRM/Grant/Words.php deleted file mode 100755 index e695533f6aa474f042b48f86cc59e7ce61c5aad3..0000000000000000000000000000000000000000 --- a/CRM/Grant/Words.php +++ /dev/null @@ -1,151 +0,0 @@ - 'zero', - 1 => 'one', - 2 => 'two', - 3 => 'three', - 4 => 'four', - 5 => 'five', - 6 => 'six', - 7 => 'seven', - 8 => 'eight', - 9 => 'nine', - 10 => 'ten', - 11 => 'eleven', - 12 => 'twelve', - 13 => 'thirteen', - 14 => 'fourteen', - 15 => 'fifteen', - 16 => 'sixteen', - 17 => 'seventeen', - 18 => 'eighteen', - 19 => 'nineteen', - 20 => 'twenty', - 30 => 'thirty', - 40 => 'fourty', - 50 => 'fifty', - 60 => 'sixty', - 70 => 'seventy', - 80 => 'eighty', - 90 => 'ninety', - 100 => 'hundred', - 1000 => 'thousand', - 1000000 => 'million', - 1000000000 => 'billion', - 1000000000000 => 'trillion', - 1000000000000000 => 'quadrillion', - 1000000000000000000 => 'quintillion' - ); - - if (!is_numeric($number)) { - return FALSE; - } - - if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) { - // overflow - trigger_error( - 'convert_number_to_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX, - E_USER_WARNING - ); - return FALSE; - } - - if ($number < 0) { - return $negative . convert_number_to_words(abs($number)); - } - - $string = $fraction = NULL; - - if (strpos($number, '.') !== FALSE) { - list($number, $fraction) = explode('.', $number); - } - - switch (TRUE) { - case $number < 21: - $string = $dictionary[$number]; - break; - case $number < 100: - $tens = ((int) ($number / 10)) * 10; - $units = $number % 10; - $string = $dictionary[$tens]; - if ($units) { - $string .= $hyphen . $dictionary[$units]; - } - break; - case $number < 1000: - $hundreds = $number / 100; - $remainder = $number % 100; - $string = $dictionary[$hundreds] . ' ' . $dictionary[100]; - if ($remainder) { - - $string .= $conjunction . self::convert_number_to_words(abs($remainder)); - } - break; - default: - $baseUnit = pow(1000, floor(log($number, 1000))); - $numBaseUnits = (int) ($number / $baseUnit); - $remainder = $number % $baseUnit; - $string = self::convert_number_to_words($numBaseUnits) . ' ' . $dictionary[$baseUnit]; - if ($remainder) { - $string .= $remainder < 100 ? $conjunction : $separator; - $string .= self::convert_number_to_words($remainder); - } - break; - } - - if (NULL !== $fraction && is_numeric($fraction)) { - $string .= $decimal; - $string .= $fraction . '/100'; - } - return $string; - } -} \ No newline at end of file diff --git a/grantprograms.php b/grantprograms.php index cc5f85ffd9790dbc76edfa3bcfce692e58ba7be4..5704ebbccef549f2667fac84df435474fae8c106 100644 --- a/grantprograms.php +++ b/grantprograms.php @@ -287,6 +287,7 @@ function grantprograms_civicrm_buildForm($formName, &$form) { $form->assign('grantUrl', $grantUrl); } + if ($formName == 'CRM_Grant_Form_Grant' && ($form->getVar('_action') != CRM_Core_Action::DELETE)) { $form->_key = CRM_Utils_Request::retrieve('key', 'String', $form); $form->_next = CRM_Utils_Request::retrieve('next', 'Positive', $form); @@ -682,7 +683,7 @@ function grantprograms_civicrm_pre($op, $objectName, $id, &$params) { $params['id'] = $id; } if (($grantStatusApproved == CRM_Utils_Array::value('status_id', $params) && empty($params['decision_date'])) || - (empty($previousGrant['decision_date']) && $previousGrant['status_id'] != CRM_Utils_Array::value('status_id', $params)) + (empty($previousGrant['decision_date']) && CRM_Utils_Array::value('status_id', $previousGrant) != CRM_Utils_Array::value('status_id', $params)) ) { $params['decision_date'] = date('Ymd'); } @@ -793,12 +794,12 @@ function grantprograms_civicrm_post($op, $objectName, $objectId, &$objectRef) { $statusID = array_search('Pending', $contributionStatuses); } elseif ($objectRef->status_id == array_search('Paid', $grantStatuses)) { - $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($objectRef->financial_type_id, 'Asset Account is') ?: getAssetFinancialAccountID(); + $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($objectRef->financial_type_id, 'Asset Account is') ?: CRM_Grant_BAO_GrantProgram::getAssetFinancialAccountID(); $statusID = array_search('Completed', $contributionStatuses); $createItem = empty($previousGrant); } elseif ($op == 'edit' && $objectRef->status_id == array_search('Withdrawn', $grantStatuses)) { - $params['to_financial_account_id'] = getAssetFinancialAccountID(); + $params['to_financial_account_id'] = CRM_Grant_BAO_GrantProgram::getAssetFinancialAccountID(); $params['from_financial_account_id'] = CRM_Core_DAO::singleValueQuery(" SELECT to_financial_account_id FROM civicrm_financial_trxn cft INNER JOIN civicrm_entity_financial_trxn ecft ON ecft.financial_trxn_id = cft.id @@ -849,14 +850,6 @@ function grantprograms_civicrm_post($op, $objectName, $objectId, &$objectRef) { } } -function getAssetFinancialAccountID() { - $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' ")); - return CRM_Core_DAO::singleValueQuery( - "SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", - [1 => [$relationTypeId, 'Integer']] - ); -} - /* * hook_civicrm_postProcess * diff --git a/sql/grantprograms_install.sql b/sql/grantprograms_install.sql index fa57832198d568897210125abb1067d5d0f12033..026a2ad7c5ef7221cc6828f4b2a6938a5d28c606 100755 --- a/sql/grantprograms_install.sql +++ b/sql/grantprograms_install.sql @@ -29,16 +29,8 @@ -- create civicrm_payment table. CREATE TABLE IF NOT EXISTS `civicrm_payment` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id', - `payment_batch_number` int(10) unsigned NOT NULL COMMENT 'Payment Batch Nnumber', - `payment_number` int(10) unsigned NOT NULL COMMENT 'Payment Number', - `financial_type_id` int(10) unsigned NOT NULL COMMENT 'Financial Type ID', - `contact_id` int(10) unsigned NOT NULL COMMENT 'Contact ID', + `financial_trxn_id` int(10) unsigned NOT NULL COMMENT 'Financial Trxn ID', `payment_created_date` date DEFAULT NULL COMMENT 'Payment Created Date.', - `payment_date` date DEFAULT NULL COMMENT 'Payment Date.', - `payable_to_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Payable To Name.', - `payable_to_address` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Payable To Address.', - `amount` decimal(20,2) NOT NULL COMMENT 'Requested grant amount, in default currency.', - `currency` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '3 character string, value from config setting or input via user.', `payment_reason` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Payment Reason.', `payment_status_id` int(10) unsigned DEFAULT NULL COMMENT 'Payment Status ID', `replaces_payment_id` varchar(8) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Replaces Payment Id.', diff --git a/templates/CRM/Grant/Form/Task/GrantPayment.tpl b/templates/CRM/Grant/Form/Task/GrantPayment.tpl index e016f439affaf57adeb0fba7c65e4b663ae18804..31098c88552471608547f5d4bf3dfd6e056864e0 100755 --- a/templates/CRM/Grant/Form/Task/GrantPayment.tpl +++ b/templates/CRM/Grant/Form/Task/GrantPayment.tpl @@ -25,41 +25,17 @@ *} {* this template is used for adding/editing/deleting financial type *} -

{ts}Pay Grants{/ts}

+

{ts}Pay Grants{/ts}

{include file="CRM/common/formButtons.tpl" location="top"}
- - - + {foreach from=$paymentFields key=fieldName item=paymentField} + {assign var='name' value=$fieldName} + + + - - - - - - - - - - - - - - - - - - - - -
{$form.financial_type_id.label}{$form.financial_type_id.html}
{$form.$name.label}{$form.$name.html}
{$form.payment_batch_number.label}{$form.payment_batch_number.html}
{$form.number_checks.label}{$form.number_checks.html}
{$form.payment_number.label}{$form.payment_number.html}
{$form.payment_date.label} - {if $hideCalendar neq true} - {include file="CRM/common/jcalendar.tpl" elementName=payment_date} - {else} - {$form.payment_date.html|crmDate} - {/if} -
{$form.download_file.label}{$form.download_file.html}
- + {/foreach} +
{include file="CRM/common/formButtons.tpl" location="botttom"}