commiting uncommited changes on live site
[weblabels.fsf.org.git] / crm.fsf.org / 20131203 / files / sites / all / modules-new / 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 $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);
258 }
259 else {
260 // There is no Tax Rate associated with this Financial Type
261 $lineItems[$dao->id]['tax_rate'] = FALSE;
262 }
263 $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
264 if ($lineItems[$dao->id]['tax_amount'] != '') {
265 $getTaxDetails = TRUE;
266 }
267 }
268 if ($invoicing) {
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);
273 }
274 return $lineItems;
275 }
276
277 /**
278 * This method will create the lineItem array required for
279 * processAmount method
280 *
281 * @param int $fid
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(.
290 * this is
291 * lineItem array)
292 *
293 * @return void
294 */
295 public static function format($fid, &$params, &$fields, &$values) {
296 if (empty($params["price_{$fid}"])) {
297 return;
298 }
299
300 $optionIDs = implode(',', array_keys($params["price_{$fid}"]));
301
302 //lets first check in fun parameter,
303 //since user might modified w/ hooks.
304 $options = array();
305 if (array_key_exists('options', $fields)) {
306 $options = $fields['options'];
307 }
308 else {
309 CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
310 }
311 $fieldTitle = CRM_Utils_Array::value('label', $fields);
312 if (!$fieldTitle) {
313 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
314 }
315
316 foreach ($params["price_{$fid}"] as $oid => $qty) {
317 $price = $options[$oid]['amount'];
318
319 // lets clean the price in case it is not yet cleant
320 // CRM-10974
321 $price = CRM_Utils_Rule::cleanMoney($price);
322
323 $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
324
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]),
331 'qty' => $qty,
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]),
342 );
343
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');
346 }
347 }
348 }
349
350 /**
351 * Delete line items for given entity.
352 *
353 * @param int $entityId
354 * @param int $entityTable
355 *
356 * @return bool
357 */
358 public static function deleteLineItems($entityId, $entityTable) {
359 if (!$entityId || !$entityTable) {
360 return FALSE;
361 }
362
363 if ($entityId && !is_array($entityId)) {
364 $entityId = array($entityId);
365 }
366
367 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
368 $dao = CRM_Core_DAO::executeQuery($query);
369 return TRUE;
370 }
371
372 /**
373 * Process price set and line items.
374 *
375 * @param int $entityId
376 * @param array $lineItem
377 * Line item array.
378 * @param object $contributionDetails
379 * @param string $entityTable
380 * Entity table.
381 *
382 * @param bool $update
383 *
384 * @return void
385 */
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)
389 ) {
390 return;
391 }
392
393 foreach ($lineItem as $priceSetId => $values) {
394 if (!$priceSetId) {
395 continue;
396 }
397
398 foreach ($values as $line) {
399 $line['entity_table'] = $entityTable;
400 if (empty($line['entity_id'])) {
401 $line['entity_id'] = $entityId;
402 }
403 if (!empty($line['membership_type_id'])) {
404 $line['entity_table'] = 'civicrm_membership';
405 }
406 if (!empty($contributionDetails->id)) {
407 $line['contribution_id'] = $contributionDetails->id;
408 if ($line['entity_table'] == 'civicrm_contribution') {
409 $line['entity_id'] = $contributionDetails->id;
410 }
411 }
412
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');
417 }
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);
423 }
424 }
425 }
426 }
427 }
428
429 /**
430 * @param int $entityId
431 * @param string $entityTable
432 * @param $amount
433 * @param array $otherParams
434 */
435 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
436 if (!$entityId || CRM_Utils_System::isNull($amount)) {
437 return;
438 }
439
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 ";
443
444 $set = " li.unit_price = %3,
445 li.line_total = %3 ";
446
447 $where = " li.entity_id = %1 AND
448 li.entity_table = %2 ";
449
450 $params = array(
451 1 => array($entityId, 'Integer'),
452 2 => array($entityTable, 'String'),
453 3 => array($amount, 'Float'),
454 );
455
456 if ($entityTable == 'civicrm_contribution') {
457 $entityName = 'default_contribution_amount';
458 $where .= " AND ps.name = %4 ";
459 $params[4] = array($entityName, 'String');
460 }
461 elseif ($entityTable == 'civicrm_participant') {
462 $from .= "
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;
469 $params += array(
470 4 => array($otherParams['fee_label'], 'String'),
471 5 => array($otherParams['event_id'], 'String'),
472 );
473 }
474
475 $query = "
476 UPDATE $from
477 SET $set
478 WHERE $where
479 ";
480
481 CRM_Core_DAO::executeQuery($query, $params);
482 }
483
484 /**
485 * Build line items array.
486 * @param array $params
487 * Form values.
488 *
489 * @param string $entityId
490 * Entity id.
491 *
492 * @param string $entityTable
493 * Entity Table.
494 *
495 * @return void
496 */
497 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
498
499 if (!$entityId) {
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']) {
506 continue;
507 }
508 if (!$totalAmount) {
509 $totalAmount = $values['amount'];
510 }
511 $financialType = $values['financial_type_id'];
512 }
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'],
517 'qty' => 1,
518 'unit_price' => $totalAmount,
519 'line_total' => $totalAmount,
520 'financial_type_id' => $financialType,
521 'membership_type_id' => $values['membership_type_id'],
522 );
523 break;
524 }
525 }
526 else {
527 $setID = NULL;
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');
535 }
536 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
537 && $totalEntityId == 1
538 ) {
539 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
540 }
541 $values['id'] = $key;
542 $params['line_item'][$setID][$key] = $values;
543 }
544 }
545 }
546 }
547
548 }