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