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, $params);
80 CRM_Utils_Hook
::post('create', 'LineItem', $params['entity_id'], $params);
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
153 * Array of line items
155 public static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL, $isQtyZero = TRUE, $relatedEntity = FALSE, $overrideWhereClause = '') {
156 $whereClause = $fromClause = NULL;
166 pf.label as field_title,
168 pfv.membership_type_id,
169 pfv.membership_num_terms,
171 li.participant_count,
172 li.price_field_value_id,
173 li.financial_type_id,
177 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
178 if ($relatedEntity) {
179 $condition = "li.contribution_id = %2.id ";
183 FROM civicrm_%2 as %2
184 LEFT JOIN civicrm_line_item li ON ({$condition})
185 LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )
186 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
190 if ($entity == 'participant') {
191 $additionalParticipantIDs = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
192 if (!empty($additionalParticipantIDs)) {
193 $whereClause = "WHERE %2.id IN (%1, " . implode(', ', $additionalParticipantIDs) . ")";
197 $orderByClause = " ORDER BY pf.weight, pfv.weight";
200 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
201 $whereClause .= " and cps.is_quick_config = 0";
205 $whereClause .= " and li.qty != 0";
208 $lineItems = array();
210 if (!$entityId ||
!$entity ||
!$fromClause) {
215 1 => array($entityId, 'Integer'),
216 2 => array($entity, 'Text'),
219 $getTaxDetails = FALSE;
220 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
221 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
222 if ($overrideWhereClause) {
223 $whereClause = $overrideWhereClause;
226 $dao = CRM_Core_DAO
::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
227 while ($dao->fetch()) {
231 $lineItems[$dao->id
] = array(
232 'qty' => (float) $dao->qty
,
233 'label' => $dao->label
,
234 'unit_price' => $dao->unit_price
,
235 'line_total' => $dao->line_total
,
236 'price_field_id' => $dao->price_field_id
,
237 'participant_count' => $dao->participant_count
,
238 'price_field_value_id' => $dao->price_field_value_id
,
239 'field_title' => $dao->field_title
,
240 'html_type' => $dao->html_type
,
241 'description' => $dao->description
,
242 // 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
243 // we also JUST WANT TO KNOW the the entity_id in the DB
244 'entity_id' => empty($overrideWhereClause) ?
$entityId : $dao->entity_id
,
245 'entity_table' => $dao->entity_table
,
246 'contribution_id' => $dao->contribution_id
,
247 'financial_type_id' => $dao->financial_type_id
,
248 'membership_type_id' => $dao->membership_type_id
,
249 'membership_num_terms' => $dao->membership_num_terms
,
250 'tax_amount' => $dao->tax_amount
,
252 $lineItems[$dao->id
]['tax_rate'] = CRM_Price_BAO_LineItem
::calculateTaxRate($lineItems[$dao->id
]);
253 $lineItems[$dao->id
]['subTotal'] = $lineItems[$dao->id
]['qty'] * $lineItems[$dao->id
]['unit_price'];
254 if ($lineItems[$dao->id
]['tax_amount'] != '') {
255 $getTaxDetails = TRUE;
259 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
260 $smarty = CRM_Core_Smarty
::singleton();
261 $smarty->assign('taxTerm', $taxTerm);
262 $smarty->assign('getTaxDetails', $getTaxDetails);
268 * This method will create the lineItem array required for
269 * processAmount method
272 * Price set field id.
273 * @param array $params
274 * Reference to form values.
275 * @param array $fields
276 * Reference to array of fields belonging.
277 * to the price set used for particular event
278 * @param array $values
279 * Reference to the values array(.
285 public static function format($fid, &$params, &$fields, &$values) {
286 if (empty($params["price_{$fid}"])) {
290 $optionIDs = implode(',', array_keys($params["price_{$fid}"]));
292 //lets first check in fun parameter,
293 //since user might modified w/ hooks.
295 if (array_key_exists('options', $fields)) {
296 $options = $fields['options'];
299 CRM_Price_BAO_PriceFieldValue
::getValues($fid, $options, 'weight', TRUE);
301 $fieldTitle = CRM_Utils_Array
::value('label', $fields);
303 $fieldTitle = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
306 foreach ($params["price_{$fid}"] as $oid => $qty) {
307 $price = $options[$oid]['amount'];
309 // lets clean the price in case it is not yet cleant
311 $price = CRM_Utils_Rule
::cleanMoney($price);
313 $participantsPerField = CRM_Utils_Array
::value('count', $options[$oid], 0);
315 $values[$oid] = array(
316 'price_field_id' => $fid,
317 'price_field_value_id' => $oid,
318 'label' => CRM_Utils_Array
::value('label', $options[$oid]),
319 'field_title' => $fieldTitle,
320 'description' => CRM_Utils_Array
::value('description', $options[$oid]),
322 'unit_price' => $price,
323 'line_total' => $qty * $price,
324 'participant_count' => $qty * $participantsPerField,
325 'max_value' => CRM_Utils_Array
::value('max_value', $options[$oid]),
326 'membership_type_id' => CRM_Utils_Array
::value('membership_type_id', $options[$oid]),
327 'membership_num_terms' => CRM_Utils_Array
::value('membership_num_terms', $options[$oid]),
328 'auto_renew' => CRM_Utils_Array
::value('auto_renew', $options[$oid]),
329 'html_type' => $fields['html_type'],
330 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $options[$oid]),
331 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $options[$oid]),
334 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
335 $values[$oid]['auto_renew'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
341 * Delete line items for given entity.
343 * @param int $entityId
344 * @param int $entityTable
348 public static function deleteLineItems($entityId, $entityTable) {
349 if (!$entityId ||
!$entityTable) {
353 if ($entityId && !is_array($entityId)) {
354 $entityId = array($entityId);
357 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
358 $dao = CRM_Core_DAO
::executeQuery($query);
363 * Process price set and line items.
365 * @param int $entityId
366 * @param array $lineItem
368 * @param object $contributionDetails
369 * @param string $entityTable
372 * @param bool $update
376 public static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
377 if (!$entityId ||
!is_array($lineItem)
378 || CRM_Utils_system
::isNull($lineItem)
383 foreach ($lineItem as $priceSetId => $values) {
388 foreach ($values as $line) {
389 $line['entity_table'] = $entityTable;
390 if (empty($line['entity_id'])) {
391 $line['entity_id'] = $entityId;
393 if (!empty($line['membership_type_id'])) {
394 $line['entity_table'] = 'civicrm_membership';
396 if (!empty($contributionDetails->id
)) {
397 $line['contribution_id'] = $contributionDetails->id
;
398 if ($line['entity_table'] == 'civicrm_contribution') {
399 $line['entity_id'] = $contributionDetails->id
;
403 // if financial type is not set and if price field value is NOT NULL
404 // get financial type id of price field value
405 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
406 $line['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
408 $lineItems = CRM_Price_BAO_LineItem
::create($line);
409 if (!$update && $contributionDetails) {
410 CRM_Financial_BAO_FinancialItem
::add($lineItems, $contributionDetails);
411 if (isset($line['tax_amount'])) {
412 CRM_Financial_BAO_FinancialItem
::add($lineItems, $contributionDetails, TRUE);
420 * @param int $entityId
421 * @param string $entityTable
423 * @param array $otherParams
425 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
426 if (!$entityId || CRM_Utils_System
::isNull($amount)) {
430 $from = " civicrm_line_item li
431 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
432 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
434 $set = " li.unit_price = %3,
435 li.line_total = %3 ";
437 $where = " li.entity_id = %1 AND
438 li.entity_table = %2 ";
441 1 => array($entityId, 'Integer'),
442 2 => array($entityTable, 'String'),
443 3 => array($amount, 'Float'),
446 if ($entityTable == 'civicrm_contribution') {
447 $entityName = 'default_contribution_amount';
448 $where .= " AND ps.name = %4 ";
449 $params[4] = array($entityName, 'String');
451 elseif ($entityTable == 'civicrm_participant') {
453 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
454 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
455 $set .= " ,li.label = %4,
456 li.price_field_value_id = cpfv.id ";
457 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
458 $amount = empty($amount) ?
0 : $amount;
460 4 => array($otherParams['fee_label'], 'String'),
461 5 => array($otherParams['event_id'], 'String'),
471 CRM_Core_DAO
::executeQuery($query, $params);
475 * Build line items array.
476 * @param array $params
479 * @param string $entityId
482 * @param string $entityTable
487 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
490 $priceSetDetails = CRM_Price_BAO_PriceSet
::getDefaultPriceSet($entityTable);
491 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
492 $financialType = CRM_Utils_Array
::value('financial_type_id', $params);
493 foreach ($priceSetDetails as $values) {
494 if ($entityTable == 'membership') {
495 if ($isRelatedID != $values['membership_type_id']) {
499 $totalAmount = $values['amount'];
501 $financialType = $values['financial_type_id'];
503 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
504 'price_field_id' => $values['priceFieldID'],
505 'price_field_value_id' => $values['priceFieldValueID'],
506 'label' => $values['label'],
508 'unit_price' => $totalAmount,
509 'line_total' => $totalAmount,
510 'financial_type_id' => $financialType,
511 'membership_type_id' => $values['membership_type_id'],
518 $totalEntityId = count($entityId);
519 foreach ($entityId as $id) {
520 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($id, $entityTable, NULL, TRUE, $isRelatedID);
521 foreach ($lineItems as $key => $values) {
522 if (!$setID && $values['price_field_id']) {
523 $setID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
524 $params['is_quick_config'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
526 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
527 && $totalEntityId == 1
529 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
531 $values['id'] = $key;
532 $params['line_item'][$setID][$key] = $values;
539 * Calculate tax rate in percentage.
541 * @param array $lineItemId
542 * An assoc array of lineItem.
547 public static function calculateTaxRate($lineItemId) {
548 if ($lineItemId['unit_price'] == 0) {
551 if ($lineItemId['html_type'] == 'Text') {
552 $tax = round($lineItemId['tax_amount'] / ($lineItemId['unit_price'] * $lineItemId['qty']) * 100, 2);
555 $tax = round(($lineItemId['tax_amount'] / $lineItemId['unit_price']) * 100, 2);