CRM-14106 - Regex targeting other conditionals
[civicrm-core.git] / CRM / Price / BAO / LineItem.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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 */
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 (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);
61
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 static function getLineTotal($entityId, $entityTable) {
96 $sqlLineItemTotal = "SELECT SUM(li.line_total)
97 FROM civicrm_line_item li
98 INNER JOIN civicrm_participant_payment pp ON ( li.entity_id = pp.participant_id
99 AND li.entity_table = '{$entityTable}'
100 AND li.entity_id = {$entityId})";
101 $lineItemTotal = CRM_Core_DAO::singleValueQuery($sqlLineItemTotal);
102 return $lineItemTotal;
103 }
104
105 /**
106 * Given a participant id/contribution id,
107 * return contribution/fee line items
108 *
109 * @param $entityId int participant/contribution id
110 * @param $entity string participant/contribution.
111 *
112 * @return array of line items
113 */
114 static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL) {
115 $selectClause = $whereClause = $fromClause = NULL;
116 $selectClause = "
117 SELECT li.id,
118 li.label,
119 li.qty,
120 li.unit_price,
121 li.line_total,
122 pf.label as field_title,
123 pf.html_type,
124 pfv.membership_type_id,
125 pfv.membership_num_terms,
126 li.price_field_id,
127 li.participant_count,
128 li.price_field_value_id,
129 li.financial_type_id,
130 pfv.description";
131
132 $fromClause = "
133 FROM civicrm_%2 as %2
134 LEFT JOIN civicrm_line_item li ON ( li.entity_id = %2.id AND li.entity_table = 'civicrm_%2')
135 LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )
136 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
137 $whereClause = "
138 WHERE %2.id = %1";
139
140 if ($isQuick) {
141 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
142 $whereClause .= " and cps.is_quick_config = 0";
143 }
144 $lineItems = array();
145
146 if (!$entityId || !$entity || !$fromClause) {
147 return $lineItems;
148 }
149
150 $params = array(
151 1 => array($entityId, 'Integer'),
152 2 => array($entity, 'Text'),
153 );
154
155 $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause", $params);
156 while ($dao->fetch()) {
157 if (!$dao->id) {
158 continue;
159 }
160 $lineItems[$dao->id] = array(
161 'qty' => $dao->qty,
162 'label' => $dao->label,
163 'unit_price' => $dao->unit_price,
164 'line_total' => $dao->line_total,
165 'price_field_id' => $dao->price_field_id,
166 'participant_count' => $dao->participant_count,
167 'price_field_value_id' => $dao->price_field_value_id,
168 'field_title' => $dao->field_title,
169 'html_type' => $dao->html_type,
170 'description' => $dao->description,
171 'entity_id' => $entityId,
172 'financial_type_id' => $dao->financial_type_id,
173 'membership_type_id' => $dao->membership_type_id,
174 'membership_num_terms' => $dao->membership_num_terms,
175 );
176 }
177 return $lineItems;
178 }
179
180 /**
181 * This method will create the lineItem array required for
182 * processAmount method
183 *
184 * @param int $fid price set field id
185 * @param array $params referance to form values
186 * @param array $fields referance to array of fields belonging
187 * to the price set used for particular event
188 * @param array $values referance to the values array(
189 this is
190 * lineItem array)
191 *
192 * @return void
193 * @access static
194 */
195 static function format($fid, &$params, &$fields, &$values) {
196 if (empty($params["price_{$fid}"])) {
197 return;
198 }
199
200 $optionIDs = implode(',', array_keys($params["price_{$fid}"]));
201
202 //lets first check in fun parameter,
203 //since user might modified w/ hooks.
204 $options = array();
205 if (array_key_exists('options', $fields)) {
206 $options = $fields['options'];
207 }
208 else {
209 CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
210 }
211 $fieldTitle = CRM_Utils_Array::value('label', $fields);
212 if (!$fieldTitle) {
213 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
214 }
215
216 foreach ($params["price_{$fid}"] as $oid => $qty) {
217 $price = $options[$oid]['amount'];
218
219 // lets clean the price in case it is not yet cleant
220 // CRM-10974
221 $price = CRM_Utils_Rule::cleanMoney($price);
222
223 $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
224
225 $values[$oid] = array(
226 'price_field_id' => $fid,
227 'price_field_value_id' => $oid,
228 'label' => CRM_Utils_Array::value('label', $options[$oid]),
229 'field_title' => $fieldTitle,
230 'description' => CRM_Utils_Array::value('description', $options[$oid]),
231 'qty' => $qty,
232 'unit_price' => $price,
233 'line_total' => $qty * $price,
234 'participant_count' => $qty * $participantsPerField,
235 'max_value' => CRM_Utils_Array::value('max_value', $options[$oid]),
236 'membership_type_id' => CRM_Utils_Array::value('membership_type_id', $options[$oid]),
237 'membership_num_terms' => CRM_Utils_Array::value('membership_num_terms', $options[$oid]),
238 'auto_renew' => CRM_Utils_Array::value('auto_renew', $options[$oid]),
239 'html_type' => $fields['html_type'],
240 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $options[$oid]),
241 );
242
243 if ($values[$oid]['membership_type_id'] && !isset($values[$oid]['auto_renew'])) {
244 $values[$oid]['auto_renew'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
245 }
246 }
247 }
248
249 /**
250 * Delete line items for given entity.
251 *
252 * @param int $entityId
253 * @param int $entityTable
254 *
255 * @access public
256 * @static
257 */
258 public static function deleteLineItems($entityId, $entityTable) {
259 if (!$entityId || !$entityTable) {
260 return FALSE;
261 }
262
263 if ($entityId && !is_array($entityId)) {
264 $entityId = array($entityId);
265 }
266
267 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
268 $dao = CRM_Core_DAO::executeQuery($query);
269 return TRUE;
270 }
271
272 /**
273 * Function to process price set and line items.
274 * @param int $contributionId contribution id
275 * @param array $lineItem line item array
276 * @param object $contributionDetails
277 * @param decimal $initAmount amount
278 * @param string $entityTable entity table
279 *
280 * @access public
281 * @return void
282 * @static
283 */
284 static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
285 if (!$entityId || !is_array($lineItem)
286 || CRM_Utils_system::isNull($lineItem)
287 ) {
288 return;
289 }
290
291 foreach ($lineItem as $priceSetId => $values) {
292 if (!$priceSetId) {
293 continue;
294 }
295
296 foreach ($values as $line) {
297 $line['entity_table'] = $entityTable;
298 $line['entity_id'] = $entityId;
299 // if financial type is not set and if price field value is NOT NULL
300 // get financial type id of price field value
301 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
302 $line['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
303 }
304 $lineItems = CRM_Price_BAO_LineItem::create($line);
305 if (!$update && $contributionDetails) {
306 CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails);
307 }
308 }
309 }
310 }
311
312 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
313 if (!$entityId || CRM_Utils_System::isNull($amount))
314 return;
315
316 $from = " civicrm_line_item li
317 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
318 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
319
320 $set = " li.unit_price = %3,
321 li.line_total = %3 ";
322
323 $where = " li.entity_id = %1 AND
324 li.entity_table = %2 ";
325
326 $params = array(
327 1 => array($entityId, 'Integer'),
328 2 => array($entityTable, 'String'),
329 3 => array($amount, 'Float'),
330 );
331
332 if ($entityTable == 'civicrm_contribution') {
333 $entityName = 'default_contribution_amount';
334 $where .= " AND ps.name = %4 ";
335 $params[4] = array($entityName, 'String');
336 }
337 elseif ($entityTable == 'civicrm_participant') {
338 $from .= "
339 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
340 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
341 $set .= " ,li.label = %4,
342 li.price_field_value_id = cpfv.id ";
343 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
344 $amount = empty($amount) ? 0: $amount;
345 $params += array(
346 4 => array($otherParams['fee_label'], 'String'),
347 5 => array($otherParams['event_id'], 'String'),
348 );
349 }
350
351 $query = "
352 UPDATE $from
353 SET $set
354 WHERE $where
355 ";
356
357 CRM_Core_DAO::executeQuery($query, $params);
358 }
359
360 /**
361 * Function to build line items array.
362 * @param int $params form values
363 *
364 * @param string $entityId entity id
365 *
366 * @param string $entityTable entity Table
367 *
368 * @access public
369 * @return void
370 * @static
371 */
372 static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution') {
373
374 if (!$entityId) {
375 $priceSetDetails = CRM_Price_BAO_PriceSet::getDefaultPriceSet();
376 foreach ($priceSetDetails as $values) {
377 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
378 'price_field_id' => $values['priceFieldID'],
379 'price_field_value_id' => $values['priceFieldValueID'],
380 'label' => $values['label'],
381 'qty' => 1,
382 'unit_price' => $params['total_amount'],
383 'line_total' => $params['total_amount'],
384 'financial_type_id' => $params['financial_type_id']
385 );
386 }
387 }
388 else {
389 $setID = NULL;
390 $totalEntityId = count($entityId);
391 foreach ($entityId as $id) {
392 $lineItems = CRM_Price_BAO_LineItem::getLineItems($id, $entityTable);
393 foreach ($lineItems as $key => $values) {
394 if (!$setID && $values['price_field_id']) {
395 $setID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
396 $params['is_quick_config'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
397 }
398 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
399 && $totalEntityId == 1) {
400 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
401 }
402 $values['id'] = $key;
403 $params['line_item'][$setID][$key] = $values;
404 }
405 }
406 }
407 }
408 }