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