Merge pull request #19057 from ixiam/dev/core#2173
[civicrm-core.git] / CRM / Contribute / Form / ManagePremiums.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class generates form components for Premiums.
20 */
21 class CRM_Contribute_Form_ManagePremiums extends CRM_Contribute_Form {
22
23 /**
24 * Classes extending CRM_Core_Form should implement this method.
25 *
26 * @return string
27 */
28 public function getDefaultEntity() {
29 return 'Product';
30 }
31
32 /**
33 * Set default values for the form.
34 */
35 public function setDefaultValues() {
36 $defaults = parent::setDefaultValues();
37 if ($this->_id) {
38 $params = ['id' => $this->_id];
39 CRM_Contribute_BAO_Product::retrieve($params, $tempDefaults);
40 if (isset($tempDefaults['image']) && isset($tempDefaults['thumbnail'])) {
41 $defaults['imageUrl'] = $tempDefaults['image'];
42 $defaults['thumbnailUrl'] = $tempDefaults['thumbnail'];
43 $defaults['imageOption'] = 'thumbnail';
44 // assign thumbnailUrl to template so we can display current image in update mode
45 $this->assign('thumbnailUrl', $defaults['thumbnailUrl']);
46 }
47 else {
48 $defaults['imageOption'] = 'noImage';
49 }
50 if (isset($tempDefaults['thumbnail']) && isset($tempDefaults['image'])) {
51 $this->assign('thumbURL', $tempDefaults['thumbnail']);
52 $this->assign('imageURL', $tempDefaults['image']);
53 }
54 if (isset($tempDefaults['period_type'])) {
55 $this->assign('showSubscriptions', TRUE);
56 }
57 }
58
59 return $defaults;
60 }
61
62 /**
63 * Build the form object.
64 *
65 * @throws \CiviCRM_API3_Exception
66 */
67 public function buildQuickForm() {
68 parent::buildQuickForm();
69 $this->setPageTitle(ts('Premium Product'));
70
71 if ($this->_action & CRM_Core_Action::PREVIEW) {
72 CRM_Contribute_BAO_Premium::buildPremiumPreviewBlock($this, $this->_id);
73 return;
74 }
75
76 if ($this->_action & CRM_Core_Action::DELETE) {
77 return;
78 }
79
80 $this->applyFilter('__ALL__', 'trim');
81 $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'name'), TRUE);
82 $this->addRule('name', ts('A product with this name already exists. Please select another name.'), 'objectExists', [
83 'CRM_Contribute_DAO_Product',
84 $this->_id,
85 ]);
86 $this->add('text', 'sku', ts('SKU'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'sku'));
87
88 $this->add('textarea', 'description', ts('Description'), ['cols' => 60, 'rows' => 3]);
89
90 $image['image'] = $this->createElement('radio', NULL, NULL, ts('Upload from my computer'), 'image', 'onclick="add_upload_file_block(\'image\');');
91 $image['thumbnail'] = $this->createElement('radio', NULL, NULL, ts('Display image and thumbnail from these locations on the web:'), 'thumbnail', 'onclick="add_upload_file_block(\'thumbnail\');');
92 $image['default_image'] = $this->createElement('radio', NULL, NULL, ts('Use default image'), 'default_image', 'onclick="add_upload_file_block(\'default\');');
93 $image['noImage'] = $this->createElement('radio', NULL, NULL, ts('Do not display an image'), 'noImage', 'onclick="add_upload_file_block(\'noImage\');');
94
95 $this->addGroup($image, 'imageOption', ts('Premium Image'));
96 $this->addRule('imageOption', ts('Please select an option for the premium image.'), 'required');
97
98 $this->addElement('text', 'imageUrl', ts('Image URL'));
99 $this->addElement('text', 'thumbnailUrl', ts('Thumbnail URL'));
100
101 $this->add('file', 'uploadFile', ts('Image File Name'), ['onChange' => 'select_option();']);
102
103 $this->add('text', 'price', ts('Market Value'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'price'), TRUE);
104 $this->addRule('price', ts('Please enter the Market Value for this product.'), 'money');
105
106 $this->add('text', 'cost', ts('Actual Cost of Product'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'cost'));
107 $this->addRule('price', ts('Please enter the Actual Cost of Product.'), 'money');
108
109 $this->add('text', 'min_contribution', ts('Minimum Contribution Amount'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'min_contribution'), TRUE);
110 $this->addRule('min_contribution', ts('Please enter a monetary value for the Minimum Contribution Amount.'), 'money');
111
112 $this->add('textarea', 'options', ts('Options'), ['cols' => 60, 'rows' => 3]);
113
114 $this->add('select', 'period_type', ts('Period Type'), [
115 'rolling' => 'Rolling',
116 'fixed' => 'Fixed',
117 ], FALSE, ['placeholder' => TRUE]);
118
119 $this->add('text', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'fixed_period_start_day'));
120
121 $this->addField('duration_unit', ['placeholder' => ts('- select period -')], FALSE);
122 $this->add('text', 'duration_interval', ts('Duration'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'duration_interval'));
123 $this->addField('frequency_unit', ['placeholder' => ts('- select period -')], FALSE);
124 $this->add('text', 'frequency_interval', ts('Frequency'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'frequency_interval'));
125
126 //Financial Type CRM-11106
127 $financialType = CRM_Contribute_PseudoConstant::financialType();
128 $premiumFinancialType = [];
129 CRM_Core_PseudoConstant::populate(
130 $premiumFinancialType,
131 'CRM_Financial_DAO_EntityFinancialAccount',
132 $all = TRUE,
133 $retrieve = 'entity_id',
134 $filter = NULL,
135 'account_relationship = 8'
136 );
137
138 $costFinancialType = [];
139 CRM_Core_PseudoConstant::populate(
140 $costFinancialType,
141 'CRM_Financial_DAO_EntityFinancialAccount',
142 $all = TRUE,
143 $retrieve = 'entity_id',
144 $filter = NULL,
145 'account_relationship = 7'
146 );
147 $productFinancialType = array_intersect($costFinancialType, $premiumFinancialType);
148 foreach ($financialType as $key => $financialTypeName) {
149 if (!in_array($key, $productFinancialType)) {
150 unset($financialType[$key]);
151 }
152 }
153 if (count($financialType)) {
154 $this->assign('financialType', $financialType);
155 }
156 $this->add(
157 'select',
158 'financial_type_id',
159 ts('Financial Type'),
160 $financialType,
161 FALSE,
162 ['placeholder' => TRUE]
163 );
164
165 $this->add('checkbox', 'is_active', ts('Enabled?'));
166
167 $this->addFormRule(['CRM_Contribute_Form_ManagePremiums', 'formRule']);
168
169 $this->addButtons([
170 [
171 'type' => 'upload',
172 'name' => ts('Save'),
173 'isDefault' => TRUE,
174 ],
175 [
176 'type' => 'cancel',
177 'name' => ts('Cancel'),
178 ],
179 ]);
180 $this->assign('productId', $this->_id);
181 }
182
183 /**
184 * Function for validation.
185 *
186 * @param array $params
187 * (ref.) an assoc array of name/value pairs.
188 * @param $files
189 *
190 * @return bool|array
191 * mixed true or array of errors
192 */
193 public static function formRule($params, $files) {
194
195 // If choosing to upload an image, then an image must be provided
196 if (CRM_Utils_Array::value('imageOption', $params) == 'image'
197 && empty($files['uploadFile']['name'])
198 ) {
199 $errors['uploadFile'] = ts('A file must be selected');
200 }
201
202 // If choosing to use image URLs, then both URLs must be present
203 if (CRM_Utils_Array::value('imageOption', $params) == 'thumbnail') {
204 if (!$params['imageUrl']) {
205 $errors['imageUrl'] = ts('Image URL is Required');
206 }
207 if (!$params['thumbnailUrl']) {
208 $errors['thumbnailUrl'] = ts('Thumbnail URL is Required');
209 }
210 }
211
212 // CRM-13231 financial type required if product has cost
213 if (!empty($params['cost']) && empty($params['financial_type_id'])) {
214 $errors['financial_type_id'] = ts('Financial Type is required for product having cost.');
215 }
216
217 if (!$params['period_type']) {
218 if ($params['fixed_period_start_day'] || $params['duration_unit'] || $params['duration_interval'] ||
219 $params['frequency_unit'] || $params['frequency_interval']
220 ) {
221 $errors['period_type'] = ts('Please select the Period Type for this subscription or service.');
222 }
223 }
224
225 if ($params['period_type'] == 'fixed' && !$params['fixed_period_start_day']) {
226 $errors['fixed_period_start_day'] = ts('Please enter a Fixed Period Start Day for this subscription or service.');
227 }
228
229 if ($params['duration_unit'] && !$params['duration_interval']) {
230 $errors['duration_interval'] = ts('Please enter the Duration Interval for this subscription or service.');
231 }
232
233 if ($params['duration_interval'] && !$params['duration_unit']) {
234 $errors['duration_unit'] = ts('Please enter the Duration Unit for this subscription or service.');
235 }
236
237 if ($params['frequency_interval'] && !$params['frequency_unit']) {
238 $errors['frequency_unit'] = ts('Please enter the Frequency Unit for this subscription or service.');
239 }
240
241 if ($params['frequency_unit'] && !$params['frequency_interval']) {
242 $errors['frequency_interval'] = ts('Please enter the Frequency Interval for this subscription or service.');
243 }
244
245 return empty($errors) ? TRUE : $errors;
246 }
247
248 /**
249 * Process the form submission.
250 */
251 public function postProcess() {
252 // If previewing, don't do any post-processing
253 if ($this->_action & CRM_Core_Action::PREVIEW) {
254 return;
255 }
256
257 // If deleting, then only delete and skip the rest of the post-processing
258 if ($this->_action & CRM_Core_Action::DELETE) {
259 try {
260 CRM_Contribute_BAO_Product::del($this->_id);
261 }
262 catch (CRM_Core_Exception $e) {
263 $message = ts("This Premium is linked to an <a href='%1'>Online Contribution page</a>. Please remove it before deleting this Premium.", [1 => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1')]);
264 CRM_Core_Session::setStatus($message, ts('Cannot delete Premium'), 'error');
265 CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/admin/contribute/managePremiums', 'reset=1&action=browse'));
266 return;
267 }
268 CRM_Core_Session::setStatus(
269 ts('Selected Premium Product type has been deleted.'),
270 ts('Deleted'), 'info');
271 return;
272 }
273
274 $params = $this->controller->exportValues($this->_name);
275
276 // Clean the the money fields
277 $moneyFields = ['cost', 'price', 'min_contribution'];
278 foreach ($moneyFields as $field) {
279 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
280 }
281
282 // If we're updating, we need to pass in the premium product Id
283 if ($this->_action & CRM_Core_Action::UPDATE) {
284 $params['id'] = $this->_id;
285 }
286
287 $this->_processImages($params);
288
289 // Save the premium product to database
290 $premium = CRM_Contribute_BAO_Product::create($params);
291
292 CRM_Core_Session::setStatus(
293 ts("The Premium '%1' has been saved.", [1 => $premium->name]),
294 ts('Saved'), 'success');
295 }
296
297 /**
298 * Look at $params to find form info about images. Manipulate images if
299 * necessary. Then alter $params to point to the newly manipulated images.
300 *
301 * @param array $params
302 */
303 protected function _processImages(&$params) {
304 $defaults = [
305 'imageOption' => 'noImage',
306 'uploadFile' => ['name' => ''],
307 'image' => '',
308 'thumbnail' => '',
309 'imageUrl' => '',
310 'thumbnailUrl' => '',
311 ];
312 $params = array_merge($defaults, $params);
313
314 // User is uploading an image
315 if ($params['imageOption'] == 'image') {
316 $imageFile = $params['uploadFile']['name'];
317 try {
318 $params['image'] = CRM_Utils_File::resizeImage($imageFile, 200, 200, "_full");
319 $params['thumbnail'] = CRM_Utils_File::resizeImage($imageFile, 50, 50, "_thumb");
320 }
321 catch (CRM_Core_Exception $e) {
322 $params['image'] = self::_defaultImage();
323 $params['thumbnail'] = self::_defaultThumbnail();
324 $msg = ts('The product has been configured to use a default image.');
325 CRM_Core_Session::setStatus($e->getMessage() . " $msg", ts('Notice'), 'alert');
326 }
327 }
328
329 // User is specifying existing URLs for the images
330 elseif ($params['imageOption'] == 'thumbnail') {
331 $params['image'] = $params['imageUrl'];
332 $params['thumbnail'] = $params['thumbnailUrl'];
333 }
334
335 // User wants a default image
336 elseif ($params['imageOption'] == 'default_image') {
337 $params['image'] = self::_defaultImage();
338 $params['thumbnail'] = self::_defaultThumbnail();
339 }
340 }
341
342 /**
343 * Returns the path to the default premium image
344 * @return string
345 */
346 protected static function _defaultImage() {
347 $config = CRM_Core_Config::singleton();
348 return $config->resourceBase . 'i/contribute/default_premium.jpg';
349 }
350
351 /**
352 * Returns the path to the default premium thumbnail
353 * @return string
354 */
355 protected static function _defaultThumbnail() {
356 $config = CRM_Core_Config::singleton();
357 return $config->resourceBase . 'i/contribute/default_premium_thumb.jpg';
358 }
359
360 }