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