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