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