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