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 (reference) an assoc array of name/value pairs
53 * @return CRM_Price_DAO_LineItem object
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 (reference ) an assoc array of name/value pairs
93 * @param array $defaults (reference ) an assoc array to hold the flattened values
95 * @return CRM_Price_BAO_LineItem object
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 $entityId int participant/contribution id
139 * @param $entity string participant/contribution.
141 * @param null $isQuick
142 * @param bool $isQtyZero
143 * @param bool $relatedEntity
145 * @param string $overrideWhereClause e.g "WHERE contribution id = 7 " per the getLineItemsByContributionID wrapper.
146 * 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
147 * when we don't want it's entity-id magix
149 * @return array of line items
151 public static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL , $isQtyZero = TRUE, $relatedEntity = FALSE, $overrideWhereClause = '') {
152 $whereClause = $fromClause = NULL;
162 pf.label as field_title,
164 pfv.membership_type_id,
165 pfv.membership_num_terms,
167 li.participant_count,
168 li.price_field_value_id,
169 li.financial_type_id,
173 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
174 if ($relatedEntity) {
175 $condition = "li.contribution_id = %2.id ";
179 FROM civicrm_%2 as %2
180 LEFT JOIN civicrm_line_item li ON ({$condition})
181 LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )
182 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
186 $orderByClause = " ORDER BY pf.weight, pfv.weight";
189 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
190 $whereClause .= " and cps.is_quick_config = 0";
194 $whereClause .= " and li.qty != 0";
197 $lineItems = array();
199 if (!$entityId ||
!$entity ||
!$fromClause) {
204 1 => array($entityId, 'Integer'),
205 2 => array($entity, 'Text'),
208 $getTaxDetails = FALSE;
209 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,'contribution_invoice_settings');
210 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
211 if ($overrideWhereClause) {
212 $whereClause = $overrideWhereClause;
215 $dao = CRM_Core_DAO
::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
216 while ($dao->fetch()) {
220 $lineItems[$dao->id
] = array(
221 'qty' => (float) $dao->qty
,
222 'label' => $dao->label
,
223 'unit_price' => $dao->unit_price
,
224 'line_total' => $dao->line_total
,
225 'price_field_id' => $dao->price_field_id
,
226 'participant_count' => $dao->participant_count
,
227 'price_field_value_id' => $dao->price_field_value_id
,
228 'field_title' => $dao->field_title
,
229 'html_type' => $dao->html_type
,
230 'description' => $dao->description
,
231 // 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
232 // we also JUST WANT TO KNOW the the entity_id in the DB
233 'entity_id' => empty($overrideWhereClause) ?
$entityId : $dao->entity_id
,
234 'entity_table' => $dao->entity_table
,
235 'contribution_id' => $dao->contribution_id
,
236 'financial_type_id' => $dao->financial_type_id
,
237 'membership_type_id' => $dao->membership_type_id
,
238 'membership_num_terms' => $dao->membership_num_terms
,
239 'tax_amount' => $dao->tax_amount
,
241 $lineItems[$dao->id
]['tax_rate'] = CRM_Price_BAO_LineItem
::calculateTaxRate($lineItems[$dao->id
]);
242 $lineItems[$dao->id
]['subTotal'] = $lineItems[$dao->id
]['qty'] * $lineItems[$dao->id
]['unit_price'];
243 if ($lineItems[$dao->id
]['tax_amount'] != '') {
244 $getTaxDetails = TRUE;
248 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
249 $smarty = CRM_Core_Smarty
::singleton();
250 $smarty->assign('taxTerm', $taxTerm);
251 $smarty->assign('getTaxDetails', $getTaxDetails);
257 * This method will create the lineItem array required for
258 * processAmount method
260 * @param int $fid price set field id
261 * @param array $params reference to form values
262 * @param array $fields reference to array of fields belonging
263 * to the price set used for particular event
264 * @param array $values reference to the values array(
270 public static function format($fid, &$params, &$fields, &$values) {
271 if (empty($params["price_{$fid}"])) {
275 $optionIDs = implode(',', array_keys($params["price_{$fid}"]));
277 //lets first check in fun parameter,
278 //since user might modified w/ hooks.
280 if (array_key_exists('options', $fields)) {
281 $options = $fields['options'];
284 CRM_Price_BAO_PriceFieldValue
::getValues($fid, $options, 'weight', TRUE);
286 $fieldTitle = CRM_Utils_Array
::value('label', $fields);
288 $fieldTitle = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
291 foreach ($params["price_{$fid}"] as $oid => $qty) {
292 $price = $options[$oid]['amount'];
294 // lets clean the price in case it is not yet cleant
296 $price = CRM_Utils_Rule
::cleanMoney($price);
298 $participantsPerField = CRM_Utils_Array
::value('count', $options[$oid], 0);
300 $values[$oid] = array(
301 'price_field_id' => $fid,
302 'price_field_value_id' => $oid,
303 'label' => CRM_Utils_Array
::value('label', $options[$oid]),
304 'field_title' => $fieldTitle,
305 'description' => CRM_Utils_Array
::value('description', $options[$oid]),
307 'unit_price' => $price,
308 'line_total' => $qty * $price,
309 'participant_count' => $qty * $participantsPerField,
310 'max_value' => CRM_Utils_Array
::value('max_value', $options[$oid]),
311 'membership_type_id' => CRM_Utils_Array
::value('membership_type_id', $options[$oid]),
312 'membership_num_terms' => CRM_Utils_Array
::value('membership_num_terms', $options[$oid]),
313 'auto_renew' => CRM_Utils_Array
::value('auto_renew', $options[$oid]),
314 'html_type' => $fields['html_type'],
315 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $options[$oid]),
316 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $options[$oid]),
319 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
320 $values[$oid]['auto_renew'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
326 * Delete line items for given entity.
328 * @param int $entityId
329 * @param int $entityTable
334 public static function deleteLineItems($entityId, $entityTable) {
335 if (!$entityId ||
!$entityTable) {
339 if ($entityId && !is_array($entityId)) {
340 $entityId = array($entityId);
343 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
344 $dao = CRM_Core_DAO
::executeQuery($query);
349 * Process price set and line items.
351 * @param int $entityId
352 * @param array $lineItem line item array
353 * @param object $contributionDetails
354 * @param string $entityTable entity table
356 * @param bool $update
361 public static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
362 if (!$entityId ||
!is_array($lineItem)
363 || CRM_Utils_system
::isNull($lineItem)
368 foreach ($lineItem as $priceSetId => $values) {
373 foreach ($values as $line) {
374 $line['entity_table'] = $entityTable;
375 if (empty($line['entity_id'])) {
376 $line['entity_id'] = $entityId;
378 if(!empty($line['membership_type_id'])) {
379 $line['entity_table'] = 'civicrm_membership';
381 if (!empty($contributionDetails->id
)) {
382 $line['contribution_id'] = $contributionDetails->id
;
383 if ($line['entity_table'] == 'civicrm_contribution') {
384 $line['entity_id'] = $contributionDetails->id
;
388 // if financial type is not set and if price field value is NOT NULL
389 // get financial type id of price field value
390 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
391 $line['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
393 $lineItems = CRM_Price_BAO_LineItem
::create($line);
394 if (!$update && $contributionDetails) {
395 CRM_Financial_BAO_FinancialItem
::add($lineItems, $contributionDetails);
396 if (isset($line['tax_amount'])) {
397 CRM_Financial_BAO_FinancialItem
::add($lineItems, $contributionDetails, TRUE);
405 * @param int $entityId
406 * @param string $entityTable
408 * @param array $otherParams
410 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
411 if (!$entityId || CRM_Utils_System
::isNull($amount))
414 $from = " civicrm_line_item li
415 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
416 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
418 $set = " li.unit_price = %3,
419 li.line_total = %3 ";
421 $where = " li.entity_id = %1 AND
422 li.entity_table = %2 ";
425 1 => array($entityId, 'Integer'),
426 2 => array($entityTable, 'String'),
427 3 => array($amount, 'Float'),
430 if ($entityTable == 'civicrm_contribution') {
431 $entityName = 'default_contribution_amount';
432 $where .= " AND ps.name = %4 ";
433 $params[4] = array($entityName, 'String');
435 elseif ($entityTable == 'civicrm_participant') {
437 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
438 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
439 $set .= " ,li.label = %4,
440 li.price_field_value_id = cpfv.id ";
441 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
442 $amount = empty($amount) ?
0: $amount;
444 4 => array($otherParams['fee_label'], 'String'),
445 5 => array($otherParams['event_id'], 'String'),
455 CRM_Core_DAO
::executeQuery($query, $params);
459 * Build line items array.
460 * @param array $params form values
462 * @param string $entityId entity id
464 * @param string $entityTable entity Table
469 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
472 $priceSetDetails = CRM_Price_BAO_PriceSet
::getDefaultPriceSet($entityTable);
473 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
474 $financialType = CRM_Utils_Array
::value('financial_type_id', $params);
475 foreach ($priceSetDetails as $values) {
476 if ($entityTable == 'membership') {
477 if ($isRelatedID != $values['membership_type_id']) {
481 $totalAmount = $values['amount'];
483 $financialType = $values['financial_type_id'];
485 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
486 'price_field_id' => $values['priceFieldID'],
487 'price_field_value_id' => $values['priceFieldValueID'],
488 'label' => $values['label'],
490 'unit_price' => $totalAmount,
491 'line_total' => $totalAmount,
492 'financial_type_id' => $financialType,
493 'membership_type_id' => $values['membership_type_id']
500 $totalEntityId = count($entityId);
501 foreach ($entityId as $id) {
502 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($id, $entityTable, NULL, TRUE, $isRelatedID);
503 foreach ($lineItems as $key => $values) {
504 if (!$setID && $values['price_field_id']) {
505 $setID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
506 $params['is_quick_config'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
508 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
509 && $totalEntityId == 1) {
510 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
512 $values['id'] = $key;
513 $params['line_item'][$setID][$key] = $values;
520 * Calculate tax rate in percentage
522 * @param $lineItemId an assoc array of lineItem
528 public static function calculateTaxRate($lineItemId) {
529 if ($lineItemId['unit_price'] == 0) {
532 if ($lineItemId['html_type'] == 'Text') {
533 $tax = $lineItemId['tax_amount']/($lineItemId['unit_price'] * $lineItemId['qty'])*100;
536 $tax = ($lineItemId['tax_amount']/$lineItemId['unit_price']) * 100;