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