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