586fbd68d6edef523ce83dabbe0152c038b8f862
[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 null $isQuick
192 * @param bool $isQtyZero
193 * @param bool $relatedEntity
194 *
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
199 *
200 * @param bool $invoice
201 * @return array
202 * Array of line items
203 */
204 public static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL, $isQtyZero = TRUE, $relatedEntity = FALSE, $overrideWhereClause = '', $invoice = FALSE) {
205 $whereClause = $fromClause = NULL;
206 $selectClause = "
207 SELECT li.id,
208 li.label,
209 li.contribution_id,
210 li.qty,
211 li.unit_price,
212 li.line_total,
213 li.entity_table,
214 li.entity_id,
215 pf.label as field_title,
216 pf.html_type,
217 pfv.membership_type_id,
218 pfv.membership_num_terms,
219 li.price_field_id,
220 li.participant_count,
221 li.price_field_value_id,
222 li.financial_type_id,
223 li.tax_amount,
224 pfv.description";
225
226 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
227 if ($relatedEntity) {
228 $condition = "li.contribution_id = %2.id ";
229 }
230
231 $fromClause = "
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 )";
236 $whereClause = "
237 WHERE %2.id = %1";
238
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) . ")";
244 }
245 }
246
247 $orderByClause = " ORDER BY pf.weight, pfv.weight";
248
249 if ($isQuick) {
250 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
251 $whereClause .= " and cps.is_quick_config = 0";
252 }
253
254 if (!$isQtyZero) {
255 $whereClause .= " and li.qty != 0";
256 }
257
258 $lineItems = array();
259
260 if (!$entityId || !$entity || !$fromClause) {
261 return $lineItems;
262 }
263
264 $params = array(
265 1 => array($entityId, 'Integer'),
266 2 => array($entity, 'Text'),
267 );
268
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;
274 }
275
276 $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
277 while ($dao->fetch()) {
278 if (!$dao->id) {
279 continue;
280 }
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 'membership_type_id' => $dao->membership_type_id,
299 'membership_num_terms' => $dao->membership_num_terms,
300 'tax_amount' => $dao->tax_amount,
301 );
302 $lineItems[$dao->id]['tax_rate'] = CRM_Price_BAO_LineItem::calculateTaxRate($lineItems[$dao->id]);
303 $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
304 if ($lineItems[$dao->id]['tax_amount'] != '') {
305 $getTaxDetails = TRUE;
306 }
307 }
308 if ($invoicing) {
309 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
310 $smarty = CRM_Core_Smarty::singleton();
311 $smarty->assign('taxTerm', $taxTerm);
312 $smarty->assign('getTaxDetails', $getTaxDetails);
313 }
314 return $lineItems;
315 }
316
317 /**
318 * This method will create the lineItem array required for
319 * processAmount method
320 *
321 * @param int $fid
322 * Price set field id.
323 * @param array $params
324 * Reference to form values.
325 * @param array $fields
326 * Array of fields belonging to the price set used for particular event
327 * @param array $values
328 * Reference to the values array(.
329 * this is
330 * lineItem array)
331 * @param string $amount_override
332 */
333 public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
334 if (empty($params["price_{$fid}"])) {
335 return;
336 }
337
338 //lets first check in fun parameter,
339 //since user might modified w/ hooks.
340 $options = array();
341 if (array_key_exists('options', $fields)) {
342 $options = $fields['options'];
343 }
344 else {
345 CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
346 }
347 $fieldTitle = CRM_Utils_Array::value('label', $fields);
348 if (!$fieldTitle) {
349 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
350 }
351
352 foreach ($params["price_{$fid}"] as $oid => $qty) {
353 $price = $amount_override === NULL ? $options[$oid]['amount'] : $amount_override;
354
355 // lets clean the price in case it is not yet cleant
356 // CRM-10974
357 $price = CRM_Utils_Rule::cleanMoney($price);
358
359 $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
360
361 $values[$oid] = array(
362 'price_field_id' => $fid,
363 'price_field_value_id' => $oid,
364 'label' => CRM_Utils_Array::value('label', $options[$oid]),
365 'field_title' => $fieldTitle,
366 'description' => CRM_Utils_Array::value('description', $options[$oid]),
367 'qty' => $qty,
368 'unit_price' => $price,
369 'line_total' => $qty * $price,
370 'participant_count' => $qty * $participantsPerField,
371 'max_value' => CRM_Utils_Array::value('max_value', $options[$oid]),
372 'membership_type_id' => CRM_Utils_Array::value('membership_type_id', $options[$oid]),
373 'membership_num_terms' => CRM_Utils_Array::value('membership_num_terms', $options[$oid]),
374 'auto_renew' => CRM_Utils_Array::value('auto_renew', $options[$oid]),
375 'html_type' => $fields['html_type'],
376 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $options[$oid]),
377 'tax_amount' => CRM_Utils_Array::value('tax_amount', $options[$oid]),
378 'non_deductible_amount' => CRM_Utils_Array::value('non_deductible_amount', $options[$oid]),
379 );
380
381 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
382 $values[$oid]['auto_renew'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
383 }
384 }
385 }
386
387 /**
388 * Delete line items for given entity.
389 *
390 * @param int $entityId
391 * @param int $entityTable
392 *
393 * @return bool
394 */
395 public static function deleteLineItems($entityId, $entityTable) {
396 if (!$entityId || !$entityTable) {
397 return FALSE;
398 }
399
400 if ($entityId && !is_array($entityId)) {
401 $entityId = array($entityId);
402 }
403
404 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
405 $dao = CRM_Core_DAO::executeQuery($query);
406 return TRUE;
407 }
408
409 /**
410 * Process price set and line items.
411 *
412 * @param int $entityId
413 * @param array $lineItem
414 * Line item array.
415 * @param object $contributionDetails
416 * @param string $entityTable
417 * Entity table.
418 *
419 * @param bool $update
420 *
421 * @return void
422 */
423 public static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
424 if (!$entityId || !is_array($lineItem)
425 || CRM_Utils_system::isNull($lineItem)
426 ) {
427 return;
428 }
429
430 foreach ($lineItem as $priceSetId => &$values) {
431 if (!$priceSetId) {
432 continue;
433 }
434
435 foreach ($values as &$line) {
436 if (empty($line['entity_table'])) {
437 $line['entity_table'] = $entityTable;
438 }
439 if (empty($line['entity_id'])) {
440 $line['entity_id'] = $entityId;
441 }
442 if (!empty($line['membership_type_id'])) {
443 $line['entity_table'] = 'civicrm_membership';
444 }
445 if (!empty($contributionDetails->id)) {
446 $line['contribution_id'] = $contributionDetails->id;
447 if ($line['entity_table'] == 'civicrm_contribution') {
448 $line['entity_id'] = $contributionDetails->id;
449 }
450 // CRM-19094: entity_table is set to civicrm_membership then ensure
451 // the entityId is set to membership ID not contribution by default
452 elseif ($line['entity_table'] == 'civicrm_membership' && !empty($line['entity_id']) && $line['entity_id'] == $contributionDetails->id) {
453 $membershipId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', 'contribution_id', $line['entity_id'], 'membership_id');
454 $line['entity_id'] = $membershipId ? $membershipId : $line['entity_id'];
455 }
456 }
457
458 // if financial type is not set and if price field value is NOT NULL
459 // get financial type id of price field value
460 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
461 $line['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
462 }
463 $lineItems = CRM_Price_BAO_LineItem::create($line);
464 if (!$update && $contributionDetails) {
465 $financialItem = CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails);
466 $line['financial_item_id'] = $financialItem->id;
467 if (!empty($line['tax_amount'])) {
468 CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails, TRUE);
469 }
470 }
471 }
472 }
473 if (!$update && $contributionDetails) {
474 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn($lineItem, $contributionDetails);
475 }
476 }
477
478 /**
479 * @param int $entityId
480 * @param string $entityTable
481 * @param $amount
482 * @param array $otherParams
483 */
484 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
485 if (!$entityId || CRM_Utils_System::isNull($amount)) {
486 return;
487 }
488
489 $from = " civicrm_line_item li
490 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
491 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
492
493 $set = " li.unit_price = %3,
494 li.line_total = %3 ";
495
496 $where = " li.entity_id = %1 AND
497 li.entity_table = %2 ";
498
499 $params = array(
500 1 => array($entityId, 'Integer'),
501 2 => array($entityTable, 'String'),
502 3 => array($amount, 'Float'),
503 );
504
505 if ($entityTable == 'civicrm_contribution') {
506 $entityName = 'default_contribution_amount';
507 $where .= " AND ps.name = %4 ";
508 $params[4] = array($entityName, 'String');
509 }
510 elseif ($entityTable == 'civicrm_participant') {
511 $from .= "
512 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
513 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
514 $set .= " ,li.label = %4,
515 li.price_field_value_id = cpfv.id ";
516 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
517 $amount = empty($amount) ? 0 : $amount;
518 $params += array(
519 4 => array($otherParams['fee_label'], 'String'),
520 5 => array($otherParams['event_id'], 'String'),
521 );
522 }
523
524 $query = "
525 UPDATE $from
526 SET $set
527 WHERE $where
528 ";
529
530 CRM_Core_DAO::executeQuery($query, $params);
531 }
532
533 /**
534 * Build line items array.
535 *
536 * @param array $params
537 * Form values.
538 *
539 * @param string $entityId
540 * Entity id.
541 *
542 * @param string $entityTable
543 * Entity Table.
544 *
545 * @param bool $isRelatedID
546 */
547 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
548
549 if (!$entityId) {
550 $priceSetDetails = CRM_Price_BAO_PriceSet::getDefaultPriceSet($entityTable);
551 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
552 $financialType = CRM_Utils_Array::value('financial_type_id', $params);
553 foreach ($priceSetDetails as $values) {
554 if ($entityTable == 'membership') {
555 if ($isRelatedID != $values['membership_type_id']) {
556 continue;
557 }
558 if (!$totalAmount) {
559 $totalAmount = $values['amount'];
560 }
561 $financialType = $values['financial_type_id'];
562 }
563 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
564 'price_field_id' => $values['priceFieldID'],
565 'price_field_value_id' => $values['priceFieldValueID'],
566 'label' => $values['label'],
567 'qty' => 1,
568 'unit_price' => $totalAmount,
569 'line_total' => $totalAmount,
570 'financial_type_id' => $financialType,
571 'membership_type_id' => $values['membership_type_id'],
572 );
573 break;
574 }
575 }
576 else {
577 $setID = NULL;
578 $totalEntityId = count($entityId);
579 if ($entityTable == 'contribution') {
580 $isRelatedID = TRUE;
581 }
582 foreach ($entityId as $id) {
583 $lineItems = CRM_Price_BAO_LineItem::getLineItems($id, $entityTable, NULL, TRUE, $isRelatedID);
584 foreach ($lineItems as $key => $values) {
585 if (!$setID && $values['price_field_id']) {
586 $setID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
587 $params['is_quick_config'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
588 }
589 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
590 && $totalEntityId == 1
591 ) {
592 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
593 }
594 $values['id'] = $key;
595 $params['line_item'][$setID][$key] = $values;
596 }
597 }
598 }
599 }
600
601 /**
602 * Calculate tax rate in percentage.
603 *
604 * @param array $lineItemId
605 * An assoc array of lineItem.
606 *
607 * @return int|void
608 * tax rate
609 */
610 public static function calculateTaxRate($lineItemId) {
611 if ($lineItemId['unit_price'] == 0 || $lineItemId['qty'] == 0) {
612 return FALSE;
613 }
614 if ($lineItemId['html_type'] == 'Text') {
615 $tax = round($lineItemId['tax_amount'] / ($lineItemId['unit_price'] * $lineItemId['qty']) * 100, 2);
616 }
617 else {
618 $tax = round(($lineItemId['tax_amount'] / $lineItemId['unit_price']) * 100, 2);
619 }
620 return $tax;
621 }
622
623 }