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