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