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