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