e1b629c4a721d07e65dc044b5d790e7371073099
[civicrm-core.git] / CRM / Price / BAO / LineItem.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 $contributionId
166 *
167 * @return null|string
168 */
169 public static function getLineTotal($contributionId) {
170 $sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
171 FROM civicrm_line_item li
172 WHERE li.contribution_id = %1";
173 $params = array(1 => array($contributionId, 'Integer'));
174 $lineItemTotal = CRM_Core_DAO::singleValueQuery($sqlLineItemTotal, $params);
175 return $lineItemTotal;
176 }
177
178 /**
179 * Wrapper for line item retrieval when contribution ID is known.
180 * @param int $contributionID
181 *
182 * @return array
183 */
184 public static function getLineItemsByContributionID($contributionID) {
185 return self::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
186 }
187
188 /**
189 * Given a participant id/contribution id,
190 * return contribution/fee line items
191 *
192 * @param int $entityId
193 * participant/contribution id.
194 * @param string $entity
195 * participant/contribution.
196 *
197 * @param bool $isQuick
198 * @param bool $isQtyZero
199 * @param bool $relatedEntity
200 *
201 * @param bool $invoice
202 * @return array
203 * Array of line items
204 */
205 public static function getLineItems($entityId, $entity = 'participant', $isQuick = FALSE, $isQtyZero = TRUE, $relatedEntity = FALSE, $invoice = FALSE) {
206 $whereClause = $fromClause = NULL;
207 $selectClause = "
208 SELECT li.id,
209 li.label,
210 li.contribution_id,
211 li.qty,
212 li.unit_price,
213 li.line_total,
214 li.entity_table,
215 li.entity_id,
216 pf.label as field_title,
217 pf.html_type,
218 pf.price_set_id,
219 pfv.membership_type_id,
220 pfv.membership_num_terms,
221 li.price_field_id,
222 li.participant_count,
223 li.price_field_value_id,
224 li.financial_type_id,
225 li.tax_amount,
226 pfv.description";
227
228 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
229 if ($relatedEntity) {
230 $condition = "li.contribution_id = %2.id ";
231 }
232
233 $fromClause = "
234 FROM civicrm_%2 as %2
235 LEFT JOIN civicrm_line_item li ON ({$condition})
236 LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )
237 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
238 $whereClause = "
239 WHERE %2.id = %1";
240
241 // CRM-16250 get additional participant's fee selection details only for invoice PDF (if any)
242 if ($entity == 'participant' && $invoice) {
243 $additionalParticipantIDs = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
244 if (!empty($additionalParticipantIDs)) {
245 $whereClause = "WHERE %2.id IN (%1, " . implode(', ', $additionalParticipantIDs) . ")";
246 }
247 }
248
249 $orderByClause = " ORDER BY pf.weight, pfv.weight";
250
251 if ($isQuick) {
252 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
253 $whereClause .= " and cps.is_quick_config = 0";
254 }
255
256 if (!$isQtyZero) {
257 $whereClause .= " and li.qty != 0";
258 }
259
260 $lineItems = array();
261
262 if (!$entityId || !$entity || !$fromClause) {
263 return $lineItems;
264 }
265
266 $params = array(
267 1 => array($entityId, 'Integer'),
268 2 => array($entity, 'Text'),
269 );
270
271 $getTaxDetails = FALSE;
272 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
273 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
274
275 $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
276 while ($dao->fetch()) {
277 if (!$dao->id) {
278 continue;
279 }
280 $lineItems[$dao->id] = array(
281 'qty' => (float) $dao->qty,
282 'label' => $dao->label,
283 'unit_price' => $dao->unit_price,
284 'line_total' => $dao->line_total,
285 'price_field_id' => $dao->price_field_id,
286 'participant_count' => $dao->participant_count,
287 'price_field_value_id' => $dao->price_field_value_id,
288 'field_title' => $dao->field_title,
289 'html_type' => $dao->html_type,
290 'description' => $dao->description,
291 'entity_id' => $dao->entity_id,
292 'entity_table' => $dao->entity_table,
293 'contribution_id' => $dao->contribution_id,
294 'financial_type_id' => $dao->financial_type_id,
295 'financial_type' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'financial_type_id', $dao->financial_type_id),
296 'membership_type_id' => $dao->membership_type_id,
297 'membership_num_terms' => $dao->membership_num_terms,
298 'tax_amount' => $dao->tax_amount,
299 'price_set_id' => $dao->price_set_id,
300 );
301 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
302 if (isset($lineItems[$dao->id]['financial_type_id']) && array_key_exists($lineItems[$dao->id]['financial_type_id'], $taxRates)) {
303 // We are close to output/display here - so apply some rounding at output/display level - to not show Tax Rate in all 8 decimals
304 $lineItems[$dao->id]['tax_rate'] = round($taxRates[$lineItems[$dao->id]['financial_type_id']], 3);
305 }
306 else {
307 // There is no Tax Rate associated with this Financial Type
308 $lineItems[$dao->id]['tax_rate'] = FALSE;
309 }
310 $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
311 if ($lineItems[$dao->id]['tax_amount'] != '') {
312 $getTaxDetails = TRUE;
313 }
314 }
315 if ($invoicing) {
316 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
317 $smarty = CRM_Core_Smarty::singleton();
318 $smarty->assign('taxTerm', $taxTerm);
319 $smarty->assign('getTaxDetails', $getTaxDetails);
320 }
321 return $lineItems;
322 }
323
324 /**
325 * This method will create the lineItem array required for
326 * processAmount method
327 *
328 * @param int $fid
329 * Price set field id.
330 * @param array $params
331 * Reference to form values.
332 * @param array $fields
333 * Array of fields belonging to the price set used for particular event
334 * @param array $values
335 * Reference to the values array(.
336 * this is
337 * lineItem array)
338 * @param string $amount_override
339 */
340 public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
341 if (empty($params["price_{$fid}"])) {
342 return;
343 }
344
345 //lets first check in fun parameter,
346 //since user might modified w/ hooks.
347 $options = array();
348 if (array_key_exists('options', $fields)) {
349 $options = $fields['options'];
350 }
351 else {
352 CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
353 }
354 $fieldTitle = CRM_Utils_Array::value('label', $fields);
355 if (!$fieldTitle) {
356 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
357 }
358
359 foreach ($params["price_{$fid}"] as $oid => $qty) {
360 $price = $amount_override === NULL ? $options[$oid]['amount'] : $amount_override;
361
362 // lets clean the price in case it is not yet cleant
363 // CRM-10974
364 $price = CRM_Utils_Rule::cleanMoney($price);
365
366 $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
367
368 $values[$oid] = array(
369 'price_field_id' => $fid,
370 'price_field_value_id' => $oid,
371 'label' => CRM_Utils_Array::value('label', $options[$oid]),
372 'field_title' => $fieldTitle,
373 'description' => CRM_Utils_Array::value('description', $options[$oid]),
374 'qty' => $qty,
375 'unit_price' => $price,
376 'line_total' => $qty * $price,
377 'participant_count' => $qty * $participantsPerField,
378 'max_value' => CRM_Utils_Array::value('max_value', $options[$oid]),
379 'membership_type_id' => CRM_Utils_Array::value('membership_type_id', $options[$oid]),
380 'membership_num_terms' => CRM_Utils_Array::value('membership_num_terms', $options[$oid]),
381 'auto_renew' => CRM_Utils_Array::value('auto_renew', $options[$oid]),
382 'html_type' => $fields['html_type'],
383 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $options[$oid]),
384 'tax_amount' => CRM_Utils_Array::value('tax_amount', $options[$oid]),
385 'non_deductible_amount' => CRM_Utils_Array::value('non_deductible_amount', $options[$oid]),
386 );
387
388 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
389 $values[$oid]['auto_renew'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
390 }
391 }
392 }
393
394 /**
395 * Delete line items for given entity.
396 *
397 * @param int $entityId
398 * @param int $entityTable
399 *
400 * @return bool
401 */
402 public static function deleteLineItems($entityId, $entityTable) {
403 if (!$entityId || !$entityTable) {
404 return FALSE;
405 }
406
407 if ($entityId && !is_array($entityId)) {
408 $entityId = array($entityId);
409 }
410
411 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
412 $dao = CRM_Core_DAO::executeQuery($query);
413 return TRUE;
414 }
415
416 /**
417 * Process price set and line items.
418 *
419 * @param int $entityId
420 * @param array $lineItem
421 * Line item array.
422 * @param object $contributionDetails
423 * @param string $entityTable
424 * Entity table.
425 *
426 * @param bool $update
427 *
428 * @return void
429 */
430 public static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
431 if (!$entityId || !is_array($lineItem)
432 || CRM_Utils_system::isNull($lineItem)
433 ) {
434 return;
435 }
436
437 foreach ($lineItem as $priceSetId => &$values) {
438 if (!$priceSetId) {
439 continue;
440 }
441
442 foreach ($values as &$line) {
443 if (empty($line['entity_table'])) {
444 $line['entity_table'] = $entityTable;
445 }
446 if (empty($line['entity_id'])) {
447 $line['entity_id'] = $entityId;
448 }
449 if (!empty($line['membership_type_id'])) {
450 $line['entity_table'] = 'civicrm_membership';
451 }
452 if (!empty($contributionDetails->id)) {
453 $line['contribution_id'] = $contributionDetails->id;
454 if ($line['entity_table'] == 'civicrm_contribution') {
455 $line['entity_id'] = $contributionDetails->id;
456 }
457 // CRM-19094: entity_table is set to civicrm_membership then ensure
458 // the entityId is set to membership ID not contribution by default
459 elseif ($line['entity_table'] == 'civicrm_membership' && !empty($line['entity_id']) && $line['entity_id'] == $contributionDetails->id) {
460 $membershipId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', 'contribution_id', $line['entity_id'], 'membership_id');
461 $line['entity_id'] = $membershipId ? $membershipId : $line['entity_id'];
462 }
463 }
464
465 // if financial type is not set and if price field value is NOT NULL
466 // get financial type id of price field value
467 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
468 $line['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
469 }
470 $lineItems = CRM_Price_BAO_LineItem::create($line);
471 if (!$update && $contributionDetails) {
472 $financialItem = CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails);
473 $line['financial_item_id'] = $financialItem->id;
474 if (!empty($line['tax_amount'])) {
475 CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails, TRUE);
476 }
477 }
478 }
479 }
480 if (!$update && $contributionDetails) {
481 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn($lineItem, $contributionDetails);
482 }
483 }
484
485 /**
486 * @param int $entityId
487 * @param string $entityTable
488 * @param $amount
489 * @param array $otherParams
490 */
491 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
492 if (!$entityId || CRM_Utils_System::isNull($amount)) {
493 return;
494 }
495
496 $from = " civicrm_line_item li
497 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
498 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
499
500 $set = " li.unit_price = %3,
501 li.line_total = %3 ";
502
503 $where = " li.entity_id = %1 AND
504 li.entity_table = %2 ";
505
506 $params = array(
507 1 => array($entityId, 'Integer'),
508 2 => array($entityTable, 'String'),
509 3 => array($amount, 'Float'),
510 );
511
512 if ($entityTable == 'civicrm_contribution') {
513 $entityName = 'default_contribution_amount';
514 $where .= " AND ps.name = %4 ";
515 $params[4] = array($entityName, 'String');
516 }
517 elseif ($entityTable == 'civicrm_participant') {
518 $from .= "
519 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
520 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
521 $set .= " ,li.label = %4,
522 li.price_field_value_id = cpfv.id ";
523 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
524 $amount = empty($amount) ? 0 : $amount;
525 $params += array(
526 4 => array($otherParams['fee_label'], 'String'),
527 5 => array($otherParams['event_id'], 'String'),
528 );
529 }
530
531 $query = "
532 UPDATE $from
533 SET $set
534 WHERE $where
535 ";
536
537 CRM_Core_DAO::executeQuery($query, $params);
538 }
539
540 /**
541 * Build line items array.
542 *
543 * @param array $params
544 * Form values.
545 *
546 * @param string $entityId
547 * Entity id.
548 *
549 * @param string $entityTable
550 * Entity Table.
551 *
552 * @param bool $isRelatedID
553 */
554 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
555
556 if (!$entityId) {
557 $priceSetDetails = CRM_Price_BAO_PriceSet::getDefaultPriceSet($entityTable);
558 $totalAmount = CRM_Utils_Array::value('partial_payment_total', $params, CRM_Utils_Array::value('total_amount', $params));
559 $financialType = CRM_Utils_Array::value('financial_type_id', $params);
560 foreach ($priceSetDetails as $values) {
561 if ($entityTable == 'membership') {
562 if ($isRelatedID != $values['membership_type_id']) {
563 continue;
564 }
565 if (!$totalAmount) {
566 $totalAmount = $values['amount'];
567 }
568 $financialType = $values['financial_type_id'];
569 }
570 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
571 'price_field_id' => $values['priceFieldID'],
572 'price_field_value_id' => $values['priceFieldValueID'],
573 'label' => $values['label'],
574 'qty' => 1,
575 'unit_price' => $totalAmount,
576 'line_total' => $totalAmount,
577 'financial_type_id' => $financialType,
578 'membership_type_id' => $values['membership_type_id'],
579 );
580 break;
581 }
582 }
583 else {
584 $setID = NULL;
585 $totalEntityId = count($entityId);
586 if ($entityTable == 'contribution') {
587 $isRelatedID = TRUE;
588 }
589 foreach ($entityId as $id) {
590 $lineItems = CRM_Price_BAO_LineItem::getLineItems($id, $entityTable, FALSE, TRUE, $isRelatedID);
591 foreach ($lineItems as $key => $values) {
592 if (!$setID && $values['price_field_id']) {
593 $setID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
594 $params['is_quick_config'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
595 }
596 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
597 && $totalEntityId == 1
598 ) {
599 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
600 }
601 $values['id'] = $key;
602 $params['line_item'][$setID][$key] = $values;
603 }
604 }
605 }
606 }
607
608 }