Merge pull request #9443 from agh1/4.7.14-releasenotes
[civicrm-core.git] / CRM / Price / BAO / LineItem.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2016
32 * $Id$
33 *
34 */
35
36 /**
37 *
38 * @package CRM
39 * @author Marshal Newrock <marshal@idealso.com>
40 * $Id$
41 */
42
43 /**
44 * Business objects for Line Items generated by monetary transactions
45 */
46 class CRM_Price_BAO_LineItem extends CRM_Price_DAO_LineItem {
47
48 /**
49 * Creates a new entry in the database.
50 *
51 * @param array $params
52 * (reference) an assoc array of name/value pairs.
53 *
54 * @return \CRM_Price_DAO_LineItem
55 *
56 * @throws \CiviCRM_API3_Exception
57 * @throws \Exception
58 */
59 public static function create(&$params) {
60 $id = CRM_Utils_Array::value('id', $params);
61 if ($id) {
62 CRM_Utils_Hook::pre('edit', 'LineItem', $id, $params);
63 $op = CRM_Core_Action::UPDATE;
64 }
65 else {
66 CRM_Utils_Hook::pre('create', 'LineItem', $params['entity_id'], $params);
67 $op = CRM_Core_Action::ADD;
68 }
69
70 // unset entity table and entity id in $params
71 // we never update the entity table and entity id during update mode
72 if ($id) {
73 unset($params['entity_id'], $params['entity_table']);
74 }
75 else {
76 if (!isset($params['unit_price'])) {
77 $params['unit_price'] = 0;
78 }
79 }
80 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && CRM_Utils_Array::value('check_permissions', $params)) {
81 if (empty($params['financial_type_id'])) {
82 throw new Exception('Mandatory key(s) missing from params array: financial_type_id');
83 }
84 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types, $op);
85 if (!in_array($params['financial_type_id'], array_keys($types))) {
86 throw new Exception('You do not have permission to create this line item');
87 }
88 }
89
90 $lineItemBAO = new CRM_Price_BAO_LineItem();
91 $lineItemBAO->copyValues($params);
92
93 $return = $lineItemBAO->save();
94 if ($lineItemBAO->entity_table == 'civicrm_membership' && $lineItemBAO->contribution_id && $lineItemBAO->entity_id) {
95 $membershipPaymentParams = array(
96 'membership_id' => $lineItemBAO->entity_id,
97 'contribution_id' => $lineItemBAO->contribution_id,
98 );
99 if (!civicrm_api3('MembershipPayment', 'getcount', $membershipPaymentParams)) {
100 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
101 }
102 }
103
104 if ($id) {
105 CRM_Utils_Hook::post('edit', 'LineItem', $id, $lineItemBAO);
106 }
107 else {
108 CRM_Utils_Hook::post('create', 'LineItem', $lineItemBAO->id, $lineItemBAO);
109 }
110
111 return $return;
112 }
113
114 /**
115 * Retrieve DB object based on input parameters.
116 *
117 * It also stores all the retrieved values in the default array.
118 *
119 * @param array $params
120 * (reference ) an assoc array of name/value pairs.
121 * @param array $defaults
122 * (reference ) an assoc array to hold the flattened values.
123 *
124 * @return CRM_Price_BAO_LineItem
125 */
126 public static function retrieve(&$params, &$defaults) {
127 $lineItem = new CRM_Price_BAO_LineItem();
128 $lineItem->copyValues($params);
129 if ($lineItem->find(TRUE)) {
130 CRM_Core_DAO::storeValues($lineItem, $defaults);
131 return $lineItem;
132 }
133 return NULL;
134 }
135
136 /**
137 * Modifies $params array for filtering financial types.
138 *
139 * @param array $params
140 * (reference ) an assoc array of name/value pairs.
141 *
142 */
143 public static function getAPILineItemParams(&$params) {
144 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types);
145 if ($types && empty($params['financial_type_id'])) {
146 $params['financial_type_id'] = array('IN' => array_keys($types));
147 }
148 elseif ($types) {
149 if (is_array($params['financial_type_id'])) {
150 $invalidFts = array_diff($params['financial_type_id'], array_keys($types));
151 }
152 elseif (!in_array($params['financial_type_id'], array_keys($types))) {
153 $invalidFts = $params['financial_type_id'];
154 }
155 if ($invalidFts) {
156 $params['financial_type_id'] = array('NOT IN' => $invalidFts);
157 }
158 }
159 else {
160 $params['financial_type_id'] = 0;
161 }
162 }
163
164 /**
165 * @param int $entityId
166 * @param $entityTable
167 *
168 * @return null|string
169 */
170 public static function getLineTotal($entityId, $entityTable) {
171 $sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
172 FROM civicrm_line_item li
173 WHERE li.entity_table = '{$entityTable}'
174 AND li.entity_id = {$entityId}
175 ";
176 $lineItemTotal = CRM_Core_DAO::singleValueQuery($sqlLineItemTotal);
177 return $lineItemTotal;
178 }
179
180 /**
181 * Wrapper for line item retrieval when contribution ID is known.
182 * @param int $contributionID
183 *
184 * @return array
185 */
186 public static function getLineItemsByContributionID($contributionID) {
187 return self::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
188 }
189
190 /**
191 * Given a participant id/contribution id,
192 * return contribution/fee line items
193 *
194 * @param int $entityId
195 * participant/contribution id.
196 * @param string $entity
197 * participant/contribution.
198 *
199 * @param bool $isQuick
200 * @param bool $isQtyZero
201 * @param bool $relatedEntity
202 *
203 * @param bool $invoice
204 * @return array
205 * Array of line items
206 */
207 public static function getLineItems($entityId, $entity = 'participant', $isQuick = FALSE, $isQtyZero = TRUE, $relatedEntity = FALSE, $invoice = FALSE) {
208 $whereClause = $fromClause = NULL;
209 $selectClause = "
210 SELECT li.id,
211 li.label,
212 li.contribution_id,
213 li.qty,
214 li.unit_price,
215 li.line_total,
216 li.entity_table,
217 li.entity_id,
218 pf.label as field_title,
219 pf.html_type,
220 pf.price_set_id,
221 pfv.membership_type_id,
222 pfv.membership_num_terms,
223 li.price_field_id,
224 li.participant_count,
225 li.price_field_value_id,
226 li.financial_type_id,
227 li.tax_amount,
228 pfv.description";
229
230 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
231 if ($relatedEntity) {
232 $condition = "li.contribution_id = %2.id ";
233 }
234
235 $fromClause = "
236 FROM civicrm_%2 as %2
237 LEFT JOIN civicrm_line_item li ON ({$condition})
238 LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )
239 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
240 $whereClause = "
241 WHERE %2.id = %1";
242
243 // CRM-16250 get additional participant's fee selection details only for invoice PDF (if any)
244 if ($entity == 'participant' && $invoice) {
245 $additionalParticipantIDs = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
246 if (!empty($additionalParticipantIDs)) {
247 $whereClause = "WHERE %2.id IN (%1, " . implode(', ', $additionalParticipantIDs) . ")";
248 }
249 }
250
251 $orderByClause = " ORDER BY pf.weight, pfv.weight";
252
253 if ($isQuick) {
254 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
255 $whereClause .= " and cps.is_quick_config = 0";
256 }
257
258 if (!$isQtyZero) {
259 $whereClause .= " and li.qty != 0";
260 }
261
262 $lineItems = array();
263
264 if (!$entityId || !$entity || !$fromClause) {
265 return $lineItems;
266 }
267
268 $params = array(
269 1 => array($entityId, 'Integer'),
270 2 => array($entity, 'Text'),
271 );
272
273 $getTaxDetails = FALSE;
274 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
275 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
276
277 $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
278 while ($dao->fetch()) {
279 if (!$dao->id) {
280 continue;
281 }
282 $lineItems[$dao->id] = array(
283 'qty' => (float) $dao->qty,
284 'label' => $dao->label,
285 'unit_price' => $dao->unit_price,
286 'line_total' => $dao->line_total,
287 'price_field_id' => $dao->price_field_id,
288 'participant_count' => $dao->participant_count,
289 'price_field_value_id' => $dao->price_field_value_id,
290 'field_title' => $dao->field_title,
291 'html_type' => $dao->html_type,
292 'description' => $dao->description,
293 'entity_id' => $dao->entity_id,
294 'entity_table' => $dao->entity_table,
295 'contribution_id' => $dao->contribution_id,
296 'financial_type_id' => $dao->financial_type_id,
297 'financial_type' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'financial_type_id', $dao->financial_type_id),
298 'membership_type_id' => $dao->membership_type_id,
299 'membership_num_terms' => $dao->membership_num_terms,
300 'tax_amount' => $dao->tax_amount,
301 'price_set_id' => $dao->price_set_id,
302 );
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;
307 }
308 }
309 if ($invoicing) {
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);
314 }
315 return $lineItems;
316 }
317
318 /**
319 * This method will create the lineItem array required for
320 * processAmount method
321 *
322 * @param int $fid
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(.
330 * this is
331 * lineItem array)
332 * @param string $amount_override
333 */
334 public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
335 if (empty($params["price_{$fid}"])) {
336 return;
337 }
338
339 //lets first check in fun parameter,
340 //since user might modified w/ hooks.
341 $options = array();
342 if (array_key_exists('options', $fields)) {
343 $options = $fields['options'];
344 }
345 else {
346 CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
347 }
348 $fieldTitle = CRM_Utils_Array::value('label', $fields);
349 if (!$fieldTitle) {
350 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
351 }
352
353 foreach ($params["price_{$fid}"] as $oid => $qty) {
354 $price = $amount_override === NULL ? $options[$oid]['amount'] : $amount_override;
355
356 // lets clean the price in case it is not yet cleant
357 // CRM-10974
358 $price = CRM_Utils_Rule::cleanMoney($price);
359
360 $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
361
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]),
368 'qty' => $qty,
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]),
380 );
381
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');
384 }
385 }
386 }
387
388 /**
389 * Delete line items for given entity.
390 *
391 * @param int $entityId
392 * @param int $entityTable
393 *
394 * @return bool
395 */
396 public static function deleteLineItems($entityId, $entityTable) {
397 if (!$entityId || !$entityTable) {
398 return FALSE;
399 }
400
401 if ($entityId && !is_array($entityId)) {
402 $entityId = array($entityId);
403 }
404
405 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
406 $dao = CRM_Core_DAO::executeQuery($query);
407 return TRUE;
408 }
409
410 /**
411 * Process price set and line items.
412 *
413 * @param int $entityId
414 * @param array $lineItem
415 * Line item array.
416 * @param object $contributionDetails
417 * @param string $entityTable
418 * Entity table.
419 *
420 * @param bool $update
421 *
422 * @return void
423 */
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)
427 ) {
428 return;
429 }
430
431 foreach ($lineItem as $priceSetId => &$values) {
432 if (!$priceSetId) {
433 continue;
434 }
435
436 foreach ($values as &$line) {
437 if (empty($line['entity_table'])) {
438 $line['entity_table'] = $entityTable;
439 }
440 if (empty($line['entity_id'])) {
441 $line['entity_id'] = $entityId;
442 }
443 if (!empty($line['membership_type_id'])) {
444 $line['entity_table'] = 'civicrm_membership';
445 }
446 if (!empty($contributionDetails->id)) {
447 $line['contribution_id'] = $contributionDetails->id;
448 if ($line['entity_table'] == 'civicrm_contribution') {
449 $line['entity_id'] = $contributionDetails->id;
450 }
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'];
456 }
457 }
458
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');
463 }
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);
470 }
471 }
472 }
473 }
474 if (!$update && $contributionDetails) {
475 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn($lineItem, $contributionDetails);
476 }
477 }
478
479 /**
480 * @param int $entityId
481 * @param string $entityTable
482 * @param $amount
483 * @param array $otherParams
484 */
485 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
486 if (!$entityId || CRM_Utils_System::isNull($amount)) {
487 return;
488 }
489
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 ";
493
494 $set = " li.unit_price = %3,
495 li.line_total = %3 ";
496
497 $where = " li.entity_id = %1 AND
498 li.entity_table = %2 ";
499
500 $params = array(
501 1 => array($entityId, 'Integer'),
502 2 => array($entityTable, 'String'),
503 3 => array($amount, 'Float'),
504 );
505
506 if ($entityTable == 'civicrm_contribution') {
507 $entityName = 'default_contribution_amount';
508 $where .= " AND ps.name = %4 ";
509 $params[4] = array($entityName, 'String');
510 }
511 elseif ($entityTable == 'civicrm_participant') {
512 $from .= "
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;
519 $params += array(
520 4 => array($otherParams['fee_label'], 'String'),
521 5 => array($otherParams['event_id'], 'String'),
522 );
523 }
524
525 $query = "
526 UPDATE $from
527 SET $set
528 WHERE $where
529 ";
530
531 CRM_Core_DAO::executeQuery($query, $params);
532 }
533
534 /**
535 * Build line items array.
536 *
537 * @param array $params
538 * Form values.
539 *
540 * @param string $entityId
541 * Entity id.
542 *
543 * @param string $entityTable
544 * Entity Table.
545 *
546 * @param bool $isRelatedID
547 */
548 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
549
550 if (!$entityId) {
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']) {
557 continue;
558 }
559 if (!$totalAmount) {
560 $totalAmount = $values['amount'];
561 }
562 $financialType = $values['financial_type_id'];
563 }
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'],
568 'qty' => 1,
569 'unit_price' => $totalAmount,
570 'line_total' => $totalAmount,
571 'financial_type_id' => $financialType,
572 'membership_type_id' => $values['membership_type_id'],
573 );
574 break;
575 }
576 }
577 else {
578 $setID = NULL;
579 $totalEntityId = count($entityId);
580 if ($entityTable == 'contribution') {
581 $isRelatedID = TRUE;
582 }
583 foreach ($entityId as $id) {
584 $lineItems = CRM_Price_BAO_LineItem::getLineItems($id, $entityTable, FALSE, 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');
589 }
590 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
591 && $totalEntityId == 1
592 ) {
593 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
594 }
595 $values['id'] = $key;
596 $params['line_item'][$setID][$key] = $values;
597 }
598 }
599 }
600 }
601
602 /**
603 * Calculate tax rate in percentage.
604 *
605 * @param array $lineItemId
606 * An assoc array of lineItem.
607 *
608 * @return int|void
609 * tax rate
610 */
611 public static function calculateTaxRate($lineItemId) {
612 if ($lineItemId['unit_price'] == 0 || $lineItemId['qty'] == 0) {
613 return FALSE;
614 }
615 if ($lineItemId['html_type'] == 'Text') {
616 $tax = round($lineItemId['tax_amount'] / ($lineItemId['unit_price'] * $lineItemId['qty']) * 100, 2);
617 }
618 else {
619 $tax = round(($lineItemId['tax_amount'] / $lineItemId['unit_price']) * 100, 2);
620 }
621 return $tax;
622 }
623
624 }