forked from avr/webform_commerce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webform_commerce.module
465 lines (389 loc) · 15.2 KB
/
webform_commerce.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<?php
/**
* @file
* Webform component to integrate Webform + Commerce.
*
*/
/**
* Implements hook_commerce_line_item_type_info().
*
* @see hook_commerce_line_item_type_info().
* @see http://www.drupalcommerce.org/specification/info-hooks/checkout
*
*/
function webform_commerce_commerce_line_item_type_info() {
$line_item_types['webform_commerce'] = array(
'name' => t('Webform extra fee'),
'description' => t('Simplest Example Line Item Type'),
'product' => FALSE,
// Here you can change the text in the submit button in the order admin form.
'add_form_submit_value' => t('Add webform extra charge'),
'base' => 'webform_commerce_line_item',
);
return $line_item_types;
}
function webform_commerce_line_item_title($line_item) {
return $line_item->line_item_label;
}
/**
* Implements hook_webform_component_info
*/
function webform_commerce_webform_component_info() {
$components = array();
$components['commerce'] = array(
'label' => t('Commerce product'),
'description' => t('Creates a product during webform submission.'),
'features' => array(
'conditional' => FALSE,
'required' => FALSE,
'title_display' => FALSE,
),
'file' => 'webform_commerce.component.inc',
);
return $components;
}
/**
* Implements hook_webform_component_info_alter().
*
* Taken directly from webform_pay
*
*/
function webform_commerce_webform_component_info_alter(&$components) {
// Allow components of these types to be used as a price field.
$components['textfield']['features']['price'] = TRUE;
$components['select']['features']['price'] = TRUE;
$components['hidden']['features']['price'] = TRUE;
}
/**
* Implements hook_webform_component_presave().
*/
function webform_commerce_webform_component_presave(&$component) {
// Create a new product if necessary
if ($component['type'] == 'commerce') {
// Update the component with the new product_sku
// $component['extra']['pricing']['product_to_add'] = 'special_test';
}
}
/**
* Implements hook_node_load().
*
* Taken directly from webform_pay
*/
function webform_commerce_node_load($nodes, $types) {
// Quick check to see if we need to do anything at all for these nodes.
$webform_types = webform_variable_get('webform_node_types');
if (count(array_intersect($types, $webform_types)) == 0) {
return;
}
// Select all webforms that match these node IDs.
$result = db_select('webform_component', 'wc')
->fields('wc', array('nid', 'cid'))
->condition('type', 'commerce')
->condition('nid', array_keys($nodes), 'IN')
->execute()
->fetchAllKeyed();
foreach ($result as $nid => $cid) {
$nodes[$nid]->webform_commerce_cid = $cid;
}
}
/**
* Implements hook_form_alter().
*
* Inspired by from webform_pay
*/
function webform_commerce_form_alter(&$form, &$form_state, $form_id) {
if (preg_match('/^webform_client_form_\d+$/', $form_id) && isset($form['#node']->webform_commerce_cid)) {
$node = $form['#node'];
$commerce_cid = $node->webform_commerce_cid;
$commerce_comp = $node->webform['components'][$commerce_cid];
if ($product = commerce_product_load_by_sku($commerce_comp['extra']['pricing']['product_to_add'])) {
$amount = commerce_product_calculate_sell_price($product);
$currency_code = $amount['currency_code'];
$form_state['wfc']['base_price'] = $amount;
$form_state['wfc']['product_id'] = $product->product_id;
}
$total = !isset($form_state['wfc']['total']) ? $amount['amount'] : $form_state['wfc']['total'];
// Add a class to add positioning to the form
$form['#attributes']['class'][] = 'commerce-webform';
// Check for submission so this only used on initial webform creation
if (empty($form['#submission']->sid)) {
// Create the "Total:" and Line Item box
$form['cost'] = array(
'#type' => 'container',
);
$form['cost']['title'] = array(
'#type' => 'item',
'#title' => t('Total:'),
'#markup' => "<span id='cost_heading'>" . commerce_currency_format($total, $currency_code ) . "</span>",
);
// add ajax for each price component
foreach ($commerce_comp['extra']['price_components'] as $cid => $enabled) {
if ($enabled && isset($node->webform['components'][$cid])) {
$price_component = $node->webform['components'][$cid];
$parent_keys = webform_component_parent_keys($node, $price_component);
foreach ($parent_keys as $form_key) {
$title = $price_component['name'];
$options = isset($form_state['wfc']['options']) ? $form_state['wfc']['options'] : NULL;
$value = isset($options[$form_key]['amount']) ? $options[$form_key]['amount'] : (int) 0;
$form['cost'][$form_key] = array(
'#type' => 'item',
'#markup' => "<p>" . $title . ": <span id='{$form_key}'>" . commerce_currency_format($value, $currency_code) . "</span></p>",
);
// add ajax to each component that can alter price
$form['submitted'][$form_key]['#attributes']['class'][] = 'ajax-fix';
$form['submitted'][$form_key]['#ajax'] = array(
'callback' => 'webform_commerce_price_adjust',
'progress' => array(
'type' => 'throbber',
'message' => NULL,
),
);
}
}
}
}
$form['#after_build'][] = 'webform_commerce_after_build';
$form['#validate'][] = 'webform_commerce_validate';
$form['#submit'][] = 'webform_commerce_submit';
}
}
/**
* Ajax callback to adjust the price display
*/
function webform_commerce_price_adjust(&$form, $form_state) {
$commands = array();
// Adjust the display of the main "Total"
$total = $form_state['wfc']['total'];
$currency_code = $form_state['wfc']['base_price']['currency_code'];
$amount = commerce_currency_format($total, $currency_code);
$commands[] = ajax_command_html("#cost_heading", $amount);
// Adjust the display value of each line item
$items = $form_state['wfc']['options'];
foreach($items as $k => $v) {
$line_item_amount = commerce_currency_format($v['amount'], 'USD');
$commands[] = ajax_command_html("#". $k, $line_item_amount);
}
return array('#type' => 'ajax', '#commands' => $commands);
}
/**
* After build function for webform_commerce_form_alter.
*
* Inspired by from webform_pay
*/
function webform_commerce_after_build($form) {
// If editing a submission, do NOT reprocess add to cart/validate functions.
if (!empty($form['#submission']->sid)) {
$submit_index = array_search('webform_commerce_submit', $form['#submit']);
$validate_index = array_search('webform_commerce_validate', $form['#validate']);
if ($submit_index !== FALSE) {
unset($form['#submit'][$submit_index]);
}
if ($validate_index !== FALSE) {
unset($form['#validate'][$validate_index]);
}
}
return $form;
}
/**
* Validation function for webforms that accept payment information.
*
* This is responsible for finding all the price fields within the webform and
* adding up all the totals. Currently either textfields or select lists may
* be used for prices.
*
* Inspired by from webform_pay
*/
function webform_commerce_validate(&$form, &$form_state) {
$node = $form['#node'];
$commerce_cid = $node->webform_commerce_cid;
$commerce_component = $node->webform['components'][$commerce_cid];
// Add up all the components that contain price values.
$total = $form_state['wfc']['base_price']['amount'];
foreach ($commerce_component['extra']['price_components'] as $cid => $enabled) {
if ($enabled && isset($node->webform['components'][$cid])) {
$price_component = $node->webform['components'][$cid];
// Find the price value if on the current page.
$price_value = _webform_commerce_component_value($node, $price_component, $form_state['values']['submitted'], TRUE);
// Find the price value from any previous pages.
if ($price_value === FALSE && isset($form_state['storage']['submitted'])) {
$price_value = _webform_commerce_component_value($node, $price_component, $form_state['storage']['submitted']);
}
$form_key = $price_component['form_key'];
$form_state['wfc']['options'][$form_key]['amount'] = (float) $price_value * 100;
$form_state['wfc']['options'][$form_key]['details'] = $price_component;
$price_parents = webform_component_parent_keys($node, $price_component);
if (!empty($price_value) && !is_numeric($price_value)) {
form_set_error('submitted][' . implode('][', $price_parents), t('The value for @name needs to be a valid amount.', array('@name' => $price_component['name'])));
}
else {
$total += (float) $price_value * 100;
}
}
}
$form_state['wfc']['total'] = $total;
// Set the total for the webform.
$form_state['values']['webform_commerce']['total'] = $total;
$form_state['values']['webform_commerce']['status'] = 'unpaid';
// Drill down to the commerce form element.
$parent_keys = webform_component_parent_keys($node, $commerce_component);
$element = &$form['submitted'];
foreach ($parent_keys as $form_key) {
$element = &$element[$form_key];
}
if ($element) {
// Set the component value so that it gets saved into the Webform table.
form_set_value($element, $form_state['values']['webform_commerce'], $form_state);
}
}
/**
* Submit callback to add a product to the cart
* This is taken straight from commerce_cart_add_to_cart_form_submit
*/
function webform_commerce_submit(&$form, &$form_state) {
// Only submit the registration if the webform has been fully submitted
if (!empty($form_state['values']['details']['sid'])) {
global $user;
if (isset($form_state['wfc']['product_id'])) {
// $product_id = $form_state['values']['product_id'];
$product_id = $form_state['wfc']['product_id'];
$quantity = '1';
$combine = FALSE;
}
if ($line_item = commerce_cart_product_add_by_id($product_id, $quantity, $combine, $user->uid)) {
$order = commerce_order_load($line_item->order_id);
// Add webform details to the order. This allows for marking the webform "paid"
// through rules
$order->data['webform'][] = array(
'nid' => $form['#node']->nid,
'sid' => $form_state['values']['details']['sid'],
);
// Wrap the order to simplify manipulating its field data.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
if (isset($form_state['wfc']['options'])) {
foreach ($form_state['wfc']['options'] as $option) {
if ($option['amount'] > 0) {
// Add a reference for each pricing option to the main line item
$line_item->data['webform_price_components'][] = $option;
commerce_line_item_save($line_item);
$unit_price = array(
'amount' => $option['amount'],
'currency_code' => 'USD',
'data' => array(),
);
$new_line_item = webform_commerce_line_item_new($unit_price, $line_item->order_id, NULL, $option['details']);
commerce_line_item_save($new_line_item);
// Add the line item to the order using the wrapper.
$order_wrapper->commerce_line_items[] = $new_line_item;
}
}
}
// Save the order again to update its line item reference field.
commerce_order_save($order);
drupal_set_message(t('Congrats'), 'status');
}
else {
drupal_set_message(t('%title could not be added to your cart.', array('%title' => $product->title)), 'error');
}
}
}
/**
* Creates a new webform_commerce line item populated values.
*
* @param $unit_price
* @param $order_id
* The ID of the order the line item belongs to (if available).
* @param $data
* A data array to set on the new line item.
*
* @return
* The fully loaded line item populated with the product data as specified.
*/
function webform_commerce_line_item_new($unit_price, $order_id = 0, $data = array(), $details = array()) {
$type = 'webform_commerce';
// Create the new line item.
$line_item = entity_create('commerce_line_item', array(
'type' => $type,
'order_id' => $order_id,
'data' => $data,
));
// Populate it with the product information.
webform_commerce_line_item_populate($line_item, $unit_price, $details);
// Return the line item.
return $line_item;
}
/**
* Populates an existing product line item with the product and quantity data.
*
* @param $line_item
* The fully loaded line item object, populated by reference.
* @param $product
* The fully loaded product referenced by the line item.
*/
function webform_commerce_line_item_populate($line_item, $unit_price, $details = array()) {
// Set the label to be the product SKU.
$line_item->line_item_label = $details['name'];
// $line_item->data['webform_component'] = $details;
// Wrap the line item and product to easily set field information.
$line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
$line_item->commerce_unit_price['und'][] = $unit_price;
if (!is_null($line_item_wrapper->commerce_unit_price->value())) {
// Add the base price to the components array.
if (!commerce_price_component_load($line_item_wrapper->commerce_unit_price->value(), 'webform_fee')) {
$line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
$unit_price,
'base_price',
$unit_price,
FALSE,
FALSE
);
}
}
}
/**
* Helper function to return the value of a component if it exists.
*
* @param $node
* The Webform node.
* @param $component
* The Webform component to check for.
* @param $values
* An array of webform values keyed by component ID.
* @param $nested_tree
* Whether or not this function should treat the $values parameter as a tree.
* On same-page validation the form value is in a tree. On multiple page forms
* or on submission, the values are flattened by Webform.
*
* @return
* The submitted value of the component, or FALSE if the component was not
* contained in $values.
*/
function _webform_commerce_component_value($node, $component, $values, $nested_tree = FALSE) {
$component_value = FALSE;
if ($nested_tree) {
$parent_keys = webform_component_parent_keys($node, $component);
$component_value = $values;
foreach ($parent_keys as $form_key) {
if (isset($component_value[$form_key])) {
$component_value = $component_value[$form_key];
}
else {
$component_value = FALSE;
break;
}
}
}
else {
$cid = $component['cid'];
$component_value = isset($values[$cid]) ? $values[$cid] : FALSE;
}
return $component_value;
}
function webform_commerce_status_update($sid, $status = 'unpaid') {
module_load_include('inc', 'webform', 'includes/webform.submissions');
$submissions = webform_get_submissions(array('sid' => $sid));
$updated_submission = $submissions[$sid];
$node = node_load($updated_submission->nid);
// change field to paid status
$updated_submission->data[$node->webform_commerce_cid]['value']['status'] = $status;
webform_submission_update($node, $updated_submission);
}