3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2016
39 * @author Marshal Newrock <marshal@idealso.com>
44 * Business objects for Line Items generated by monetary transactions
46 class CRM_Price_BAO_LineItem
extends CRM_Price_DAO_LineItem
{
49 * Creates a new entry in the database.
51 * @param array $params
52 * (reference) an assoc array of name/value pairs.
54 * @return CRM_Price_DAO_LineItem
56 public static function create(&$params) {
57 $id = CRM_Utils_Array
::value('id', $params);
59 CRM_Utils_Hook
::pre('edit', 'LineItem', $id, $params);
60 $op = CRM_Core_Action
::UPDATE
;
63 CRM_Utils_Hook
::pre('create', 'LineItem', $params['entity_id'], $params);
64 $op = CRM_Core_Action
::ADD
;
67 // unset entity table and entity id in $params
68 // we never update the entity table and entity id during update mode
70 unset($params['entity_id'], $params['entity_table']);
72 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus() && CRM_Utils_Array
::value('check_permissions', $params)) {
73 if (empty($params['financial_type_id'])) {
74 throw new Exception('Mandatory key(s) missing from params array: financial_type_id');
76 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($types, $op);
77 if (!in_array($params['financial_type_id'], array_keys($types))) {
78 throw new Exception('You do not have permission to create this line item');
82 $lineItemBAO = new CRM_Price_BAO_LineItem();
83 $lineItemBAO->copyValues($params);
85 $return = $lineItemBAO->save();
86 if ($lineItemBAO->entity_table
== 'civicrm_membership' && $lineItemBAO->contribution_id
&& $lineItemBAO->entity_id
) {
87 $membershipPaymentParams = array(
88 'membership_id' => $lineItemBAO->entity_id
,
89 'contribution_id' => $lineItemBAO->contribution_id
,
91 if (!civicrm_api3('MembershipPayment', 'getcount', $membershipPaymentParams)) {
92 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
97 CRM_Utils_Hook
::post('edit', 'LineItem', $id, $lineItemBAO);
100 CRM_Utils_Hook
::post('create', 'LineItem', $lineItemBAO->id
, $lineItemBAO);
107 * Retrieve DB object based on input parameters.
109 * It also stores all the retrieved values in the default array.
111 * @param array $params
112 * (reference ) an assoc array of name/value pairs.
113 * @param array $defaults
114 * (reference ) an assoc array to hold the flattened values.
116 * @return CRM_Price_BAO_LineItem
118 public static function retrieve(&$params, &$defaults) {
119 $lineItem = new CRM_Price_BAO_LineItem();
120 $lineItem->copyValues($params);
121 if ($lineItem->find(TRUE)) {
122 CRM_Core_DAO
::storeValues($lineItem, $defaults);
129 * Modifies $params array for filtering financial types.
131 * @param array $params
132 * (reference ) an assoc array of name/value pairs.
135 public static function getAPILineItemParams(&$params) {
136 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($types);
137 if ($types && empty($params['financial_type_id'])) {
138 $params['financial_type_id'] = array('IN' => array_keys($types));
141 if (is_array($params['financial_type_id'])) {
142 $invalidFts = array_diff($params['financial_type_id'], array_keys($types));
144 elseif (!in_array($params['financial_type_id'], array_keys($types))) {
145 $invalidFts = $params['financial_type_id'];
148 $params['financial_type_id'] = array('NOT IN' => $invalidFts);
152 $params['financial_type_id'] = 0;
157 * @param int $entityId
158 * @param $entityTable
160 * @return null|string
162 public static function getLineTotal($entityId, $entityTable) {
163 $sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
164 FROM civicrm_line_item li
165 WHERE li.entity_table = '{$entityTable}'
166 AND li.entity_id = {$entityId}
168 $lineItemTotal = CRM_Core_DAO
::singleValueQuery($sqlLineItemTotal);
169 return $lineItemTotal;
173 * Wrapper for line item retrieval when contribution ID is known.
174 * @param int $contributionID
178 public static function getLineItemsByContributionID($contributionID) {
179 return self
::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
183 * Given a participant id/contribution id,
184 * return contribution/fee line items
186 * @param int $entityId
187 * participant/contribution id.
188 * @param string $entity
189 * participant/contribution.
191 * @param null $isQuick
192 * @param bool $isQtyZero
193 * @param bool $relatedEntity
195 * @param string $overrideWhereClause
196 * E.g "WHERE contribution id = 7 " per the getLineItemsByContributionID wrapper.
197 * this function precedes the convenience of the contribution id but since it does quite a bit more than just a db retrieval we need to be able to use it even
198 * when we don't want it's entity-id magix
200 * @param bool $invoice
202 * Array of line items
204 public static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL, $isQtyZero = TRUE, $relatedEntity = FALSE, $overrideWhereClause = '', $invoice = FALSE) {
205 $whereClause = $fromClause = NULL;
215 pf.label as field_title,
217 pfv.membership_type_id,
218 pfv.membership_num_terms,
220 li.participant_count,
221 li.price_field_value_id,
222 li.financial_type_id,
226 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
227 if ($relatedEntity) {
228 $condition = "li.contribution_id = %2.id ";
232 FROM civicrm_%2 as %2
233 LEFT JOIN civicrm_line_item li ON ({$condition})
234 LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )
235 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
239 // CRM-16250 get additional participant's fee selection details only for invoice PDF (if any)
240 if ($entity == 'participant' && $invoice) {
241 $additionalParticipantIDs = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
242 if (!empty($additionalParticipantIDs)) {
243 $whereClause = "WHERE %2.id IN (%1, " . implode(', ', $additionalParticipantIDs) . ")";
247 $orderByClause = " ORDER BY pf.weight, pfv.weight";
250 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
251 $whereClause .= " and cps.is_quick_config = 0";
255 $whereClause .= " and li.qty != 0";
258 $lineItems = array();
260 if (!$entityId ||
!$entity ||
!$fromClause) {
265 1 => array($entityId, 'Integer'),
266 2 => array($entity, 'Text'),
269 $getTaxDetails = FALSE;
270 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
271 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
272 if ($overrideWhereClause) {
273 $whereClause = $overrideWhereClause;
276 $dao = CRM_Core_DAO
::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
277 while ($dao->fetch()) {
281 $lineItems[$dao->id
] = array(
282 'qty' => (float) $dao->qty
,
283 'label' => $dao->label
,
284 'unit_price' => $dao->unit_price
,
285 'line_total' => $dao->line_total
,
286 'price_field_id' => $dao->price_field_id
,
287 'participant_count' => $dao->participant_count
,
288 'price_field_value_id' => $dao->price_field_value_id
,
289 'field_title' => $dao->field_title
,
290 'html_type' => $dao->html_type
,
291 'description' => $dao->description
,
292 // the entity id seems prone to randomness but not sure if it has a reason - so if we are overriding the Where clause we assume
293 // we also JUST WANT TO KNOW the the entity_id in the DB
294 'entity_id' => empty($overrideWhereClause) ?
$entityId : $dao->entity_id
,
295 'entity_table' => $dao->entity_table
,
296 'contribution_id' => $dao->contribution_id
,
297 'financial_type_id' => $dao->financial_type_id
,
298 'financial_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'financial_type_id', $dao->financial_type_id
),
299 'membership_type_id' => $dao->membership_type_id
,
300 'membership_num_terms' => $dao->membership_num_terms
,
301 'tax_amount' => $dao->tax_amount
,
303 $lineItems[$dao->id
]['tax_rate'] = CRM_Price_BAO_LineItem
::calculateTaxRate($lineItems[$dao->id
]);
304 $lineItems[$dao->id
]['subTotal'] = $lineItems[$dao->id
]['qty'] * $lineItems[$dao->id
]['unit_price'];
305 if ($lineItems[$dao->id
]['tax_amount'] != '') {
306 $getTaxDetails = TRUE;
310 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
311 $smarty = CRM_Core_Smarty
::singleton();
312 $smarty->assign('taxTerm', $taxTerm);
313 $smarty->assign('getTaxDetails', $getTaxDetails);
319 * This method will create the lineItem array required for
320 * processAmount method
323 * Price set field id.
324 * @param array $params
325 * Reference to form values.
326 * @param array $fields
327 * Array of fields belonging to the price set used for particular event
328 * @param array $values
329 * Reference to the values array(.
332 * @param string $amount_override
334 public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
335 if (empty($params["price_{$fid}"])) {
339 //lets first check in fun parameter,
340 //since user might modified w/ hooks.
342 if (array_key_exists('options', $fields)) {
343 $options = $fields['options'];
346 CRM_Price_BAO_PriceFieldValue
::getValues($fid, $options, 'weight', TRUE);
348 $fieldTitle = CRM_Utils_Array
::value('label', $fields);
350 $fieldTitle = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
353 foreach ($params["price_{$fid}"] as $oid => $qty) {
354 $price = $amount_override === NULL ?
$options[$oid]['amount'] : $amount_override;
356 // lets clean the price in case it is not yet cleant
358 $price = CRM_Utils_Rule
::cleanMoney($price);
360 $participantsPerField = CRM_Utils_Array
::value('count', $options[$oid], 0);
362 $values[$oid] = array(
363 'price_field_id' => $fid,
364 'price_field_value_id' => $oid,
365 'label' => CRM_Utils_Array
::value('label', $options[$oid]),
366 'field_title' => $fieldTitle,
367 'description' => CRM_Utils_Array
::value('description', $options[$oid]),
369 'unit_price' => $price,
370 'line_total' => $qty * $price,
371 'participant_count' => $qty * $participantsPerField,
372 'max_value' => CRM_Utils_Array
::value('max_value', $options[$oid]),
373 'membership_type_id' => CRM_Utils_Array
::value('membership_type_id', $options[$oid]),
374 'membership_num_terms' => CRM_Utils_Array
::value('membership_num_terms', $options[$oid]),
375 'auto_renew' => CRM_Utils_Array
::value('auto_renew', $options[$oid]),
376 'html_type' => $fields['html_type'],
377 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $options[$oid]),
378 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $options[$oid]),
379 'non_deductible_amount' => CRM_Utils_Array
::value('non_deductible_amount', $options[$oid]),
382 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
383 $values[$oid]['auto_renew'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
389 * Delete line items for given entity.
391 * @param int $entityId
392 * @param int $entityTable
396 public static function deleteLineItems($entityId, $entityTable) {
397 if (!$entityId ||
!$entityTable) {
401 if ($entityId && !is_array($entityId)) {
402 $entityId = array($entityId);
405 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
406 $dao = CRM_Core_DAO
::executeQuery($query);
411 * Process price set and line items.
413 * @param int $entityId
414 * @param array $lineItem
416 * @param object $contributionDetails
417 * @param string $entityTable
420 * @param bool $update
424 public static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
425 if (!$entityId ||
!is_array($lineItem)
426 || CRM_Utils_system
::isNull($lineItem)
431 foreach ($lineItem as $priceSetId => &$values) {
436 foreach ($values as &$line) {
437 if (empty($line['entity_table'])) {
438 $line['entity_table'] = $entityTable;
440 if (empty($line['entity_id'])) {
441 $line['entity_id'] = $entityId;
443 if (!empty($line['membership_type_id'])) {
444 $line['entity_table'] = 'civicrm_membership';
446 if (!empty($contributionDetails->id
)) {
447 $line['contribution_id'] = $contributionDetails->id
;
448 if ($line['entity_table'] == 'civicrm_contribution') {
449 $line['entity_id'] = $contributionDetails->id
;
451 // CRM-19094: entity_table is set to civicrm_membership then ensure
452 // the entityId is set to membership ID not contribution by default
453 elseif ($line['entity_table'] == 'civicrm_membership' && !empty($line['entity_id']) && $line['entity_id'] == $contributionDetails->id
) {
454 $membershipId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', 'contribution_id', $line['entity_id'], 'membership_id');
455 $line['entity_id'] = $membershipId ?
$membershipId : $line['entity_id'];
459 // if financial type is not set and if price field value is NOT NULL
460 // get financial type id of price field value
461 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
462 $line['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
464 $lineItems = CRM_Price_BAO_LineItem
::create($line);
465 if (!$update && $contributionDetails) {
466 $financialItem = CRM_Financial_BAO_FinancialItem
::add($lineItems, $contributionDetails);
467 $line['financial_item_id'] = $financialItem->id
;
468 if (!empty($line['tax_amount'])) {
469 CRM_Financial_BAO_FinancialItem
::add($lineItems, $contributionDetails, TRUE);
474 if (!$update && $contributionDetails) {
475 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn($lineItem, $contributionDetails);
480 * @param int $entityId
481 * @param string $entityTable
483 * @param array $otherParams
485 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
486 if (!$entityId || CRM_Utils_System
::isNull($amount)) {
490 $from = " civicrm_line_item li
491 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
492 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
494 $set = " li.unit_price = %3,
495 li.line_total = %3 ";
497 $where = " li.entity_id = %1 AND
498 li.entity_table = %2 ";
501 1 => array($entityId, 'Integer'),
502 2 => array($entityTable, 'String'),
503 3 => array($amount, 'Float'),
506 if ($entityTable == 'civicrm_contribution') {
507 $entityName = 'default_contribution_amount';
508 $where .= " AND ps.name = %4 ";
509 $params[4] = array($entityName, 'String');
511 elseif ($entityTable == 'civicrm_participant') {
513 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
514 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
515 $set .= " ,li.label = %4,
516 li.price_field_value_id = cpfv.id ";
517 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
518 $amount = empty($amount) ?
0 : $amount;
520 4 => array($otherParams['fee_label'], 'String'),
521 5 => array($otherParams['event_id'], 'String'),
531 CRM_Core_DAO
::executeQuery($query, $params);
535 * Build line items array.
537 * @param array $params
540 * @param string $entityId
543 * @param string $entityTable
546 * @param bool $isRelatedID
548 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
551 $priceSetDetails = CRM_Price_BAO_PriceSet
::getDefaultPriceSet($entityTable);
552 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
553 $financialType = CRM_Utils_Array
::value('financial_type_id', $params);
554 foreach ($priceSetDetails as $values) {
555 if ($entityTable == 'membership') {
556 if ($isRelatedID != $values['membership_type_id']) {
560 $totalAmount = $values['amount'];
562 $financialType = $values['financial_type_id'];
564 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
565 'price_field_id' => $values['priceFieldID'],
566 'price_field_value_id' => $values['priceFieldValueID'],
567 'label' => $values['label'],
569 'unit_price' => $totalAmount,
570 'line_total' => $totalAmount,
571 'financial_type_id' => $financialType,
572 'membership_type_id' => $values['membership_type_id'],
579 $totalEntityId = count($entityId);
580 if ($entityTable == 'contribution') {
583 foreach ($entityId as $id) {
584 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($id, $entityTable, NULL, TRUE, $isRelatedID);
585 foreach ($lineItems as $key => $values) {
586 if (!$setID && $values['price_field_id']) {
587 $setID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
588 $params['is_quick_config'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
590 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
591 && $totalEntityId == 1
593 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
595 $values['id'] = $key;
596 $params['line_item'][$setID][$key] = $values;
603 * Calculate tax rate in percentage.
605 * @param array $lineItemId
606 * An assoc array of lineItem.
611 public static function calculateTaxRate($lineItemId) {
612 if ($lineItemId['unit_price'] == 0 ||
$lineItemId['qty'] == 0) {
615 if ($lineItemId['html_type'] == 'Text') {
616 $tax = round($lineItemId['tax_amount'] / ($lineItemId['unit_price'] * $lineItemId['qty']) * 100, 2);
619 $tax = round(($lineItemId['tax_amount'] / $lineItemId['unit_price']) * 100, 2);