-- fixed code to save line item when contribution is updated for membership, CRM...
[civicrm-core.git] / CRM / Price / BAO / LineItem.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
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 */
46class CRM_Price_BAO_LineItem extends CRM_Price_DAO_LineItem {
47
48 /**
49 * Creates a new entry in the database.
50 *
51 * @param array $params (reference) an assoc array of name/value pairs
52 *
53 * @return object CRM_Price_DAO_LineItem object
54 * @access public
55 * @static
56 */
57 static function create(&$params) {
22fe049d
PN
58 $id = CRM_Utils_Array::value('id', $params);
59 if ($id) {
60 CRM_Utils_Hook::pre('edit', 'LineItem', $id, $params);
61 }
62 else {
63 CRM_Utils_Hook::pre('create', 'LineItem', $params['entity_id'], $params);
64 }
65
66 // unset entity table and entity id in $params
67 // we never update the entity table and entity id during update mode
68 if ($id) {
69 unset($params['entity_id'], $params['entity_table']);
70 }
421dfaa6 71
6a488035
TO
72 $lineItemBAO = new CRM_Price_BAO_LineItem();
73 $lineItemBAO->copyValues($params);
74
75 $return = $lineItemBAO->save();
76
22fe049d
PN
77 if ($id) {
78 CRM_Utils_Hook::post('edit', 'LineItem', $id, $params);
79 }
80 else {
81 CRM_Utils_Hook::post('create', 'LineItem', $params['entity_id'], $params);
82 }
6a488035
TO
83
84 return $return;
85 }
86
87 /**
88 * Takes a bunch of params that are needed to match certain criteria and
89 * retrieves the relevant objects. Typically, the valid params are only
90 * price_field_id. This is the inverse function of create. It also
91 * stores all of the retrieved values in the default array.
92 *
93 * @param array $params (reference ) an assoc array of name/value pairs
94 * @param array $defaults (reference ) an assoc array to hold the flattened values
95 *
96 * @return object CRM_Price_BAO_LineItem object
97 * @access public
98 * @static
99 */
100 static function retrieve(&$params, &$defaults) {
101 $lineItem = new CRM_Price_BAO_LineItem();
102 $lineItem->copyValues($params);
103 if ($lineItem->find(TRUE)) {
104 CRM_Core_DAO::storeValues($lineItem, $defaults);
105 return $lineItem;
106 }
107 return NULL;
108 }
109
ffd93213
EM
110 /**
111 * @param $entityId
112 * @param $entityTable
113 *
114 * @return null|string
115 */
bc2eeabb
PJ
116 static function getLineTotal($entityId, $entityTable) {
117 $sqlLineItemTotal = "SELECT SUM(li.line_total)
118FROM civicrm_line_item li
ae53df5f
PJ
119WHERE li.entity_table = '{$entityTable}'
120AND li.entity_id = {$entityId}
121";
bc2eeabb
PJ
122 $lineItemTotal = CRM_Core_DAO::singleValueQuery($sqlLineItemTotal);
123 return $lineItemTotal;
124 }
125
6a488035
TO
126 /**
127 * Given a participant id/contribution id,
128 * return contribution/fee line items
129 *
130 * @param $entityId int participant/contribution id
131 * @param $entity string participant/contribution.
132 *
dd244018
EM
133 * @param null $isQuick
134 * @param bool $isQtyZero
0d6f29cd 135 * @param bool $relatedEntity
dd244018 136 *
6a488035
TO
137 * @return array of line items
138 */
0d6f29cd 139 static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL , $isQtyZero = TRUE, $relatedEntity = FALSE) {
6a488035
TO
140 $selectClause = $whereClause = $fromClause = NULL;
141 $selectClause = "
142 SELECT li.id,
143 li.label,
a7886853 144 li.contribution_id,
6a488035
TO
145 li.qty,
146 li.unit_price,
147 li.line_total,
148 pf.label as field_title,
149 pf.html_type,
150 pfv.membership_type_id,
9c09f5b7 151 pfv.membership_num_terms,
6a488035
TO
152 li.price_field_id,
153 li.participant_count,
154 li.price_field_value_id,
bf45dbe8 155 li.financial_type_id,
6a488035
TO
156 pfv.description";
157
0d6f29cd 158 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
159 if ($relatedEntity) {
160 $condition = "li.contribution_id = %2.id ";
161 }
162
6a488035
TO
163 $fromClause = "
164 FROM civicrm_%2 as %2
0d6f29cd 165 LEFT JOIN civicrm_line_item li ON ({$condition})
6a488035
TO
166 LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )
167 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
168 $whereClause = "
169 WHERE %2.id = %1";
170
e68f41a5
DG
171 $orderByClause = " ORDER BY pf.weight, pfv.weight";
172
6a488035
TO
173 if ($isQuick) {
174 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
175 $whereClause .= " and cps.is_quick_config = 0";
176 }
d5397f2f
PJ
177
178 if (!$isQtyZero) {
179 $whereClause .= " and li.qty != 0";
180 }
181
6a488035
TO
182 $lineItems = array();
183
184 if (!$entityId || !$entity || !$fromClause) {
185 return $lineItems;
186 }
187
188 $params = array(
189 1 => array($entityId, 'Integer'),
190 2 => array($entity, 'Text'),
191 );
192
e68f41a5 193 $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
6a488035
TO
194 while ($dao->fetch()) {
195 if (!$dao->id) {
196 continue;
197 }
198 $lineItems[$dao->id] = array(
199 'qty' => $dao->qty,
200 'label' => $dao->label,
201 'unit_price' => $dao->unit_price,
202 'line_total' => $dao->line_total,
203 'price_field_id' => $dao->price_field_id,
204 'participant_count' => $dao->participant_count,
205 'price_field_value_id' => $dao->price_field_value_id,
206 'field_title' => $dao->field_title,
207 'html_type' => $dao->html_type,
208 'description' => $dao->description,
209 'entity_id' => $entityId,
a7886853 210 'contribution_id' => $dao->contribution_id,
bf45dbe8 211 'financial_type_id' => $dao->financial_type_id,
6a488035 212 'membership_type_id' => $dao->membership_type_id,
9c09f5b7 213 'membership_num_terms' => $dao->membership_num_terms,
6a488035
TO
214 );
215 }
216 return $lineItems;
217 }
218
219 /**
220 * This method will create the lineItem array required for
221 * processAmount method
222 *
223 * @param int $fid price set field id
224 * @param array $params referance to form values
225 * @param array $fields referance to array of fields belonging
226 * to the price set used for particular event
227 * @param array $values referance to the values array(
228 this is
229 * lineItem array)
230 *
231 * @return void
232 * @access static
233 */
234 static function format($fid, &$params, &$fields, &$values) {
235 if (empty($params["price_{$fid}"])) {
236 return;
237 }
238
239 $optionIDs = implode(',', array_keys($params["price_{$fid}"]));
240
241 //lets first check in fun parameter,
242 //since user might modified w/ hooks.
243 $options = array();
244 if (array_key_exists('options', $fields)) {
245 $options = $fields['options'];
246 }
247 else {
9da8dc8c 248 CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
6a488035
TO
249 }
250 $fieldTitle = CRM_Utils_Array::value('label', $fields);
251 if (!$fieldTitle) {
9da8dc8c 252 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
6a488035
TO
253 }
254
255 foreach ($params["price_{$fid}"] as $oid => $qty) {
256 $price = $options[$oid]['amount'];
257
258 // lets clean the price in case it is not yet cleant
259 // CRM-10974
260 $price = CRM_Utils_Rule::cleanMoney($price);
261
262 $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
263
264 $values[$oid] = array(
265 'price_field_id' => $fid,
266 'price_field_value_id' => $oid,
267 'label' => CRM_Utils_Array::value('label', $options[$oid]),
268 'field_title' => $fieldTitle,
269 'description' => CRM_Utils_Array::value('description', $options[$oid]),
270 'qty' => $qty,
271 'unit_price' => $price,
272 'line_total' => $qty * $price,
273 'participant_count' => $qty * $participantsPerField,
274 'max_value' => CRM_Utils_Array::value('max_value', $options[$oid]),
275 'membership_type_id' => CRM_Utils_Array::value('membership_type_id', $options[$oid]),
276 'membership_num_terms' => CRM_Utils_Array::value('membership_num_terms', $options[$oid]),
277 'auto_renew' => CRM_Utils_Array::value('auto_renew', $options[$oid]),
278 'html_type' => $fields['html_type'],
bf45dbe8 279 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $options[$oid]),
6a488035 280 );
cdeb4bdf 281
e03317f1 282 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
421dfaa6 283 $values[$oid]['auto_renew'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
6a488035
TO
284 }
285 }
286 }
287
288 /**
289 * Delete line items for given entity.
290 *
291 * @param int $entityId
292 * @param int $entityTable
293 *
77b97be7 294 * @return bool
6a488035
TO
295 * @access public
296 * @static
297 */
421dfaa6 298 public static function deleteLineItems($entityId, $entityTable) {
6a488035 299 if (!$entityId || !$entityTable) {
9330406e 300 return FALSE;
6a488035
TO
301 }
302
303 if ($entityId && !is_array($entityId)) {
304 $entityId = array($entityId);
305 }
306
de1c25e1 307 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
6a488035 308 $dao = CRM_Core_DAO::executeQuery($query);
9330406e 309 return TRUE;
6a488035
TO
310 }
311
312 /**
313 * Function to process price set and line items.
dd244018
EM
314 *
315 * @param $entityId
6a488035
TO
316 * @param array $lineItem line item array
317 * @param object $contributionDetails
6a488035
TO
318 * @param string $entityTable entity table
319 *
dd244018
EM
320 * @param bool $update
321 *
322 * @internal param int $contributionId contribution id
323 * @internal param \decimal $initAmount amount
6a488035
TO
324 * @access public
325 * @return void
326 * @static
327 */
328 static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
329 if (!$entityId || !is_array($lineItem)
330 || CRM_Utils_system::isNull($lineItem)
331 ) {
332 return;
333 }
421dfaa6 334
6a488035
TO
335 foreach ($lineItem as $priceSetId => $values) {
336 if (!$priceSetId) {
337 continue;
338 }
339
340 foreach ($values as $line) {
341 $line['entity_table'] = $entityTable;
342 $line['entity_id'] = $entityId;
8aa7457a
EM
343 if(!empty($line['membership_type_id'])) {
344 $entityTable == 'civicrm_membership';
345 $line['contribution_id'] = $contributionDetails->id;
346 }
a7886853
E
347 if ($entityTable == 'civicrm_contribution') {
348 $line['contribution_id'] = $entityId;
349 }
350 else {
7d3f62f6
C
351 if (!empty($contributionDetails->id)) {
352 $line['contribution_id'] = $contributionDetails->id;
353 }
a7886853 354 }
6a488035
TO
355 // if financial type is not set and if price field value is NOT NULL
356 // get financial type id of price field value
8cc574cf 357 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
9da8dc8c 358 $line['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
6a488035
TO
359 }
360 $lineItems = CRM_Price_BAO_LineItem::create($line);
361 if (!$update && $contributionDetails) {
362 CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails);
363 }
364 }
365 }
421dfaa6 366 }
6a488035 367
ffd93213
EM
368 /**
369 * @param $entityId
370 * @param string $entityTable
371 * @param $amount
372 * @param null $otherParams
373 */
6a488035
TO
374 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
375 if (!$entityId || CRM_Utils_System::isNull($amount))
376 return;
377
378 $from = " civicrm_line_item li
379 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
380 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
381
421dfaa6 382 $set = " li.unit_price = %3,
6a488035
TO
383 li.line_total = %3 ";
384
421dfaa6 385 $where = " li.entity_id = %1 AND
6a488035
TO
386 li.entity_table = %2 ";
387
388 $params = array(
389 1 => array($entityId, 'Integer'),
390 2 => array($entityTable, 'String'),
391 3 => array($amount, 'Float'),
392 );
393
394 if ($entityTable == 'civicrm_contribution') {
395 $entityName = 'default_contribution_amount';
396 $where .= " AND ps.name = %4 ";
421dfaa6 397 $params[4] = array($entityName, 'String');
398 }
6a488035
TO
399 elseif ($entityTable == 'civicrm_participant') {
400 $from .= "
401 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
402 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
403 $set .= " ,li.label = %4,
404 li.price_field_value_id = cpfv.id ";
405 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
406 $amount = empty($amount) ? 0: $amount;
407 $params += array(
408 4 => array($otherParams['fee_label'], 'String'),
409 5 => array($otherParams['event_id'], 'String'),
410 );
411 }
412
421dfaa6 413 $query = "
6a488035
TO
414 UPDATE $from
415 SET $set
421dfaa6 416 WHERE $where
6a488035
TO
417 ";
418
419 CRM_Core_DAO::executeQuery($query, $params);
420 }
421
422 /**
423 * Function to build line items array.
62c4420e 424 * @param array $params form values
6a488035
TO
425 *
426 * @param string $entityId entity id
427 *
428 * @param string $entityTable entity Table
429 *
430 * @access public
431 * @return void
432 * @static
433 */
434 static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution') {
421dfaa6 435
6a488035 436 if (!$entityId) {
9da8dc8c 437 $priceSetDetails = CRM_Price_BAO_PriceSet::getDefaultPriceSet();
6a488035
TO
438 foreach ($priceSetDetails as $values) {
439 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
440 'price_field_id' => $values['priceFieldID'],
441 'price_field_value_id' => $values['priceFieldValueID'],
442 'label' => $values['label'],
443 'qty' => 1,
444 'unit_price' => $params['total_amount'],
445 'line_total' => $params['total_amount'],
446 'financial_type_id' => $params['financial_type_id']
447 );
448 }
421dfaa6 449 }
6a488035
TO
450 else {
451 $setID = NULL;
464bb009
PN
452 $totalEntityId = count($entityId);
453 foreach ($entityId as $id) {
454 $lineItems = CRM_Price_BAO_LineItem::getLineItems($id, $entityTable);
455 foreach ($lineItems as $key => $values) {
32cb2feb 456 if (!$setID && $values['price_field_id']) {
9da8dc8c 457 $setID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
458 $params['is_quick_config'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
464bb009 459 }
a7488080 460 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
464bb009
PN
461 && $totalEntityId == 1) {
462 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
463 }
464 $values['id'] = $key;
465 $params['line_item'][$setID][$key] = $values;
6a488035 466 }
6a488035
TO
467 }
468 }
469 }
470}