Merge pull request #4892 from colemanw/INFRA-132
[civicrm-core.git] / CRM / Price / BAO / LineItem.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
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 */
46class CRM_Price_BAO_LineItem extends CRM_Price_DAO_LineItem {
47
48 /**
49 * Creates a new entry in the database.
50 *
414c1420
TO
51 * @param array $params
52 * (reference) an assoc array of name/value pairs.
6a488035 53 *
c490a46a 54 * @return CRM_Price_DAO_LineItem object
6a488035
TO
55 * @static
56 */
00be9182 57 public static function create(&$params) {
22fe049d
PN
58 $id = CRM_Utils_Array::value('id', $params);
59 if ($id) {
60 CRM_Utils_Hook::pre('edit', 'LineItem', $id, $params);
61 }
62 else {
63 CRM_Utils_Hook::pre('create', 'LineItem', $params['entity_id'], $params);
64 }
c206647d 65
22fe049d
PN
66 // unset entity table and entity id in $params
67 // we never update the entity table and entity id during update mode
68 if ($id) {
69 unset($params['entity_id'], $params['entity_table']);
70 }
421dfaa6 71
6a488035
TO
72 $lineItemBAO = new CRM_Price_BAO_LineItem();
73 $lineItemBAO->copyValues($params);
74
75 $return = $lineItemBAO->save();
76
22fe049d
PN
77 if ($id) {
78 CRM_Utils_Hook::post('edit', 'LineItem', $id, $params);
79 }
80 else {
81 CRM_Utils_Hook::post('create', 'LineItem', $params['entity_id'], $params);
82 }
6a488035
TO
83
84 return $return;
85 }
86
87 /**
88 * Takes a bunch of params that are needed to match certain criteria and
89 * retrieves the relevant objects. Typically, the valid params are only
90 * price_field_id. This is the inverse function of create. It also
91 * stores all of the retrieved values in the default array.
92 *
414c1420
TO
93 * @param array $params
94 * (reference ) an assoc array of name/value pairs.
95 * @param array $defaults
96 * (reference ) an assoc array to hold the flattened values.
6a488035 97 *
c490a46a 98 * @return CRM_Price_BAO_LineItem object
6a488035
TO
99 * @static
100 */
00be9182 101 public static function retrieve(&$params, &$defaults) {
6a488035
TO
102 $lineItem = new CRM_Price_BAO_LineItem();
103 $lineItem->copyValues($params);
104 if ($lineItem->find(TRUE)) {
105 CRM_Core_DAO::storeValues($lineItem, $defaults);
106 return $lineItem;
107 }
108 return NULL;
109 }
110
ffd93213 111 /**
100fef9d 112 * @param int $entityId
ffd93213
EM
113 * @param $entityTable
114 *
115 * @return null|string
116 */
00be9182 117 public static function getLineTotal($entityId, $entityTable) {
5a18a545 118 $sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
bc2eeabb 119FROM civicrm_line_item li
ae53df5f
PJ
120WHERE li.entity_table = '{$entityTable}'
121AND li.entity_id = {$entityId}
122";
bc2eeabb
PJ
123 $lineItemTotal = CRM_Core_DAO::singleValueQuery($sqlLineItemTotal);
124 return $lineItemTotal;
125 }
126
34a100a7 127 /**
100fef9d
CW
128 * Wrapper for line item retrieval when contribution ID is known
129 * @param int $contributionID
34a100a7
EM
130 *
131 * @return array
132 */
00be9182 133 public static function getLineItemsByContributionID($contributionID) {
ba1dcfda 134 return self::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
34a100a7
EM
135 }
136
6a488035
TO
137 /**
138 * Given a participant id/contribution id,
139 * return contribution/fee line items
140 *
5a4f6742
CW
141 * @param int $entityId
142 * participant/contribution id.
143 * @param string $entity
144 * participant/contribution.
6a488035 145 *
dd244018
EM
146 * @param null $isQuick
147 * @param bool $isQtyZero
0d6f29cd 148 * @param bool $relatedEntity
dd244018 149 *
414c1420
TO
150 * @param string $overrideWhereClause
151 * E.g "WHERE contribution id = 7 " per the getLineItemsByContributionID wrapper.
34a100a7
EM
152 * 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
153 * when we don't want it's entity-id magix
154 *
6a488035
TO
155 * @return array of line items
156 */
ba1dcfda 157 public static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL, $isQtyZero = TRUE, $relatedEntity = FALSE, $overrideWhereClause = '') {
34a100a7 158 $whereClause = $fromClause = NULL;
6a488035
TO
159 $selectClause = "
160 SELECT li.id,
161 li.label,
a7886853 162 li.contribution_id,
6a488035
TO
163 li.qty,
164 li.unit_price,
165 li.line_total,
34a100a7
EM
166 li.entity_table,
167 li.entity_id,
6a488035
TO
168 pf.label as field_title,
169 pf.html_type,
170 pfv.membership_type_id,
9c09f5b7 171 pfv.membership_num_terms,
6a488035
TO
172 li.price_field_id,
173 li.participant_count,
174 li.price_field_value_id,
bf45dbe8 175 li.financial_type_id,
9849720e 176 li.tax_amount,
6a488035
TO
177 pfv.description";
178
0d6f29cd 179 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
180 if ($relatedEntity) {
181 $condition = "li.contribution_id = %2.id ";
182 }
183
6a488035
TO
184 $fromClause = "
185 FROM civicrm_%2 as %2
0d6f29cd 186 LEFT JOIN civicrm_line_item li ON ({$condition})
6a488035
TO
187 LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )
188 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
189 $whereClause = "
190 WHERE %2.id = %1";
191
e68f41a5
DG
192 $orderByClause = " ORDER BY pf.weight, pfv.weight";
193
6a488035
TO
194 if ($isQuick) {
195 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
196 $whereClause .= " and cps.is_quick_config = 0";
197 }
d5397f2f
PJ
198
199 if (!$isQtyZero) {
200 $whereClause .= " and li.qty != 0";
201 }
202
6a488035
TO
203 $lineItems = array();
204
205 if (!$entityId || !$entity || !$fromClause) {
206 return $lineItems;
207 }
208
209 $params = array(
210 1 => array($entityId, 'Integer'),
211 2 => array($entity, 'Text'),
212 );
213
2feea3d1 214 $getTaxDetails = FALSE;
ba1dcfda 215 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
03b412ae 216 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
34a100a7
EM
217 if ($overrideWhereClause) {
218 $whereClause = $overrideWhereClause;
219 }
220
e68f41a5 221 $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
6a488035
TO
222 while ($dao->fetch()) {
223 if (!$dao->id) {
224 continue;
225 }
226 $lineItems[$dao->id] = array(
4dc7af82 227 'qty' => (float) $dao->qty,
6a488035
TO
228 'label' => $dao->label,
229 'unit_price' => $dao->unit_price,
230 'line_total' => $dao->line_total,
231 'price_field_id' => $dao->price_field_id,
232 'participant_count' => $dao->participant_count,
233 'price_field_value_id' => $dao->price_field_value_id,
234 'field_title' => $dao->field_title,
235 'html_type' => $dao->html_type,
236 'description' => $dao->description,
34a100a7
EM
237 // 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
238 // we also JUST WANT TO KNOW the the entity_id in the DB
239 'entity_id' => empty($overrideWhereClause) ? $entityId : $dao->entity_id,
240 'entity_table' => $dao->entity_table,
a7886853 241 'contribution_id' => $dao->contribution_id,
bf45dbe8 242 'financial_type_id' => $dao->financial_type_id,
6a488035 243 'membership_type_id' => $dao->membership_type_id,
9c09f5b7 244 'membership_num_terms' => $dao->membership_num_terms,
9849720e 245 'tax_amount' => $dao->tax_amount,
6a488035 246 );
9849720e
RK
247 $lineItems[$dao->id]['tax_rate'] = CRM_Price_BAO_LineItem::calculateTaxRate($lineItems[$dao->id]);
248 $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
2feea3d1
PB
249 if ($lineItems[$dao->id]['tax_amount'] != '') {
250 $getTaxDetails = TRUE;
251 }
6a488035 252 }
03b412ae
PB
253 if ($invoicing) {
254 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
255 $smarty = CRM_Core_Smarty::singleton();
256 $smarty->assign('taxTerm', $taxTerm);
257 $smarty->assign('getTaxDetails', $getTaxDetails);
258 }
6a488035
TO
259 return $lineItems;
260 }
261
262 /**
263 * This method will create the lineItem array required for
264 * processAmount method
265 *
414c1420
TO
266 * @param int $fid
267 * Price set field id.
268 * @param array $params
269 * Reference to form values.
270 * @param array $fields
271 * Reference to array of fields belonging.
6a488035 272 * to the price set used for particular event
414c1420
TO
273 * @param array $values
274 * Reference to the values array(.
ba1dcfda 275 this is
6a488035
TO
276 * lineItem array)
277 *
278 * @return void
6a488035 279 */
00be9182 280 public static function format($fid, &$params, &$fields, &$values) {
6a488035
TO
281 if (empty($params["price_{$fid}"])) {
282 return;
283 }
284
285 $optionIDs = implode(',', array_keys($params["price_{$fid}"]));
286
287 //lets first check in fun parameter,
288 //since user might modified w/ hooks.
289 $options = array();
290 if (array_key_exists('options', $fields)) {
291 $options = $fields['options'];
292 }
293 else {
9da8dc8c 294 CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
6a488035
TO
295 }
296 $fieldTitle = CRM_Utils_Array::value('label', $fields);
297 if (!$fieldTitle) {
9da8dc8c 298 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
6a488035
TO
299 }
300
301 foreach ($params["price_{$fid}"] as $oid => $qty) {
302 $price = $options[$oid]['amount'];
303
304 // lets clean the price in case it is not yet cleant
305 // CRM-10974
306 $price = CRM_Utils_Rule::cleanMoney($price);
307
308 $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
309
310 $values[$oid] = array(
311 'price_field_id' => $fid,
312 'price_field_value_id' => $oid,
313 'label' => CRM_Utils_Array::value('label', $options[$oid]),
314 'field_title' => $fieldTitle,
315 'description' => CRM_Utils_Array::value('description', $options[$oid]),
316 'qty' => $qty,
317 'unit_price' => $price,
318 'line_total' => $qty * $price,
319 'participant_count' => $qty * $participantsPerField,
320 'max_value' => CRM_Utils_Array::value('max_value', $options[$oid]),
321 'membership_type_id' => CRM_Utils_Array::value('membership_type_id', $options[$oid]),
322 'membership_num_terms' => CRM_Utils_Array::value('membership_num_terms', $options[$oid]),
323 'auto_renew' => CRM_Utils_Array::value('auto_renew', $options[$oid]),
324 'html_type' => $fields['html_type'],
bf45dbe8 325 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $options[$oid]),
5a18a545 326 'tax_amount' => CRM_Utils_Array::value('tax_amount', $options[$oid]),
6a488035 327 );
cdeb4bdf 328
e03317f1 329 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
421dfaa6 330 $values[$oid]['auto_renew'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
6a488035
TO
331 }
332 }
333 }
334
335 /**
336 * Delete line items for given entity.
337 *
338 * @param int $entityId
339 * @param int $entityTable
340 *
77b97be7 341 * @return bool
6a488035
TO
342 * @static
343 */
421dfaa6 344 public static function deleteLineItems($entityId, $entityTable) {
6a488035 345 if (!$entityId || !$entityTable) {
9330406e 346 return FALSE;
6a488035
TO
347 }
348
349 if ($entityId && !is_array($entityId)) {
350 $entityId = array($entityId);
351 }
352
de1c25e1 353 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
6a488035 354 $dao = CRM_Core_DAO::executeQuery($query);
9330406e 355 return TRUE;
6a488035
TO
356 }
357
358 /**
100fef9d 359 * Process price set and line items.
dd244018 360 *
100fef9d 361 * @param int $entityId
414c1420
TO
362 * @param array $lineItem
363 * Line item array.
6a488035 364 * @param object $contributionDetails
414c1420
TO
365 * @param string $entityTable
366 * Entity table.
6a488035 367 *
dd244018
EM
368 * @param bool $update
369 *
6a488035
TO
370 * @return void
371 * @static
372 */
00be9182 373 public static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
6a488035
TO
374 if (!$entityId || !is_array($lineItem)
375 || CRM_Utils_system::isNull($lineItem)
376 ) {
377 return;
378 }
421dfaa6 379
6a488035
TO
380 foreach ($lineItem as $priceSetId => $values) {
381 if (!$priceSetId) {
382 continue;
383 }
384
385 foreach ($values as $line) {
386 $line['entity_table'] = $entityTable;
34a100a7
EM
387 if (empty($line['entity_id'])) {
388 $line['entity_id'] = $entityId;
389 }
22e263ad 390 if (!empty($line['membership_type_id'])) {
79ebec7b 391 $line['entity_table'] = 'civicrm_membership';
8aa7457a 392 }
79ebec7b
PN
393 if (!empty($contributionDetails->id)) {
394 $line['contribution_id'] = $contributionDetails->id;
395 if ($line['entity_table'] == 'civicrm_contribution') {
396 $line['entity_id'] = $contributionDetails->id;
7d3f62f6 397 }
a7886853 398 }
c206647d 399
6a488035
TO
400 // if financial type is not set and if price field value is NOT NULL
401 // get financial type id of price field value
8cc574cf 402 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
9da8dc8c 403 $line['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
6a488035
TO
404 }
405 $lineItems = CRM_Price_BAO_LineItem::create($line);
406 if (!$update && $contributionDetails) {
407 CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails);
c40e1ff4 408 if (isset($line['tax_amount'])) {
0b7bd9dd 409 CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails, TRUE);
410 }
6a488035
TO
411 }
412 }
413 }
421dfaa6 414 }
6a488035 415
ffd93213 416 /**
100fef9d 417 * @param int $entityId
ffd93213
EM
418 * @param string $entityTable
419 * @param $amount
100fef9d 420 * @param array $otherParams
ffd93213 421 */
6a488035 422 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
ba1dcfda 423 if (!$entityId || CRM_Utils_System::isNull($amount)) {
6a488035 424 return;
ba1dcfda 425 }
6a488035
TO
426
427 $from = " civicrm_line_item li
428 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
429 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
430
421dfaa6 431 $set = " li.unit_price = %3,
6a488035
TO
432 li.line_total = %3 ";
433
421dfaa6 434 $where = " li.entity_id = %1 AND
6a488035
TO
435 li.entity_table = %2 ";
436
437 $params = array(
438 1 => array($entityId, 'Integer'),
439 2 => array($entityTable, 'String'),
440 3 => array($amount, 'Float'),
441 );
442
443 if ($entityTable == 'civicrm_contribution') {
444 $entityName = 'default_contribution_amount';
445 $where .= " AND ps.name = %4 ";
421dfaa6 446 $params[4] = array($entityName, 'String');
447 }
6a488035
TO
448 elseif ($entityTable == 'civicrm_participant') {
449 $from .= "
450 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
451 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
452 $set .= " ,li.label = %4,
453 li.price_field_value_id = cpfv.id ";
454 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
ba1dcfda 455 $amount = empty($amount) ? 0 : $amount;
6a488035
TO
456 $params += array(
457 4 => array($otherParams['fee_label'], 'String'),
458 5 => array($otherParams['event_id'], 'String'),
459 );
460 }
461
421dfaa6 462 $query = "
6a488035
TO
463 UPDATE $from
464 SET $set
421dfaa6 465 WHERE $where
6a488035
TO
466 ";
467
468 CRM_Core_DAO::executeQuery($query, $params);
469 }
470
ba1dcfda 471 /**
100fef9d 472 * Build line items array.
414c1420
TO
473 * @param array $params
474 * Form values.
6a488035 475 *
414c1420
TO
476 * @param string $entityId
477 * Entity id.
6a488035 478 *
414c1420
TO
479 * @param string $entityTable
480 * Entity Table.
6a488035 481 *
6a488035
TO
482 * @return void
483 * @static
484 */
00be9182 485 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
421dfaa6 486
6a488035 487 if (!$entityId) {
82cc6775
PN
488 $priceSetDetails = CRM_Price_BAO_PriceSet::getDefaultPriceSet($entityTable);
489 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
490 $financialType = CRM_Utils_Array::value('financial_type_id', $params);
6a488035 491 foreach ($priceSetDetails as $values) {
c206647d 492 if ($entityTable == 'membership') {
82cc6775
PN
493 if ($isRelatedID != $values['membership_type_id']) {
494 continue;
495 }
496 if (!$totalAmount) {
497 $totalAmount = $values['amount'];
498 }
499 $financialType = $values['financial_type_id'];
500 }
6a488035
TO
501 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
502 'price_field_id' => $values['priceFieldID'],
503 'price_field_value_id' => $values['priceFieldValueID'],
504 'label' => $values['label'],
505 'qty' => 1,
82cc6775
PN
506 'unit_price' => $totalAmount,
507 'line_total' => $totalAmount,
508 'financial_type_id' => $financialType,
21dfd5f5 509 'membership_type_id' => $values['membership_type_id'],
6a488035 510 );
82cc6775 511 break;
6a488035 512 }
421dfaa6 513 }
6a488035
TO
514 else {
515 $setID = NULL;
464bb009
PN
516 $totalEntityId = count($entityId);
517 foreach ($entityId as $id) {
79ebec7b 518 $lineItems = CRM_Price_BAO_LineItem::getLineItems($id, $entityTable, NULL, TRUE, $isRelatedID);
464bb009 519 foreach ($lineItems as $key => $values) {
32cb2feb 520 if (!$setID && $values['price_field_id']) {
9da8dc8c 521 $setID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
522 $params['is_quick_config'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
464bb009 523 }
a7488080 524 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
464bb009
PN
525 && $totalEntityId == 1) {
526 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
527 }
528 $values['id'] = $key;
529 $params['line_item'][$setID][$key] = $values;
6a488035 530 }
6a488035
TO
531 }
532 }
533 }
9849720e
RK
534
535 /**
2826a42e
RK
536 * Calculate tax rate in percentage
537 *
5a4f6742 538 * @param array $lineItemId
414c1420 539 * An assoc array of lineItem.
2826a42e
RK
540 *
541 * @return tax rate
542 *
2826a42e 543 * @static
9849720e
RK
544 */
545 public static function calculateTaxRate($lineItemId) {
5b22467a
RK
546 if ($lineItemId['unit_price'] == 0) {
547 return;
548 }
9849720e 549 if ($lineItemId['html_type'] == 'Text') {
ba1dcfda 550 $tax = $lineItemId['tax_amount'] / ($lineItemId['unit_price'] * $lineItemId['qty']) * 100;
9849720e
RK
551 }
552 else {
ba1dcfda 553 $tax = ($lineItemId['tax_amount'] / $lineItemId['unit_price']) * 100;
9849720e
RK
554 }
555 return $tax;
556 }
6a488035 557}