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