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