3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 * Takes a bunch of params that are needed to match certain criteria and
88 * retrieves the relevant objects. Typically, the valid params are only
89 * price_field_id. This is the inverse function of create. It also
90 * stores all of the retrieved values in the default array.
92 * @param array $params
93 * (reference ) an assoc array of name/value pairs.
94 * @param array $defaults
95 * (reference ) an assoc array to hold the flattened values.
97 * @return CRM_Price_BAO_LineItem
99 public static function retrieve(&$params, &$defaults) {
100 $lineItem = new CRM_Price_BAO_LineItem();
101 $lineItem->copyValues($params);
102 if ($lineItem->find(TRUE)) {
103 CRM_Core_DAO
::storeValues($lineItem, $defaults);
110 * @param int $entityId
111 * @param $entityTable
113 * @return null|string
115 public static function getLineTotal($entityId, $entityTable) {
116 $sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
117 FROM civicrm_line_item li
118 WHERE li.entity_table = '{$entityTable}'
119 AND li.entity_id = {$entityId}
121 $lineItemTotal = CRM_Core_DAO
::singleValueQuery($sqlLineItemTotal);
122 return $lineItemTotal;
126 * Wrapper for line item retrieval when contribution ID is known
127 * @param int $contributionID
131 public static function getLineItemsByContributionID($contributionID) {
132 return self
::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
136 * Given a participant id/contribution id,
137 * return contribution/fee line items
139 * @param int $entityId
140 * participant/contribution id.
141 * @param string $entity
142 * participant/contribution.
144 * @param null $isQuick
145 * @param bool $isQtyZero
146 * @param bool $relatedEntity
148 * @param string $overrideWhereClause
149 * E.g "WHERE contribution id = 7 " per the getLineItemsByContributionID wrapper.
150 * 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
151 * when we don't want it's entity-id magix
154 * Array of line items
156 public static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL, $isQtyZero = TRUE, $relatedEntity = FALSE, $overrideWhereClause = '') {
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 $orderByClause = " ORDER BY pf.weight, pfv.weight";
194 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
195 $whereClause .= " and cps.is_quick_config = 0";
199 $whereClause .= " and li.qty != 0";
202 $lineItems = array();
204 if (!$entityId ||
!$entity ||
!$fromClause) {
209 1 => array($entityId, 'Integer'),
210 2 => array($entity, 'Text'),
213 $getTaxDetails = FALSE;
214 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
215 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
216 if ($overrideWhereClause) {
217 $whereClause = $overrideWhereClause;
220 $dao = CRM_Core_DAO
::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
221 while ($dao->fetch()) {
225 $lineItems[$dao->id
] = array(
226 'qty' => (float) $dao->qty
,
227 'label' => $dao->label
,
228 'unit_price' => $dao->unit_price
,
229 'line_total' => $dao->line_total
,
230 'price_field_id' => $dao->price_field_id
,
231 'participant_count' => $dao->participant_count
,
232 'price_field_value_id' => $dao->price_field_value_id
,
233 'field_title' => $dao->field_title
,
234 'html_type' => $dao->html_type
,
235 'description' => $dao->description
,
236 // 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
237 // we also JUST WANT TO KNOW the the entity_id in the DB
238 'entity_id' => empty($overrideWhereClause) ?
$entityId : $dao->entity_id
,
239 'entity_table' => $dao->entity_table
,
240 'contribution_id' => $dao->contribution_id
,
241 'financial_type_id' => $dao->financial_type_id
,
242 'membership_type_id' => $dao->membership_type_id
,
243 'membership_num_terms' => $dao->membership_num_terms
,
244 'tax_amount' => $dao->tax_amount
,
246 $lineItems[$dao->id
]['tax_rate'] = CRM_Price_BAO_LineItem
::calculateTaxRate($lineItems[$dao->id
]);
247 $lineItems[$dao->id
]['subTotal'] = $lineItems[$dao->id
]['qty'] * $lineItems[$dao->id
]['unit_price'];
248 if ($lineItems[$dao->id
]['tax_amount'] != '') {
249 $getTaxDetails = TRUE;
253 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
254 $smarty = CRM_Core_Smarty
::singleton();
255 $smarty->assign('taxTerm', $taxTerm);
256 $smarty->assign('getTaxDetails', $getTaxDetails);
262 * This method will create the lineItem array required for
263 * processAmount method
266 * Price set field id.
267 * @param array $params
268 * Reference to form values.
269 * @param array $fields
270 * Reference to array of fields belonging.
271 * to the price set used for particular event
272 * @param array $values
273 * Reference to the values array(.
279 public static function format($fid, &$params, &$fields, &$values) {
280 if (empty($params["price_{$fid}"])) {
284 $optionIDs = implode(',', array_keys($params["price_{$fid}"]));
286 //lets first check in fun parameter,
287 //since user might modified w/ hooks.
289 if (array_key_exists('options', $fields)) {
290 $options = $fields['options'];
293 CRM_Price_BAO_PriceFieldValue
::getValues($fid, $options, 'weight', TRUE);
295 $fieldTitle = CRM_Utils_Array
::value('label', $fields);
297 $fieldTitle = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
300 foreach ($params["price_{$fid}"] as $oid => $qty) {
301 $price = $options[$oid]['amount'];
303 // lets clean the price in case it is not yet cleant
305 $price = CRM_Utils_Rule
::cleanMoney($price);
307 $participantsPerField = CRM_Utils_Array
::value('count', $options[$oid], 0);
309 $values[$oid] = array(
310 'price_field_id' => $fid,
311 'price_field_value_id' => $oid,
312 'label' => CRM_Utils_Array
::value('label', $options[$oid]),
313 'field_title' => $fieldTitle,
314 'description' => CRM_Utils_Array
::value('description', $options[$oid]),
316 'unit_price' => $price,
317 'line_total' => $qty * $price,
318 'participant_count' => $qty * $participantsPerField,
319 'max_value' => CRM_Utils_Array
::value('max_value', $options[$oid]),
320 'membership_type_id' => CRM_Utils_Array
::value('membership_type_id', $options[$oid]),
321 'membership_num_terms' => CRM_Utils_Array
::value('membership_num_terms', $options[$oid]),
322 'auto_renew' => CRM_Utils_Array
::value('auto_renew', $options[$oid]),
323 'html_type' => $fields['html_type'],
324 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $options[$oid]),
325 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $options[$oid]),
328 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
329 $values[$oid]['auto_renew'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
335 * Delete line items for given entity.
337 * @param int $entityId
338 * @param int $entityTable
342 public static function deleteLineItems($entityId, $entityTable) {
343 if (!$entityId ||
!$entityTable) {
347 if ($entityId && !is_array($entityId)) {
348 $entityId = array($entityId);
351 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
352 $dao = CRM_Core_DAO
::executeQuery($query);
357 * Process price set and line items.
359 * @param int $entityId
360 * @param array $lineItem
362 * @param object $contributionDetails
363 * @param string $entityTable
366 * @param bool $update
370 public static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
371 if (!$entityId ||
!is_array($lineItem)
372 || CRM_Utils_system
::isNull($lineItem)
377 foreach ($lineItem as $priceSetId => $values) {
382 foreach ($values as $line) {
383 $line['entity_table'] = $entityTable;
384 if (empty($line['entity_id'])) {
385 $line['entity_id'] = $entityId;
387 if (!empty($line['membership_type_id'])) {
388 $line['entity_table'] = 'civicrm_membership';
390 if (!empty($contributionDetails->id
)) {
391 $line['contribution_id'] = $contributionDetails->id
;
392 if ($line['entity_table'] == 'civicrm_contribution') {
393 $line['entity_id'] = $contributionDetails->id
;
397 // if financial type is not set and if price field value is NOT NULL
398 // get financial type id of price field value
399 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
400 $line['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
402 $lineItems = CRM_Price_BAO_LineItem
::create($line);
403 if (!$update && $contributionDetails) {
404 CRM_Financial_BAO_FinancialItem
::add($lineItems, $contributionDetails);
405 if (isset($line['tax_amount'])) {
406 CRM_Financial_BAO_FinancialItem
::add($lineItems, $contributionDetails, TRUE);
414 * @param int $entityId
415 * @param string $entityTable
417 * @param array $otherParams
419 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
420 if (!$entityId || CRM_Utils_System
::isNull($amount)) {
424 $from = " civicrm_line_item li
425 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
426 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
428 $set = " li.unit_price = %3,
429 li.line_total = %3 ";
431 $where = " li.entity_id = %1 AND
432 li.entity_table = %2 ";
435 1 => array($entityId, 'Integer'),
436 2 => array($entityTable, 'String'),
437 3 => array($amount, 'Float'),
440 if ($entityTable == 'civicrm_contribution') {
441 $entityName = 'default_contribution_amount';
442 $where .= " AND ps.name = %4 ";
443 $params[4] = array($entityName, 'String');
445 elseif ($entityTable == 'civicrm_participant') {
447 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
448 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
449 $set .= " ,li.label = %4,
450 li.price_field_value_id = cpfv.id ";
451 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
452 $amount = empty($amount) ?
0 : $amount;
454 4 => array($otherParams['fee_label'], 'String'),
455 5 => array($otherParams['event_id'], 'String'),
465 CRM_Core_DAO
::executeQuery($query, $params);
469 * Build line items array.
470 * @param array $params
473 * @param string $entityId
476 * @param string $entityTable
481 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
484 $priceSetDetails = CRM_Price_BAO_PriceSet
::getDefaultPriceSet($entityTable);
485 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
486 $financialType = CRM_Utils_Array
::value('financial_type_id', $params);
487 foreach ($priceSetDetails as $values) {
488 if ($entityTable == 'membership') {
489 if ($isRelatedID != $values['membership_type_id']) {
493 $totalAmount = $values['amount'];
495 $financialType = $values['financial_type_id'];
497 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
498 'price_field_id' => $values['priceFieldID'],
499 'price_field_value_id' => $values['priceFieldValueID'],
500 'label' => $values['label'],
502 'unit_price' => $totalAmount,
503 'line_total' => $totalAmount,
504 'financial_type_id' => $financialType,
505 'membership_type_id' => $values['membership_type_id'],
512 $totalEntityId = count($entityId);
513 foreach ($entityId as $id) {
514 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($id, $entityTable, NULL, TRUE, $isRelatedID);
515 foreach ($lineItems as $key => $values) {
516 if (!$setID && $values['price_field_id']) {
517 $setID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
518 $params['is_quick_config'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
520 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
521 && $totalEntityId == 1
523 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
525 $values['id'] = $key;
526 $params['line_item'][$setID][$key] = $values;
533 * Calculate tax rate in percentage
535 * @param array $lineItemId
536 * An assoc array of lineItem.
541 public static function calculateTaxRate($lineItemId) {
542 if ($lineItemId['unit_price'] == 0) {
545 if ($lineItemId['html_type'] == 'Text') {
546 $tax = $lineItemId['tax_amount'] / ($lineItemId['unit_price'] * $lineItemId['qty']) * 100;
549 $tax = ($lineItemId['tax_amount'] / $lineItemId['unit_price']) * 100;