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