3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
39 * @author Marshal Newrock <marshal@idealso.com>
44 * Business objects for Line Items generated by monetary transactions
46 class CRM_Price_BAO_LineItem
extends CRM_Price_DAO_LineItem
{
49 * Creates a new entry in the database.
51 * @param array $params
52 * (reference) an assoc array of name/value pairs.
54 * @return CRM_Price_DAO_LineItem
56 public static function create(&$params) {
57 $id = CRM_Utils_Array
::value('id', $params);
59 CRM_Utils_Hook
::pre('edit', 'LineItem', $id, $params);
62 CRM_Utils_Hook
::pre('create', 'LineItem', $params['entity_id'], $params);
65 // unset entity table and entity id in $params
66 // we never update the entity table and entity id during update mode
68 unset($params['entity_id'], $params['entity_table']);
71 $lineItemBAO = new CRM_Price_BAO_LineItem();
72 $lineItemBAO->copyValues($params);
74 $return = $lineItemBAO->save();
77 CRM_Utils_Hook
::post('edit', 'LineItem', $id, $lineItemBAO);
80 CRM_Utils_Hook
::post('create', 'LineItem', $lineItemBAO->id
, $lineItemBAO);
87 * Retrieve DB object based on input parameters.
89 * It also stores all the retrieved values in the default array.
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.
96 * @return CRM_Price_BAO_LineItem
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);
109 * @param int $entityId
110 * @param $entityTable
112 * @return null|string
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}
120 $lineItemTotal = CRM_Core_DAO
::singleValueQuery($sqlLineItemTotal);
121 return $lineItemTotal;
125 * Wrapper for line item retrieval when contribution ID is known.
126 * @param int $contributionID
130 public static function getLineItemsByContributionID($contributionID) {
131 return self
::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
135 * Given a participant id/contribution id,
136 * return contribution/fee line items
138 * @param int $entityId
139 * participant/contribution id.
140 * @param string $entity
141 * participant/contribution.
143 * @param null $isQuick
144 * @param bool $isQtyZero
145 * @param bool $relatedEntity
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
152 * @param bool $invoice
154 * Array of line items
156 public static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL, $isQtyZero = TRUE, $relatedEntity = FALSE, $overrideWhereClause = '', $invoice = FALSE) {
157 $whereClause = $fromClause = NULL;
167 pf.label as field_title,
169 pfv.membership_type_id,
170 pfv.membership_num_terms,
172 li.participant_count,
173 li.price_field_value_id,
174 li.financial_type_id,
178 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
179 if ($relatedEntity) {
180 $condition = "li.contribution_id = %2.id ";
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 )";
191 // CRM-16250 get additional participant's fee selection details only for invoice PDF (if any)
192 if ($entity == 'participant' && $invoice) {
193 $additionalParticipantIDs = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
194 if (!empty($additionalParticipantIDs)) {
195 $whereClause = "WHERE %2.id IN (%1, " . implode(', ', $additionalParticipantIDs) . ")";
199 $orderByClause = " ORDER BY pf.weight, pfv.weight";
202 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
203 $whereClause .= " and cps.is_quick_config = 0";
207 $whereClause .= " and li.qty != 0";
210 $lineItems = array();
212 if (!$entityId ||
!$entity ||
!$fromClause) {
217 1 => array($entityId, 'Integer'),
218 2 => array($entity, 'Text'),
221 $getTaxDetails = FALSE;
222 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
223 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
224 if ($overrideWhereClause) {
225 $whereClause = $overrideWhereClause;
228 $dao = CRM_Core_DAO
::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
229 while ($dao->fetch()) {
233 $lineItems[$dao->id
] = array(
234 'qty' => (float) $dao->qty
,
235 'label' => $dao->label
,
236 'unit_price' => $dao->unit_price
,
237 'line_total' => $dao->line_total
,
238 'price_field_id' => $dao->price_field_id
,
239 'participant_count' => $dao->participant_count
,
240 'price_field_value_id' => $dao->price_field_value_id
,
241 'field_title' => $dao->field_title
,
242 'html_type' => $dao->html_type
,
243 'description' => $dao->description
,
244 // 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
245 // we also JUST WANT TO KNOW the the entity_id in the DB
246 'entity_id' => empty($overrideWhereClause) ?
$entityId : $dao->entity_id
,
247 'entity_table' => $dao->entity_table
,
248 'contribution_id' => $dao->contribution_id
,
249 'financial_type_id' => $dao->financial_type_id
,
250 'membership_type_id' => $dao->membership_type_id
,
251 'membership_num_terms' => $dao->membership_num_terms
,
252 'tax_amount' => $dao->tax_amount
,
254 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
255 if (isset($lineItems[$dao->id
]['financial_type_id']) && array_key_exists($lineItems[$dao->id
]['financial_type_id'], $taxRates)) {
256 // We are close to output/display here - so apply some rounding at output/display level - to not show Tax Rate in it's full 8 decimals
257 $lineItems[$dao->id
]['tax_rate'] = round($taxRates[$lineItems[$dao->id
]['financial_type_id']], 3);
260 // There is no Tax Rate associated with this Financial Type
261 $lineItems[$dao->id
]['tax_rate'] = FALSE;
263 $lineItems[$dao->id
]['subTotal'] = $lineItems[$dao->id
]['qty'] * $lineItems[$dao->id
]['unit_price'];
264 if ($lineItems[$dao->id
]['tax_amount'] != '') {
265 $getTaxDetails = TRUE;
269 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
270 $smarty = CRM_Core_Smarty
::singleton();
271 $smarty->assign('taxTerm', $taxTerm);
272 $smarty->assign('getTaxDetails', $getTaxDetails);
278 * This method will create the lineItem array required for
279 * processAmount method
282 * Price set field id.
283 * @param array $params
284 * Reference to form values.
285 * @param array $fields
286 * Reference to array of fields belonging.
287 * to the price set used for particular event
288 * @param array $values
289 * Reference to the values array(.
295 public static function format($fid, &$params, &$fields, &$values) {
296 if (empty($params["price_{$fid}"])) {
300 $optionIDs = implode(',', array_keys($params["price_{$fid}"]));
302 //lets first check in fun parameter,
303 //since user might modified w/ hooks.
305 if (array_key_exists('options', $fields)) {
306 $options = $fields['options'];
309 CRM_Price_BAO_PriceFieldValue
::getValues($fid, $options, 'weight', TRUE);
311 $fieldTitle = CRM_Utils_Array
::value('label', $fields);
313 $fieldTitle = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
316 foreach ($params["price_{$fid}"] as $oid => $qty) {
317 $price = $options[$oid]['amount'];
319 // lets clean the price in case it is not yet cleant
321 $price = CRM_Utils_Rule
::cleanMoney($price);
323 $participantsPerField = CRM_Utils_Array
::value('count', $options[$oid], 0);
325 $values[$oid] = array(
326 'price_field_id' => $fid,
327 'price_field_value_id' => $oid,
328 'label' => CRM_Utils_Array
::value('label', $options[$oid]),
329 'field_title' => $fieldTitle,
330 'description' => CRM_Utils_Array
::value('description', $options[$oid]),
332 'unit_price' => $price,
333 'line_total' => $qty * $price,
334 'participant_count' => $qty * $participantsPerField,
335 'max_value' => CRM_Utils_Array
::value('max_value', $options[$oid]),
336 'membership_type_id' => CRM_Utils_Array
::value('membership_type_id', $options[$oid]),
337 'membership_num_terms' => CRM_Utils_Array
::value('membership_num_terms', $options[$oid]),
338 'auto_renew' => CRM_Utils_Array
::value('auto_renew', $options[$oid]),
339 'html_type' => $fields['html_type'],
340 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $options[$oid]),
341 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $options[$oid]),
344 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
345 $values[$oid]['auto_renew'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
351 * Delete line items for given entity.
353 * @param int $entityId
354 * @param int $entityTable
358 public static function deleteLineItems($entityId, $entityTable) {
359 if (!$entityId ||
!$entityTable) {
363 if ($entityId && !is_array($entityId)) {
364 $entityId = array($entityId);
367 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
368 $dao = CRM_Core_DAO
::executeQuery($query);
373 * Process price set and line items.
375 * @param int $entityId
376 * @param array $lineItem
378 * @param object $contributionDetails
379 * @param string $entityTable
382 * @param bool $update
386 public static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
387 if (!$entityId ||
!is_array($lineItem)
388 || CRM_Utils_system
::isNull($lineItem)
393 foreach ($lineItem as $priceSetId => $values) {
398 foreach ($values as $line) {
399 $line['entity_table'] = $entityTable;
400 if (empty($line['entity_id'])) {
401 $line['entity_id'] = $entityId;
403 if (!empty($line['membership_type_id'])) {
404 $line['entity_table'] = 'civicrm_membership';
406 if (!empty($contributionDetails->id
)) {
407 $line['contribution_id'] = $contributionDetails->id
;
408 if ($line['entity_table'] == 'civicrm_contribution') {
409 $line['entity_id'] = $contributionDetails->id
;
413 // if financial type is not set and if price field value is NOT NULL
414 // get financial type id of price field value
415 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
416 $line['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
418 $lineItems = CRM_Price_BAO_LineItem
::create($line);
419 if (!$update && $contributionDetails) {
420 CRM_Financial_BAO_FinancialItem
::add($lineItems, $contributionDetails);
421 if (isset($line['tax_amount'])) {
422 CRM_Financial_BAO_FinancialItem
::add($lineItems, $contributionDetails, TRUE);
430 * @param int $entityId
431 * @param string $entityTable
433 * @param array $otherParams
435 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
436 if (!$entityId || CRM_Utils_System
::isNull($amount)) {
440 $from = " civicrm_line_item li
441 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
442 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
444 $set = " li.unit_price = %3,
445 li.line_total = %3 ";
447 $where = " li.entity_id = %1 AND
448 li.entity_table = %2 ";
451 1 => array($entityId, 'Integer'),
452 2 => array($entityTable, 'String'),
453 3 => array($amount, 'Float'),
456 if ($entityTable == 'civicrm_contribution') {
457 $entityName = 'default_contribution_amount';
458 $where .= " AND ps.name = %4 ";
459 $params[4] = array($entityName, 'String');
461 elseif ($entityTable == 'civicrm_participant') {
463 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
464 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
465 $set .= " ,li.label = %4,
466 li.price_field_value_id = cpfv.id ";
467 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
468 $amount = empty($amount) ?
0 : $amount;
470 4 => array($otherParams['fee_label'], 'String'),
471 5 => array($otherParams['event_id'], 'String'),
481 CRM_Core_DAO
::executeQuery($query, $params);
485 * Build line items array.
486 * @param array $params
489 * @param string $entityId
492 * @param string $entityTable
497 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
500 $priceSetDetails = CRM_Price_BAO_PriceSet
::getDefaultPriceSet($entityTable);
501 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
502 $financialType = CRM_Utils_Array
::value('financial_type_id', $params);
503 foreach ($priceSetDetails as $values) {
504 if ($entityTable == 'membership') {
505 if ($isRelatedID != $values['membership_type_id']) {
509 $totalAmount = $values['amount'];
511 $financialType = $values['financial_type_id'];
513 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
514 'price_field_id' => $values['priceFieldID'],
515 'price_field_value_id' => $values['priceFieldValueID'],
516 'label' => $values['label'],
518 'unit_price' => $totalAmount,
519 'line_total' => $totalAmount,
520 'financial_type_id' => $financialType,
521 'membership_type_id' => $values['membership_type_id'],
528 $totalEntityId = count($entityId);
529 foreach ($entityId as $id) {
530 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($id, $entityTable, NULL, TRUE, $isRelatedID);
531 foreach ($lineItems as $key => $values) {
532 if (!$setID && $values['price_field_id']) {
533 $setID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
534 $params['is_quick_config'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
536 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
537 && $totalEntityId == 1
539 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
541 $values['id'] = $key;
542 $params['line_item'][$setID][$key] = $values;