forked from bockhauzen/rentalshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproduct_availability.php
380 lines (369 loc) · 19.1 KB
/
product_availability.php
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
<?php
// ------------- Adding the date fields for the rental period ------------- \\
# Adds date fields to 'Rentable' products in the store
function add_custom_field(){
global $post;
$pf = new WC_Product_Factory();
$product = $pf->get_product($post->ID);
if ($product->get_type() == 'rentable'){
# Display stock quantity of current product if enabled
if (get_option('plugin-rentman-checkstock') == 1){
$stock = __(' in stock', 'rentalshop');
$nostock = __('Total stock unknown', 'rentalshop');
if ($product->get_stock_quantity() == '')
echo $nostock . '<br><br>';
else if ($product->get_stock_quantity() == 0)
echo '✕ ' . $product->get_stock_quantity() . $stock . '<br><br>';
else
echo '✓ ' . $product->get_stock_quantity() . $stock . '<br><br>';
}
# Checks if there already is a 'Rentable' product in the shopping cart
$rentableProduct = false;
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item){
$product = $cart_item['data'];
if ($product->get_type() == 'rentable'){
$rentableProduct = true;
break;
}
}
echo '<div class="rentman-fields">';
# If there isn't, display the date input fields
if ($rentableProduct == false){
$dates = get_dates();
$fromDate = $dates['from_date'];
$toDate = $dates['to_date'];
$today = date("Y-m-d");
$datepickerlanguage = get_datepicker_translation(get_locale());
# Check if the 'from' date is earlier than the 'to' date
if (strtotime($fromDate) < strtotime($today))
$fromDate = $today;
if (strtotime($toDate) < strtotime($today))
$toDate = $today;
?>
<!-- actual HTML code for the date input fields -->
<?php _e('From:', 'rentalshop');?>
<input type="text" name="start_date" id="start-date" onchange="quickCheck()" value="<?php echo(format_date_picker_date($fromDate)); ?>" data-language='<?php echo($datepickerlanguage); ?>' min="<?php echo(format_date_picker_date($today)); ?>" /><br />
<?php _e('To:', 'rentalshop');?>
<input type="text" name="end_date" id="end-date" onchange="quickCheck()" value="<?php echo(format_date_picker_date($toDate)); ?>" data-language='<?php echo($datepickerlanguage); ?>' />
<p><?php _e('Important: You can change the rent dates for other materials that you want to rent in the cart!', 'rentalshop');?></p>
<?php
}
else{ # Else, display the dates from the products in your shopping cart
$dates = get_dates();
?>
<?php _e('<h3>Selected dates: </h3> <p><b>From </b>', 'rentalshop'); echo(format_date_picker_date($dates['from_date'])); _e('<b> to </b>', 'rentalshop'); echo(format_date_picker_date($dates['to_date'])); ?></p>
<?php
}
# Only show the availability messages when 'check availability for sending' is allowed
if (get_option('plugin-rentman-checkavail') == 1){
echo '<p class="availLog"></p>';
} else{
echo '<p class="availLog" hidden></p>';
}
echo '</div>';
}
}
# Also adds date fields to the checkout and cart menu
function add_date_checkout(){
$pf = new WC_Product_Factory();
$rentableProduct = false;
$today = date("Y-m-d");
# Again check if the shopping cart contains any 'Rentable' products
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item){
$product = $cart_item['data'];
if ($product->get_type() == 'rentable'){
$rentableProduct = true;
break;
}
}
# If it does, add the date fields
if ($rentableProduct){
if (apply_filters('rentman/show_checkout_dates', true)) {
init_datepickers();
?><p>
<?php _e('<h2>Rental Period</h2>', 'rentalshop');
$dates = get_dates();
$startdate = $dates['from_date'];
$enddate = $dates['to_date'];
$sdate =& $startdate;
$edate =& $enddate;
$datepickerlanguage = get_datepicker_translation(get_locale());
?>
<form method="post">
<?php _e('From:', 'rentalshop'); ?>
<input type="text" name="start_date" id="start-date" value="<?php echo(format_date_picker_date($startdate)); ?>" data-language='<?php echo($datepickerlanguage); ?>' min="<?php echo(format_date_picker_date($today)); ?>" />
<?php _e('To:', 'rentalshop'); ?>
<input type="text" name="end_date" id="end-date" value="<?php echo(format_date_picker_date($enddate)); ?>" data-language='<?php echo($datepickerlanguage); ?>' min="<?php echo(format_date_picker_date($today)); ?>" />
<!-- Update Button --></p>
<input type="hidden" name="rm-update-dates">
<input type="button" class="button button-primary" id="changePeriod" value="<?php _e('Update Dates', 'rentalshop');?>">
<input type="hidden" name="backup-start" value="<?php echo $sdate;?>">
<input type="hidden" name="backup-end" value="<?php echo $edate;?>">
</form>
<?php
}
}
}
# Display the selected dates in the checkout menu
function show_selected_dates(){
$pf = new WC_Product_Factory();
$rentableProduct = false;
# Again check if the shopping cart contains any 'Rentable' products
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item){
$product = $cart_item['data'];
if ($product->get_type() == 'rentable'){
$rentableProduct = true;
break;
}
}
# If it does, add the date fields
if ($rentableProduct){
$dates = get_dates();
?>
<?php _e('<h3>Selected dates </h3> <p class="rentman-rental-period"><b>From </b>', 'rentalshop'); echo(format_date_picker_date($dates['from_date'])); _e('<b> to </b>', 'rentalshop'); echo(format_date_picker_date($dates['to_date'])); ?></p>
<?php
}
}
// ------------- Template Changes ------------- \\
# Changes text of the 'add to cart' button
function woo_custom_cart_button_text(){
global $post;
$pf = new WC_Product_Factory();
$product = $pf->get_product($post->ID);
if ($product->get_type() == 'rentable'){
return __('Reserve', 'rentalshop');
}
return __('Add to cart', 'rentalshop');
}
# Adds a template for 'Rentable' products
function add_to_cart_template(){
global $post;
$pf = new WC_Product_Factory();
$product = $pf->get_product($post->ID);
if ($product->get_type() == 'rentable'){
if (apply_filters('rentman/add_to_cart_template', true)) {
do_action('woocommerce_before_add_to_cart_form'); ?>
<form class="cart rentman-extra-margin" method="post" enctype='multipart/form-data'>
<?php do_action('woocommerce_before_add_to_cart_button'); ?>
<?php
if (!$product->is_sold_individually())
woocommerce_quantity_input(array(
'min_value' => apply_filters('woocommerce_quantity_input_min', 1, $product),
'max_value' => apply_filters('woocommerce_quantity_input_max', $product->backorders_allowed() ? '' : $product->get_stock_quantity(), $product)
));
?>
<input type="hidden" name="add-to-cart" value="<?php echo esc_attr($product->get_id()); ?>"/>
<button type="submit" class="single_add_to_cart_button button alt"><?php echo $product->single_add_to_cart_text();?></button>
<?php do_action('woocommerce_after_add_to_cart_button'); ?>
</form>
<?php do_action('woocommerce_after_add_to_cart_form');
}
}
}
// ------------- API Request Functions ------------- \\
# Apply the check_available function on updated products in the cart
function update_amount($passed, $cart_item_key, $values, $quantity){
$product = $values['data'];
return check_available($passed, $product->get_id(), $quantity, 'from_CART');
}
# Apply availability check for each item in the cart for the new dates and update the
# dates in the current session if all products are available
function update_dates(){
$pf = new WC_Product_Factory();
$checkergroup = true;
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item){
$product = $cart_item['data'];
if ($product->get_type() == 'rentable'){
$checkergroup = check_available($checkergroup, $product->get_id(), $cart_item[''], 'checkout');
if ($checkergroup == false)
break;
}
} # Only update the dates when all materials are available in the new time period
if ($checkergroup){
echo 'Materials are available, updating the dates in the current session';
$_SESSION['rentman_rental_session']['from_date'] = $_POST['start_date'];
$_SESSION['rentman_rental_session']['to_date'] = $_POST['end_date'];
} else {
echo 'Materials are not available, so do not update the dates of the current session';
echo 'SESSION from date = ' . $_SESSION['rentman_rental_session']['from_date'];
echo 'SESSION to date = ' . $_SESSION['rentman_rental_session']['to_date'];
}
wp_die();
}
# Set the availability functions
function set_functions(){
# Check if product is already in the cart
global $product;
$quantity = 0;
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item){
$cartproduct = $cart_item['data'];
if ($cartproduct->get_title() == $product->get_title()){
$quantity += $cart_item['quantity'];
break;
}
}
# Adjust the ending date to 00:00 on the following day
$dates = get_dates();
$enddate = $dates['to_date'];
$enddate = date("Y-m-j", strtotime("+1 day", strtotime($enddate)));
# Register and localize the availability script
wp_register_style('style_datepicker', plugins_url('js/datepicker.css', __FILE__ ));
wp_enqueue_style('style_datepicker');
wp_register_script('admin_datepicker', plugins_url('js/admin_datepicker.js', __FILE__ ));
wp_enqueue_script('admin_datepicker');
wp_register_script('admin_datepicker_translation', plugins_url('js/admin_datepicker_translation.js', __FILE__ ));
wp_enqueue_script('admin_datepicker_translation');
wp_register_script('admin_availability', plugins_url('js/admin_available.js', __FILE__ ));
wp_localize_script('admin_availability', 'startDate', $dates['from_date']);
wp_localize_script('admin_availability', 'endDate', $enddate);
wp_localize_script('admin_availability', 'endPoint', receive_endpoint());
wp_localize_script('admin_availability', 'rm_account', get_option('plugin-rentman-account'));
wp_localize_script('admin_availability', 'rm_token', get_option('plugin-rentman-token'));
wp_localize_script('admin_availability', 'cart_amount', (string)$quantity);
wp_localize_script('admin_availability', 'unavailable', __("Product is not available!", "rentalshop"));
wp_localize_script('admin_availability', 'maybe', __("Product might not be available!", "rentalshop"));
wp_localize_script('admin_availability', 'available', __("Product is available!", "rentalshop"));
wp_localize_script('admin_availability', 'ajax_file_path', admin_url('admin-ajax.php'));
wp_enqueue_script('admin_availability');
}
# Attach script to the 'update rental period' button
function init_datepickers(){
# Register and localize the datepickers script
wp_register_style('style_datepicker', plugins_url('js/datepicker.css', __FILE__ ));
wp_enqueue_style('style_datepicker');
wp_register_script('admin_datepicker', plugins_url('js/admin_datepicker.js', __FILE__ ));
wp_enqueue_script('admin_datepicker');
wp_register_script('admin_datepicker_translation', plugins_url('js/admin_datepicker_translation.js', __FILE__ ));
wp_enqueue_script('admin_datepicker_translation');
wp_register_script('admin_datepickers', plugins_url('js/admin_datepickers.js', __FILE__ ));
wp_localize_script('admin_datepickers', 'ajax_file_path', admin_url('admin-ajax.php'));
wp_enqueue_script('admin_datepickers');
}
# Format date for Jquery datepicker
function format_date_picker_date($formatdate) {
return substr($formatdate, -2) . "-" . substr($formatdate, 5, 2) . "-" . substr($formatdate, 0, 4);
}
# Get language code for datepicker
function get_datepicker_translation($languagecode){
$transvalues[] = ["cs", "cs_CZ"];
$transvalues[] = ["da", "da_DK"];
$transvalues[] = ["de", "de_DE"];
$transvalues[] = ["de", "de_CH"];
$transvalues[] = ["en", "en_US"];
$transvalues[] = ["en", "en_AU"];
$transvalues[] = ["en", "en_CA"];
$transvalues[] = ["en", "en_GB"];
$transvalues[] = ["es", "es_AR"];
$transvalues[] = ["es", "es_CL"];
$transvalues[] = ["es", "es_CO"];
$transvalues[] = ["es", "es_MX"];
$transvalues[] = ["es", "es_PE"];
$transvalues[] = ["es", "es_ES"];
$transvalues[] = ["es", "es_PR"];
$transvalues[] = ["es", "es_VE"];
$transvalues[] = ["fi", "fi"];
$transvalues[] = ["fr", "fr_BE"];
$transvalues[] = ["fr", "fr_CA"];
$transvalues[] = ["fr", "fr_FR"];
$transvalues[] = ["hu", "hu_HU"];
$transvalues[] = ["it", "it_IT"];
$transvalues[] = ["nl", "nl_BE"];
$transvalues[] = ["nl", "nl_NL"];
$transvalues[] = ["pl", "pl_PL"];
$transvalues[] = ["pt-BR", "pt_BR"];
$transvalues[] = ["pt", "pt_PT"];
$transvalues[] = ["ro", "ro_RO"];
$transvalues[] = ["sk", "sk_SK"];
$transvalues[] = ["zh", "zh_CN"];
$transvalues[] = ["zh", "zh_HK"];
$transvalues[] = ["zh", "zh_TW"];
$key = array_search($languagecode, array_column($transvalues,1));
if($key==""){
return "en";
}else{
return $transvalues[$key][0];
}
}
# Main function for the availability check and relevant API requests
function check_available($passed, $product_id, $quantity, $variation_id = '', $variations = ''){
# Get the product and chosen dates
$pf = new WC_Product_Factory();
$product = $pf->get_product($product_id);
$startDate = "";
$endDate = "";
if(isset($_POST['start_date'])){
$startDate = $_POST['start_date'];
}
if(isset($_POST['end_date'])){
$endDate = $_POST['end_date'];
}
if ($startDate == '' or $endDate == ''){
$dates = get_dates();
$startDate = $dates['from_date'];
$endDate = $dates['to_date'];
}
# Only apply availability check on products that were
# imported from Rentman (so with the 'rentable' product type)
if ($product->get_type() == 'rentable'){
if (apply_filters('rentman/availability_check', true)) {
if ($variation_id != 'checkout') {
$_SESSION['rentman_rental_session']['from_date'] = $startDate;
$_SESSION['rentman_rental_session']['to_date'] = $endDate;
$dates = get_dates();
$sdate = $dates['from_date'];
$edate = $dates['to_date'];
} else {
$sdate = $startDate;
$edate = $endDate;
}
# Check if any of the input dates are empty or the rental period is invalid
if ($sdate == '' or $edate == '' or (strtotime($edate) < strtotime($sdate))) {
$passed = false;
wc_add_notice(__('Something went wrong.. Did you provide correct dates?', 'rentalshop'), 'error');
} else {
# Continue with the check if 'Check availability for sending' is set to yes
if (get_option('plugin-rentman-checkavail') == 1) {
$url = receive_endpoint();
# Check if the item is already in the cart and adjust
# the input quantity accordingly
if ($variation_id != 'from_CART') {
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
$cartproduct = $cart_item['data'];
if ($cartproduct->get_title() == $product->get_title()) {
$quantity += $cart_item['quantity'];
break;
}
}
}
# Setup Request to send JSON
$message = json_encode(available_request(get_option('plugin-rentman-token'), $product->get_sku(), $quantity, true, $sdate, $edate), JSON_PRETTY_PRINT);
# Send Request & Receive Response
$received = do_request($url, $message);
$parsed = json_decode($received, true);
$parsed = parseResponse($parsed);
# Get values from parsed response
$maxconfirmed = $parsed['response']['value']['maxconfirmed'];
$maxoption = $parsed['response']['value']['maxoption'];
$residual = $quantity + $maxconfirmed; # Total amount of available items
$optional = $maxoption * (-1);
$possible = min($optional, $quantity); # Amount of items that might be available
# The actual Availability Check
# Comparing values of 'maxconfirmed' and 'maxoption'
if ($maxconfirmed < 0) { # Products are definitely not available
$passed = false;
$notice = __('There are only ', 'rentalshop') . $residual . ' ' . $product->get_title() . __(' available in that time period.', 'rentalshop');
wc_add_notice($notice, 'error');
} else if ($maxconfirmed >= 0 and $maxoption < 0) { # Products might be available, depending on confirmation of other orders
$notice = __('Important: ', 'rentalshop') . $possible . __(' out of ', 'rentalshop') . $quantity . ' ' . $product->get_title() . __(' might not be available in that time period..', 'rentalshop');
wc_add_notice($notice, 'error');
} else { # Products are available and are added to the cart
$notice = __('Your selected amount of ', 'rentalshop') . $product->get_title() . __(' is available in that time period!', 'rentalshop');
wc_add_notice($notice, 'success');
}
}
}
}
}
return $passed;
}
?>