Merge pull request #19766 from WeMoveEU/faster-select2-groups
[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 $imageJS = [];
90 $image['image'] = ts('Upload from my computer');
91 $imageJS['image'] = ['onclick' => 'add_upload_file_block(\'image\');', 'class' => 'required'];
92 $image['thumbnail'] = ts('Display image and thumbnail from these locations on the web:');
93 $imageJS['thumbnail'] = ['onclick' => 'add_upload_file_block(\'thumbnail\');', 'class' => 'required'];
94 $image['default_image'] = ts('Use default image');
95 $imageJS['default_image'] = ['onclick' => 'add_upload_file_block(\'default\');', 'class' => 'required'];
96 $image['noImage'] = ts('Do not display an image');
97 $imageJS['noImage'] = ['onclick' => 'add_upload_file_block(\'noImage\');', 'class' => 'required'];
98
99 $this->addRadio('imageOption', ts('Premium Image'), $image, [], NULL, FALSE, $imageJS);
100 $this->addRule('imageOption', ts('Please select an option for the premium image.'), 'required');
101
102 $this->addElement('text', 'imageUrl', ts('Image URL'));
103 $this->addElement('text', 'thumbnailUrl', ts('Thumbnail URL'));
104
105 $this->add('file', 'uploadFile', ts('Image File Name'), ['onChange' => 'select_option();']);
106
107 $this->add('text', 'price', ts('Market Value'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'price'), TRUE);
108 $this->addRule('price', ts('Please enter the Market Value for this product.'), 'money');
109
110 $this->add('text', 'cost', ts('Actual Cost of Product'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'cost'));
111 $this->addRule('price', ts('Please enter the Actual Cost of Product.'), 'money');
112
113 $this->add('text', 'min_contribution', ts('Minimum Contribution Amount'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'min_contribution'), TRUE);
114 $this->addRule('min_contribution', ts('Please enter a monetary value for the Minimum Contribution Amount.'), 'money');
115
116 $this->add('textarea', 'options', ts('Options'), ['cols' => 60, 'rows' => 3]);
117
118 $this->add('select', 'period_type', ts('Period Type'), [
119 'rolling' => 'Rolling',
120 'fixed' => 'Fixed',
121 ], FALSE, ['placeholder' => TRUE]);
122
123 $this->add('text', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'fixed_period_start_day'));
124
125 $this->addField('duration_unit', ['placeholder' => ts('- select period -')], FALSE);
126 $this->add('text', 'duration_interval', ts('Duration'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'duration_interval'));
127 $this->addField('frequency_unit', ['placeholder' => ts('- select period -')], FALSE);
128 $this->add('text', 'frequency_interval', ts('Frequency'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'frequency_interval'));
129
130 //Financial Type CRM-11106
131 $financialType = CRM_Contribute_PseudoConstant::financialType();
132 $premiumFinancialType = [];
133 CRM_Core_PseudoConstant::populate(
134 $premiumFinancialType,
135 'CRM_Financial_DAO_EntityFinancialAccount',
136 $all = TRUE,
137 $retrieve = 'entity_id',
138 $filter = NULL,
139 'account_relationship = 8'
140 );
141
142 $costFinancialType = [];
143 CRM_Core_PseudoConstant::populate(
144 $costFinancialType,
145 'CRM_Financial_DAO_EntityFinancialAccount',
146 $all = TRUE,
147 $retrieve = 'entity_id',
148 $filter = NULL,
149 'account_relationship = 7'
150 );
151 $productFinancialType = array_intersect($costFinancialType, $premiumFinancialType);
152 foreach ($financialType as $key => $financialTypeName) {
153 if (!in_array($key, $productFinancialType)) {
154 unset($financialType[$key]);
155 }
156 }
157 if (count($financialType)) {
158 $this->assign('financialType', $financialType);
159 }
160 $this->add(
161 'select',
162 'financial_type_id',
163 ts('Financial Type'),
164 $financialType,
165 FALSE,
166 ['placeholder' => TRUE]
167 );
168
169 $this->add('checkbox', 'is_active', ts('Enabled?'));
170
171 $this->addFormRule(['CRM_Contribute_Form_ManagePremiums', 'formRule']);
172
173 $this->addButtons([
174 [
175 'type' => 'upload',
176 'name' => ts('Save'),
177 'isDefault' => TRUE,
178 ],
179 [
180 'type' => 'cancel',
181 'name' => ts('Cancel'),
182 ],
183 ]);
184 $this->assign('productId', $this->_id);
185 }
186
187 /**
188 * Function for validation.
189 *
190 * @param array $params
191 * (ref.) an assoc array of name/value pairs.
192 * @param $files
193 *
194 * @return bool|array
195 * mixed true or array of errors
196 */
197 public static function formRule($params, $files) {
198
199 // If choosing to upload an image, then an image must be provided
200 if (CRM_Utils_Array::value('imageOption', $params) == 'image'
201 && empty($files['uploadFile']['name'])
202 ) {
203 $errors['uploadFile'] = ts('A file must be selected');
204 }
205
206 // If choosing to use image URLs, then both URLs must be present
207 if (CRM_Utils_Array::value('imageOption', $params) == 'thumbnail') {
208 if (!$params['imageUrl']) {
209 $errors['imageUrl'] = ts('Image URL is Required');
210 }
211 if (!$params['thumbnailUrl']) {
212 $errors['thumbnailUrl'] = ts('Thumbnail URL is Required');
213 }
214 }
215
216 // CRM-13231 financial type required if product has cost
217 if (!empty($params['cost']) && empty($params['financial_type_id'])) {
218 $errors['financial_type_id'] = ts('Financial Type is required for product having cost.');
219 }
220
221 if (!$params['period_type']) {
222 if ($params['fixed_period_start_day'] || $params['duration_unit'] || $params['duration_interval'] ||
223 $params['frequency_unit'] || $params['frequency_interval']
224 ) {
225 $errors['period_type'] = ts('Please select the Period Type for this subscription or service.');
226 }
227 }
228
229 if ($params['period_type'] == 'fixed' && !$params['fixed_period_start_day']) {
230 $errors['fixed_period_start_day'] = ts('Please enter a Fixed Period Start Day for this subscription or service.');
231 }
232
233 if ($params['duration_unit'] && !$params['duration_interval']) {
234 $errors['duration_interval'] = ts('Please enter the Duration Interval for this subscription or service.');
235 }
236
237 if ($params['duration_interval'] && !$params['duration_unit']) {
238 $errors['duration_unit'] = ts('Please enter the Duration Unit for this subscription or service.');
239 }
240
241 if ($params['frequency_interval'] && !$params['frequency_unit']) {
242 $errors['frequency_unit'] = ts('Please enter the Frequency Unit for this subscription or service.');
243 }
244
245 if ($params['frequency_unit'] && !$params['frequency_interval']) {
246 $errors['frequency_interval'] = ts('Please enter the Frequency Interval for this subscription or service.');
247 }
248
249 return empty($errors) ? TRUE : $errors;
250 }
251
252 /**
253 * Process the form submission.
254 */
255 public function postProcess() {
256 // If previewing, don't do any post-processing
257 if ($this->_action & CRM_Core_Action::PREVIEW) {
258 return;
259 }
260
261 // If deleting, then only delete and skip the rest of the post-processing
262 if ($this->_action & CRM_Core_Action::DELETE) {
263 try {
264 CRM_Contribute_BAO_Product::del($this->_id);
265 }
266 catch (CRM_Core_Exception $e) {
267 $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')]);
268 CRM_Core_Session::setStatus($message, ts('Cannot delete Premium'), 'error');
269 CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/admin/contribute/managePremiums', 'reset=1&action=browse'));
270 return;
271 }
272 CRM_Core_Session::setStatus(
273 ts('Selected Premium Product type has been deleted.'),
274 ts('Deleted'), 'info');
275 return;
276 }
277
278 $params = $this->controller->exportValues($this->_name);
279
280 // Clean the the money fields
281 $moneyFields = ['cost', 'price', 'min_contribution'];
282 foreach ($moneyFields as $field) {
283 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
284 }
285
286 // If we're updating, we need to pass in the premium product Id
287 if ($this->_action & CRM_Core_Action::UPDATE) {
288 $params['id'] = $this->_id;
289 }
290
291 $this->_processImages($params);
292
293 // Save the premium product to database
294 $premium = CRM_Contribute_BAO_Product::create($params);
295
296 CRM_Core_Session::setStatus(
297 ts("The Premium '%1' has been saved.", [1 => $premium->name]),
298 ts('Saved'), 'success');
299 }
300
301 /**
302 * Look at $params to find form info about images. Manipulate images if
303 * necessary. Then alter $params to point to the newly manipulated images.
304 *
305 * @param array $params
306 */
307 protected function _processImages(&$params) {
308 $defaults = [
309 'imageOption' => 'noImage',
310 'uploadFile' => ['name' => ''],
311 'image' => '',
312 'thumbnail' => '',
313 'imageUrl' => '',
314 'thumbnailUrl' => '',
315 ];
316 $params = array_merge($defaults, $params);
317
318 // User is uploading an image
319 if ($params['imageOption'] == 'image') {
320 $imageFile = $params['uploadFile']['name'];
321 try {
322 $params['image'] = CRM_Utils_File::resizeImage($imageFile, 200, 200, "_full");
323 $params['thumbnail'] = CRM_Utils_File::resizeImage($imageFile, 50, 50, "_thumb");
324 }
325 catch (CRM_Core_Exception $e) {
326 $params['image'] = self::_defaultImage();
327 $params['thumbnail'] = self::_defaultThumbnail();
328 $msg = ts('The product has been configured to use a default image.');
329 CRM_Core_Session::setStatus($e->getMessage() . " $msg", ts('Notice'), 'alert');
330 }
331 }
332
333 // User is specifying existing URLs for the images
334 elseif ($params['imageOption'] == 'thumbnail') {
335 $params['image'] = $params['imageUrl'];
336 $params['thumbnail'] = $params['thumbnailUrl'];
337 }
338
339 // User wants a default image
340 elseif ($params['imageOption'] == 'default_image') {
341 $params['image'] = self::_defaultImage();
342 $params['thumbnail'] = self::_defaultThumbnail();
343 }
344 }
345
346 /**
347 * Returns the path to the default premium image
348 * @return string
349 */
350 protected static function _defaultImage() {
351 $config = CRM_Core_Config::singleton();
352 return $config->resourceBase . 'i/contribute/default_premium.jpg';
353 }
354
355 /**
356 * Returns the path to the default premium thumbnail
357 * @return string
358 */
359 protected static function _defaultThumbnail() {
360 $config = CRM_Core_Config::singleton();
361 return $config->resourceBase . 'i/contribute/default_premium_thumb.jpg';
362 }
363
364 }