Merge pull request #10602 from agileware/CIVICRM-167
[civicrm-core.git] / CRM / Price / BAO / PriceFieldValue.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
32 */
33
34 /**
35 * Business objects for managing price fields values.
36 *
37 */
38 class CRM_Price_BAO_PriceFieldValue extends CRM_Price_DAO_PriceFieldValue {
39
40 /**
41 * Insert/update a new entry in the database.
42 *
43 * @param array $params
44 *
45 * @param array $ids
46 * Deprecated variable.
47 *
48 * @return CRM_Price_DAO_PriceFieldValue
49 */
50 public static function add(&$params, $ids = array()) {
51
52 $fieldValueBAO = new CRM_Price_BAO_PriceFieldValue();
53 $fieldValueBAO->copyValues($params);
54
55 if ($id = CRM_Utils_Array::value('id', $ids)) {
56 $fieldValueBAO->id = $id;
57 $prevLabel = self::getOptionLabel($id);
58 if (!empty($params['label']) && $prevLabel != $params['label']) {
59 self::updateAmountAndFeeLevel($id, $prevLabel, $params['label']);
60 }
61 }
62 // CRM-16189
63 $priceFieldID = CRM_Utils_Array::value('price_field_id', $params);
64 if (!$priceFieldID) {
65 $priceFieldID = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceFieldValue', $id, 'price_field_id');
66 }
67 if (!empty($params['is_default'])) {
68 $query = 'UPDATE civicrm_price_field_value SET is_default = 0 WHERE price_field_id = %1';
69 $p = array(1 => array($params['price_field_id'], 'Integer'));
70 CRM_Core_DAO::executeQuery($query, $p);
71 }
72
73 $fieldValueBAO->save();
74 // Reset the cached values in this function.
75 CRM_Price_BAO_PriceField::getOptions(CRM_Utils_Array::value('price_field_id', $params), FALSE, TRUE);
76 return $fieldValueBAO;
77 }
78
79 /**
80 * Creates a new entry in the database.
81 *
82 * @param array $params
83 * (reference), array $ids.
84 *
85 * @param $ids
86 *
87 * @return CRM_Price_DAO_PriceFieldValue
88 */
89 public static function create(&$params, $ids = array()) {
90 $id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('id', $ids));
91 if (!is_array($params) || empty($params)) {
92 return NULL;
93 }
94 if (!$id && empty($params['name'])) {
95 $params['name'] = strtolower(CRM_Utils_String::munge($params['label'], '_', 242));
96 }
97
98 if ($id && !empty($params['weight'])) {
99 if (isset($params['name'])) {
100 unset($params['name']);
101 }
102
103 $oldWeight = NULL;
104 if ($id) {
105 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $id, 'weight', 'id');
106 }
107 $fieldValues = array('price_field_id' => CRM_Utils_Array::value('price_field_id', $params, 0));
108 $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Price_DAO_PriceFieldValue', $oldWeight, $params['weight'], $fieldValues);
109 }
110 else {
111 if (!$id) {
112 CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
113 if (empty($params['name'])) {
114 $params['name'] = CRM_Utils_String::munge(CRM_Utils_Array::value('label', $params), '_', 64);
115 }
116 }
117 }
118
119 $financialType = CRM_Utils_Array::value('financial_type_id', $params, NULL);
120 if (!$financialType && $id) {
121 $financialType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $id, 'financial_type_id', 'id');
122 }
123 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
124 if (!empty($financialType) && !array_key_exists($financialType, $financialTypes) && $params['is_active']) {
125 throw new CRM_Core_Exception("Financial Type for Price Field Option is either disabled or does not exist");
126 }
127 return self::add($params, $ids);
128 }
129
130 /**
131 * Get defaults for new entity.
132 * @return array
133 */
134 public static function getDefaults() {
135 return array(
136 'is_active' => 1,
137 'weight' => 1,
138 );
139
140 }
141
142 /**
143 * Retrieve DB object based on input parameters.
144 *
145 * It also stores all the retrieved values in the default array.
146 *
147 * @param array $params
148 * (reference ) an assoc array.
149 * @param array $defaults
150 * (reference ) an assoc array to hold the flattened values.
151 *
152 * @return CRM_Price_DAO_PriceFieldValue
153 */
154 public static function retrieve(&$params, &$defaults) {
155 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceFieldValue', $params, $defaults);
156 }
157
158 /**
159 * Retrieve all values for given field id.
160 *
161 * @param int $fieldId
162 * Price_field_id.
163 * @param array $values
164 * (reference ) to hold the values.
165 * @param string $orderBy
166 * For order by, default weight.
167 * @param bool|int $isActive is_active, default false
168 * @param bool $admin is this loading it for use on an admin page.
169 *
170 * @return array
171 *
172 */
173 public static function getValues($fieldId, &$values, $orderBy = 'weight', $isActive = FALSE, $admin = FALSE) {
174 $sql = "SELECT cs.id FROM civicrm_price_set cs INNER JOIN civicrm_price_field cp ON cp.price_set_id = cs.id
175 WHERE cs.name IN ('default_contribution_amount', 'default_membership_type_amount') AND cp.id = {$fieldId} ";
176 $setId = CRM_Core_DAO::singleValueQuery($sql);
177 $fieldValueDAO = new CRM_Price_DAO_PriceFieldValue();
178 $fieldValueDAO->price_field_id = $fieldId;
179 $addWhere = '';
180 if (!$setId) {
181 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
182 if (!$admin) {
183 $addWhere = "financial_type_id IN (0)";
184 }
185 if (!empty($financialTypes) && !$admin) {
186 $addWhere = "financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
187 }
188 if (!empty($addWhere)) {
189 $fieldValueDAO->whereAdd($addWhere);
190 }
191 }
192 $fieldValueDAO->orderBy($orderBy, 'label');
193 if ($isActive) {
194 $fieldValueDAO->is_active = 1;
195 }
196 $fieldValueDAO->find();
197 while ($fieldValueDAO->fetch()) {
198 CRM_Core_DAO::storeValues($fieldValueDAO, $values[$fieldValueDAO->id]);
199 }
200
201 return $values;
202 }
203
204 /**
205 * Get the price field option label.
206 *
207 * @param int $id
208 * Id of field option.
209 *
210 * @return string
211 * name
212 *
213 */
214 public static function getOptionLabel($id) {
215 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $id, 'label');
216 }
217
218 /**
219 * Update the is_active flag in the db.
220 *
221 * @param int $id
222 * Id of the database record.
223 * @param bool $is_active
224 * Value we want to set the is_active field.
225 *
226 * @return Object
227 * DAO object on success, null otherwise
228 *
229 */
230 public static function setIsActive($id, $is_active) {
231 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceFieldValue', $id, 'is_active', $is_active);
232 }
233
234 /**
235 * Delete all values of the given field id.
236 *
237 * @param int $fieldId
238 * Price field id.
239 *
240 *
241 */
242 public static function deleteValues($fieldId) {
243 if (!$fieldId) {
244 return;
245 }
246
247 $fieldValueDAO = new CRM_Price_DAO_PriceFieldValue();
248 $fieldValueDAO->price_field_id = $fieldId;
249 $fieldValueDAO->delete();
250 }
251
252 /**
253 * Delete the value.
254 *
255 * @param int $id
256 * Id.
257 *
258 * @return bool
259 *
260 */
261 public static function del($id) {
262 if (!$id) {
263 return FALSE;
264 }
265
266 $fieldValueDAO = new CRM_Price_DAO_PriceFieldValue();
267 $fieldValueDAO->id = $id;
268 return $fieldValueDAO->delete();
269 }
270
271 /**
272 * Update civicrm_price_field_value.financial_type_id
273 * when financial_type_id of contribution_page or event is changed
274 *
275 * @param int $entityId
276 * Id.
277 * @param string $entityTable table.
278 * Entity table.
279 * @param string $financialTypeID type id.
280 * Financial type id.
281 *
282 */
283 public static function updateFinancialType($entityId, $entityTable, $financialTypeID) {
284 if (!$entityId || !$entityTable || !$financialTypeID) {
285 return;
286 }
287 $params = array(
288 1 => array($entityId, 'Integer'),
289 2 => array($entityTable, 'String'),
290 3 => array($financialTypeID, 'Integer'),
291 );
292 // for event discount
293 $join = $where = '';
294 if ($entityTable == 'civicrm_event') {
295 $join = " LEFT JOIN civicrm_discount cd ON cd.price_set_id = cps.id AND cd.entity_id = %1 AND cd.entity_table = %2 ";
296 $where = ' OR cd.id IS NOT NULL ';
297 }
298 $sql = "UPDATE civicrm_price_set cps
299 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = cps.id AND cpse.entity_id = %1 AND cpse.entity_table = %2
300 LEFT JOIN civicrm_price_field cpf ON cpf.price_set_id = cps.id
301 LEFT JOIN civicrm_price_field_value cpfv ON cpf.id = cpfv.price_field_id
302 {$join}
303 SET cpfv.financial_type_id = CASE
304 WHEN cpfv.membership_type_id IS NOT NULL
305 THEN cpfv.financial_type_id
306 ELSE %3
307 END,
308 cps.financial_type_id = %3
309 WHERE cpse.id IS NOT NULL {$where}";
310
311 CRM_Core_DAO::executeQuery($sql, $params);
312 }
313
314 /**
315 * Update price option label in line_item, civicrm_contribution and civicrm_participant.
316 *
317 * @param int $id - id of the price_field_value
318 * @param string $prevLabel
319 * @param string $newLabel
320 *
321 */
322 public static function updateAmountAndFeeLevel($id, $prevLabel, $newLabel) {
323 // update price field label in line item.
324 $lineItem = new CRM_Price_DAO_LineItem();
325 $lineItem->price_field_value_id = $id;
326 $lineItem->label = $prevLabel;
327 $lineItem->find();
328 while ($lineItem->fetch()) {
329 $lineItemParams['id'] = $lineItem->id;
330 $lineItemParams['label'] = $newLabel;
331 CRM_Price_BAO_LineItem::create($lineItemParams);
332
333 // update amount and fee level in civicrm_contribution and civicrm_participant
334 $params = array(
335 1 => array(CRM_Core_DAO::VALUE_SEPARATOR . $prevLabel . ' -', 'String'),
336 2 => array(CRM_Core_DAO::VALUE_SEPARATOR . $newLabel . ' -', 'String'),
337 );
338 // Update contribution
339 if (!empty($lineItem->contribution_id)) {
340 CRM_Core_DAO::executeQuery("UPDATE `civicrm_contribution` SET `amount_level` = REPLACE(amount_level, %1, %2) WHERE id = {$lineItem->contribution_id}", $params);
341 }
342 // Update participant
343 if ($lineItem->entity_table == 'civicrm_participant') {
344 CRM_Core_DAO::executeQuery("UPDATE `civicrm_participant` SET `fee_level` = REPLACE(fee_level, %1, %2) WHERE id = {$lineItem->entity_id}", $params);
345 }
346 }
347 }
348
349 }