How to use product method in Puppeteer

Best JavaScript code snippet using puppeteer

admin_order.js

Source:admin_order.js Github

copy

Full Screen

1/*2* 2007-2014 PrestaShop3*4* NOTICE OF LICENSE5*6* This source file is subject to the Academic Free License (AFL 3.0)7* that is bundled with this package in the file LICENSE.txt.8* It is also available through the world-wide-web at this URL:9* http://opensource.org/licenses/afl-3.0.php10* If you did not receive a copy of the license and are unable to11* obtain it through the world-wide-web, please send an email12* to license@prestashop.com so we can send you a copy immediately.13*14* DISCLAIMER15*16* Do not edit or add to this file if you wish to upgrade PrestaShop to newer17* versions in the future. If you wish to customize PrestaShop for your18* needs please refer to http://www.prestashop.com for more information.19*20* @author PrestaShop SA <contact@prestashop.com>21* @copyright 2007-2014 PrestaShop SA22* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)23* International Registered Trademark & Property of PrestaShop SA24*/25var current_product = null;26var ajaxQueries = new Array();27$(document).ready(function() {28 // Init all events29 init();30 $('img.js-disabled-action').css({"opacity":0.5});31});32function stopAjaxQuery() {33 if (typeof(ajaxQueries) == 'undefined')34 ajaxQueries = new Array();35 for(i = 0; i < ajaxQueries.length; i++)36 ajaxQueries[i].abort();37 ajaxQueries = new Array();38}39function updateInvoice(invoices)40{41 // Update select on product edition line42 $('.edit_product_invoice').each(function() {43 var selected = $(this).children('option:selected').val();44 $(this).children('option').remove();45 for(i in invoices)46 {47 // Create new option48 var option = $('<option>'+invoices[i].name+'</option>').attr('value', invoices[i].id);49 if (invoices[i].id == selected)50 option.attr('selected', true);51 $(this).append(option);52 }53 });54 // Update select on product addition line55 $('#add_product_product_invoice').each(function() {56 var parent = $(this).children('optgroup.existing');57 parent.children('option').remove();58 for(i in invoices)59 {60 // Create new option61 var option = $('<option>'+invoices[i].name+'</option>').attr('value', invoices[i].id);62 parent.append(option);63 }64 parent.children('option:first').attr('selected', true);65 });66 // Update select on product addition line67 $('#payment_invoice').each(function() {68 $(this).children('option').remove();69 for(i in invoices)70 {71 // Create new option72 var option = $('<option>'+invoices[i].name+'</option>').attr('value', invoices[i].id);73 $(this).append(option);74 }75 });76}77function updateDocuments(documents_html)78{79 $('#documents_table').attr('id', 'documents_table_old');80 $('#documents_table_old').after(documents_html);81 $('#documents_table_old').remove();82}83function updateShipping(shipping_html)84{85 $('#shipping_table').attr('id', 'shipping_table_old');86 $('#shipping_table_old').after(shipping_html);87 $('#shipping_table_old').remove();88}89function updateDiscountForm(discount_form_html)90{91 $('#voucher_form').html(discount_form_html);92}93function populateWarehouseList(warehouse_list)94{95 $('#add_product_product_warehouse_area').hide();96 if (warehouse_list.length > 1)97 {98 $('#add_product_product_warehouse_area').show();99 }100 var order_warehouse_list = $('#warehouse_list').val().split(',');101 $('#add_product_warehouse').html('');102 var warehouse_selected = false;103 $.each(warehouse_list, function() {104 if (warehouse_selected == false && $.inArray(this.id_warehouse, order_warehouse_list))105 warehouse_selected = this.id_warehouse;106 $('#add_product_warehouse').append($('<option value="' + this.id_warehouse + '">' + this.name + '</option>'));107 });108 if (warehouse_selected)109 $('#add_product_warehouse').val(warehouse_selected);110}111function addProductRefreshTotal()112{113 var quantity = parseInt($('#add_product_product_quantity').val());114 if (quantity < 1|| isNaN(quantity))115 quantity = 1;116 if (use_taxes)117 var price = parseFloat($('#add_product_product_price_tax_incl').val());118 else119 var price = parseFloat($('#add_product_product_price_tax_excl').val());120 if (price < 0 || isNaN(price))121 price = 0;122 var total = makeTotalProductCaculation(quantity, price);123 $('#add_product_product_total').html(formatCurrency(total, currency_format, currency_sign, currency_blank));124}125function editProductRefreshTotal(element)126{127 element = element.parent().parent().parent();128 var element_list = [];129 130 // Customized product131 if(element.hasClass('customized'))132 {133 var element_list = $('.customized-' + element.find('.edit_product_id_order_detail').val());134 element = $(element_list[0]);135 }136 var quantity = parseInt(element.find('td .edit_product_quantity').val());137 if (quantity < 1 || isNaN(quantity))138 quantity = 1;139 if (use_taxes)140 var price = parseFloat(element.find('td .edit_product_price_tax_incl').val());141 else142 var price = parseFloat(element.find('td .edit_product_price_tax_excl').val())143 if (price < 0 || isNaN(price))144 price = 0;145 146 // Customized product147 if (element_list.length)148 {149 var qty = 0;150 $.each(element_list, function(i, elm) {151 if($(elm).find('.edit_product_quantity').length)152 {153 qty += parseInt($(elm).find('.edit_product_quantity').val());154 subtotal = makeTotalProductCaculation($(elm).find('.edit_product_quantity').val(), price);155 $(elm).find('.total_product').html(formatCurrency(subtotal, currency_format, currency_sign, currency_blank));156 }157 });158 159 var total = makeTotalProductCaculation(qty, price);160 element.find('td.total_product').html(formatCurrency(total, currency_format, currency_sign, currency_blank));161 element.find('td.productQuantity').html(qty);162 }163 else164 {165 var total = makeTotalProductCaculation(quantity, price);166 element.find('td.total_product').html(formatCurrency(total, currency_format, currency_sign, currency_blank));167 }168}169function makeTotalProductCaculation(quantity, price)170{171 return Math.round(quantity * price * 100) / 100;172}173function addViewOrderDetailRow(view)174{175 html = $(view);176 html.find('td').hide();177 $('tr#new_invoice').hide();178 $('tr#new_product').hide();179 // Initialize fields180 closeAddProduct();181 $('tr#new_product').before(html);182 html.find('td').each(function() {183 if (!$(this).is('.product_invoice'))184 $(this).fadeIn('slow');185 });186}187function refreshProductLineView(element, view)188{189 var new_product_line = $(view);190 new_product_line.find('td').hide();191 192 var element_list = [];193 if (element.parent().parent().find('.edit_product_id_order_detail').length)194 var element_list = $('.customized-' + element.parent().parent().find('.edit_product_id_order_detail').val());195 if (!element_list.length)196 element_list = $(element.parent().parent());197 var current_product_line = element.parent().parent();198 current_product_line.replaceWith(new_product_line);199 element_list.remove();200 new_product_line.find('td').each(function() {201 if (!$(this).is('.product_invoice'))202 $(this).fadeIn('slow');203 });204}205function updateAmounts(order)206{207 $('#total_products td.amount').fadeOut('slow', function() {208 $(this).html(formatCurrency(parseFloat(order.total_products_wt), currency_format, currency_sign, currency_blank));209 $(this).fadeIn('slow');210 });211 $('#total_discounts td.amount').fadeOut('slow', function() {212 $(this).html(formatCurrency(parseFloat(order.total_discounts_tax_incl), currency_format, currency_sign, currency_blank));213 $(this).fadeIn('slow');214 });215 if (order.total_discounts_tax_incl > 0)216 $('#total_discounts').slideDown('slow');217 $('#total_wrapping td.amount').fadeOut('slow', function() {218 $(this).html(formatCurrency(parseFloat(order.total_wrapping_tax_incl), currency_format, currency_sign, currency_blank));219 $(this).fadeIn('slow');220 });221 if (order.total_wrapping_tax_incl > 0)222 $('#total_wrapping').slideDown('slow');223 $('#total_shipping td.amount').fadeOut('slow', function() {224 $(this).html(formatCurrency(parseFloat(order.total_shipping_tax_incl), currency_format, currency_sign, currency_blank));225 $(this).fadeIn('slow');226 });227 $('#total_order td.amount').fadeOut('slow', function() {228 $(this).html(formatCurrency(parseFloat(order.total_paid_tax_incl), currency_format, currency_sign, currency_blank));229 $(this).fadeIn('slow');230 });231 $('.total_paid').fadeOut('slow', function() {232 $(this).html(formatCurrency(parseFloat(order.total_paid_tax_incl), currency_format, currency_sign, currency_blank));233 $(this).fadeIn('slow');234 });235 $('.alert').slideDown('slow');236 $('#product_number').fadeOut('slow', function() {237 var old_quantity = parseInt($(this).html());238 $(this).html(old_quantity + 1);239 $(this).fadeIn('slow');240 });241 $('#shipping_table .weight').fadeOut('slow', function() {242 $(this).html(order.weight);243 $(this).fadeIn('slow');244 });245}246function closeAddProduct()247{248 $('tr#new_invoice').hide();249 $('tr#new_product').hide();250 // Initialize fields251 $('tr#new_product select, tr#new_product input').each(function() {252 if (!$(this).is('.button'))253 $(this).val('')254 });255 $('tr#new_invoice select, tr#new_invoice input').val('');256 $('#add_product_product_quantity').val('1');257 $('#add_product_product_attribute_id option').remove();258 $('#add_product_product_attribute_area').hide();259 if (stock_management)260 $('#add_product_product_stock').html('0');261 current_product = null;262}263/**264 * This method allow to initialize all events265 */266function init()267{268 $('#txt_msg').on('keyup', function(){269 var length = $('#txt_msg').val().length;270 if (length > 600) length = '600+';271 $('#nbchars').html(length+'/600');272 });273 $('#newMessage').unbind('click').click(function(e) {274 $(this).hide();275 $('#message').show();276 e.preventDefault();277 });278 $('#cancelMessage').unbind('click').click(function(e) {279 $('#newMessage').show();280 $('#message').hide();281 e.preventDefault();282 });283 284 $('#add_product').unbind('click').click(function(e) {285 $('.cancel_product_change_link:visible').trigger('click');286 $('.add_product_fields').show();287 $('.edit_product_fields, .standard_refund_fields, .partial_refund_fields, .order_action').hide();288 $('tr#new_product').slideDown('fast', function () {289 $('tr#new_product td').fadeIn('fast', function() {290 $('#add_product_product_name').focus();291 scroll_if_anchor('#new_product');292 });293 });294 e.preventDefault();295 });296 $('#cancelAddProduct').unbind('click').click(function() {297 $('.order_action').show();298 $('tr#new_product td').fadeOut('fast');299 });300 $("#add_product_product_name").autocomplete(admin_order_tab_link,301 {302 minChars: 3,303 max: 10,304 width: 500,305 selectFirst: false,306 scroll: false,307 dataType: "json",308 highlightItem: true,309 formatItem: function(data, i, max, value, term) {310 return value;311 },312 parse: function(data) {313 var products = new Array();314 if (typeof(data.products) != 'undefined')315 for (var i = 0; i < data.products.length; i++)316 products[i] = { data: data.products[i], value: data.products[i].name };317 return products;318 },319 extraParams: {320 ajax: true,321 token: token,322 action: 'searchProducts',323 id_lang: id_lang,324 id_currency: id_currency,325 id_address: id_address,326 id_customer: id_customer,327 product_search: function() { return $('#add_product_product_name').val(); }328 }329 }330 )331 .result(function(event, data, formatted) {332 if (!data)333 {334 $('tr#new_product input, tr#new_product select').each(function() {335 if ($(this).attr('id') != 'add_product_product_name')336 $('tr#new_product input, tr#new_product select, tr#new_product button').attr('disabled', true);337 });338 }339 else340 {341 $('tr#new_product input, tr#new_product select, tr#new_product button').removeAttr('disabled');342 // Keep product variable343 current_product = data;344 $('#add_product_product_id').val(data.id_product);345 $('#add_product_product_name').val(data.name);346 $('#add_product_product_price_tax_incl').val(data.price_tax_incl);347 $('#add_product_product_price_tax_excl').val(data.price_tax_excl);348 addProductRefreshTotal();349 if (stock_management)350 $('#add_product_product_stock').html(data.stock[0]);351 if (current_product.combinations.length !== 0)352 {353 // Reset combinations list354 $('select#add_product_product_attribute_id').html('');355 var defaultAttribute = 0;356 $.each(current_product.combinations, function() {357 $('select#add_product_product_attribute_id').append('<option value="'+this.id_product_attribute+'"'+(this.default_on == 1 ? ' selected="selected"' : '')+'>'+this.attributes+'</option>');358 if (this.default_on == 1)359 {360 if (stock_management)361 $('#add_product_product_stock').html(this.qty_in_stock);362 defaultAttribute = this.id_product_attribute;363 }364 });365 // Show select list366 $('#add_product_product_attribute_area').show();367 populateWarehouseList(current_product.warehouse_list[defaultAttribute]);368 }369 else370 {371 // Reset combinations list372 $('select#add_product_product_attribute_id').html('');373 // Hide select list374 $('#add_product_product_attribute_area').hide();375 populateWarehouseList(current_product.warehouse_list[0]);376 }377 }378 });379 $('select#add_product_product_attribute_id').unbind('change');380 $('select#add_product_product_attribute_id').change(function() {381 $('#add_product_product_price_tax_incl').val(current_product.combinations[$(this).val()].price_tax_incl);382 $('#add_product_product_price_tax_excl').val(current_product.combinations[$(this).val()].price_tax_excl);383 populateWarehouseList(current_product.warehouse_list[$(this).val()]);384 addProductRefreshTotal();385 if (stock_management)386 $('#add_product_product_stock').html(current_product.combinations[$(this).val()].qty_in_stock);387 });388 $('input#add_product_product_quantity').unbind('keyup').keyup(function() {389 if (stock_management)390 {391 var quantity = parseInt($(this).val());392 if (quantity < 1 || isNaN(quantity))393 quantity = 1;394 var stock_available = parseInt($('#add_product_product_stock').html());395 // stock status update396 if (quantity > stock_available)397 $('#add_product_product_stock').css('font-weight', 'bold').css('color', 'red').css('font-size', '1.2em');398 else399 $('#add_product_product_stock').css('font-weight', 'normal').css('color', 'black').css('font-size', '1em');400 }401 // total update402 addProductRefreshTotal();403 });404 $('#submitAddProduct').unbind('click').click(function(e) {405 e.preventDefault();406 stopAjaxQuery();407 var go = true;408 if ($('input#add_product_product_id').val() == 0)409 {410 jAlert(txt_add_product_no_product);411 go = false;412 }413 if ($('input#add_product_product_quantity').val() == 0)414 {415 jAlert(txt_add_product_no_product_quantity);416 go = false;417 }418 if ($('input#add_product_product_price_excl').val() == 0)419 {420 jAlert(txt_add_product_no_product_price);421 go = false;422 }423 if (go)424 {425 if (parseInt($('input#add_product_product_quantity').val()) > parseInt($('#add_product_product_stock').html()))426 go = confirm(txt_add_product_stock_issue);427 if (go && $('select#add_product_product_invoice').val() == 0)428 go = confirm(txt_add_product_new_invoice);429 if (go)430 {431 var query = 'ajax=1&token='+token+'&action=addProductOnOrder&id_order='+id_order+'&';432 query += $('#add_product_warehouse').serialize()+'&';433 query += $('tr#new_product select, tr#new_product input').serialize();434 if ($('select#add_product_product_invoice').val() == 0)435 query += '&'+$('tr#new_invoice select, tr#new_invoice input').serialize();436 var ajax_query = $.ajax({437 type: 'POST',438 url: admin_order_tab_link,439 cache: false,440 dataType: 'json',441 data : query,442 success : function(data) {443 if (data.result)444 {445 go = false;446 addViewOrderDetailRow(data.view);447 updateAmounts(data.order);448 updateInvoice(data.invoices);449 updateDocuments(data.documents_html);450 updateShipping(data.shipping_html);451 updateDiscountForm(data.discount_form_html);452 // Initialize all events453 init();454 $('.standard_refund_fields').hide();455 $('.partial_refund_fields').hide();456 $('.order_action').show();457 }458 else459 jAlert(data.error);460 },461 error : function(XMLHttpRequest, textStatus, errorThrown) {462 jAlert("Impossible to add the product to the cart.\n\ntextStatus: '" + textStatus + "'\nerrorThrown: '" + errorThrown + "'\nresponseText:\n" + XMLHttpRequest.responseText);463 }464 });465 ajaxQueries.push(ajax_query);466 }467 }468 });469 $('.edit_shipping_number_link').unbind('click').click(function(e) {470 $(this).parent().find('.shipping_number_show').hide();471 $(this).parent().find('.shipping_number_edit').show();472 $(this).parent().find('.edit_shipping_number_link').hide();473 $(this).parent().find('.cancel_shipping_number_link').show();474 e.preventDefault();475 });476 $('.cancel_shipping_number_link').unbind('click').click(function(e) {477 $(this).parent().find('.shipping_number_show').show();478 $(this).parent().find('.shipping_number_edit').hide();479 $(this).parent().find('.edit_shipping_number_link').show();480 $(this).parent().find('.cancel_shipping_number_link').hide();481 e.preventDefault();482 });483 $('#add_product_product_invoice').unbind('change').change(function() {484 if ($(this).val() == '0')485 $('#new_invoice').slideDown('slow');486 else487 $('#new_invoice').slideUp('slow');488 });489 $('#add_product_product_price_tax_excl').unbind('keyup').keyup(function() {490 var price_tax_excl = parseFloat($(this).val());491 if (price_tax_excl < 0 || isNaN(price_tax_excl))492 price_tax_excl = 0;493 var tax_rate = current_product.tax_rate / 100 + 1;494 $('#add_product_product_price_tax_incl').val(ps_round(price_tax_excl * tax_rate, 2));495 // Update total product496 addProductRefreshTotal();497 });498 $('#add_product_product_price_tax_incl').unbind('keyup').keyup(function() {499 var price_tax_incl = parseFloat($(this).val());500 if (price_tax_incl < 0 || isNaN(price_tax_incl))501 price_tax_incl = 0;502 var tax_rate = current_product.tax_rate / 100 + 1;503 $('#add_product_product_price_tax_excl').val(ps_round(price_tax_incl / tax_rate, 2));504 // Update total product505 addProductRefreshTotal();506 });507 $('.edit_product_change_link').unbind('click').click(function(e) {508 $('.add_product_fields, .standard_refund_fields, .order_action').hide();509 $('.edit_product_fields').show();510 $('.cancel_product_change_link:visible').trigger('click');511 closeAddProduct();512 var element = $(this);513 $.ajax({514 type: 'POST',515 url: admin_order_tab_link,516 cache: false,517 dataType: 'json',518 data : {519 ajax: 1,520 token: token,521 action: 'loadProductInformation',522 id_order_detail: element.closest('tr.product-line-row').find('input.edit_product_id_order_detail').val(),523 id_address: id_address,524 id_order: id_order525 },526 success : function(data)527 {528 if (data.result)529 {530 current_product = data;531 532 var element_list = $('.customized-' + element.parent().parent().find('.edit_product_id_order_detail').val());533 if (!element_list.length)534 element_list = element.parent().parent().parent();535 element_list.find('td .product_price_show').hide();536 element_list.find('td .product_quantity_show').hide();537 element_list.find('td .product_price_edit').show();538 element_list.find('td .product_quantity_edit').show();539 element_list.find('td.cancelCheck').hide();540 element_list.find('td.cancelQuantity').hide();541 element_list.find('td.product_invoice').show();542 $('td.product_action').attr('colspan', 3);543 $('th.edit_product_fields').show();544 $('th.edit_product_fields').attr('colspan', 2);545 element_list.find('td.product_action').attr('colspan', 1);546 element.parent().children('.edit_product_change_link').parent().hide();547 element.parent().parent().find('button.submitProductChange').show();548 element.parent().parent().find('.cancel_product_change_link').show();549 $('.standard_refund_fields').hide();550 $('.partial_refund_fields').hide();551 }552 else553 jAlert(data.error);554 }555 });556 e.preventDefault();557 });558 $('.cancel_product_change_link').unbind('click').click(function(e)559 {560 current_product = null;561 $('.edit_product_fields').hide();562 var element_list = $('.customized-' + $(this).parent().parent().find('.edit_product_id_order_detail').val());563 if (!element_list.length)564 element_list = $($(this).parent().parent());565 element_list.find('td .product_price_show').show();566 element_list.find('td .product_quantity_show').show();567 element_list.find('td .product_price_edit').hide();568 element_list.find('td .product_quantity_edit').hide();569 element_list.find('td.product_invoice').hide();570 element_list.find('td.cancelCheck').show();571 element_list.find('td.cancelQuantity').show();572 element_list.find('.edit_product_change_link').parent().show();573 element_list.find('button.submitProductChange').hide();574 element_list.find('.cancel_product_change_link').hide();575 $('.order_action').show();576 $('.standard_refund_fields').hide();577 e.preventDefault();578 });579 $('button.submitProductChange').unbind('click').click(function(e) {580 e.preventDefault();581 if ($(this).closest('tr.product-line-row').find('td .edit_product_quantity').val() <= 0)582 {583 jAlert(txt_add_product_no_product_quantity);584 return false;585 }586 if ($(this).closest('tr.product-line-row').find('td .edit_product_price').val() <= 0)587 {588 jAlert(txt_add_product_no_product_price);589 return false;590 }591 if (confirm(txt_confirm))592 {593 var element = $(this);594 var element_list = $('.customized-' + $(this).parent().parent().find('.edit_product_id_order_detail').val());595 query = 'ajax=1&token='+token+'&action=editProductOnOrder&id_order='+id_order+'&';596 if (element_list.length)597 query += element_list.parent().parent().find('input:visible, select:visible, .edit_product_id_order_detail').serialize();598 else599 query += element.parent().parent().find('input:visible, select:visible, .edit_product_id_order_detail').serialize();600 $.ajax({601 type: 'POST',602 url: admin_order_tab_link,603 cache: false,604 dataType: 'json',605 data : query,606 success : function(data)607 {608 if (data.result)609 {610 refreshProductLineView(element, data.view);611 updateAmounts(data.order);612 updateInvoice(data.invoices);613 updateDocuments(data.documents_html);614 updateDiscountForm(data.discount_form_html);615 // Initialize all events616 init();617 $('.standard_refund_fields').hide();618 $('.partial_refund_fields').hide();619 $('.add_product_fields').hide();620 $('.add_product_fields').hide();621 $('td.product_action').attr('colspan', 3);622 }623 else624 jAlert(data.error);625 }626 });627 }628 return false;629 });630 $('.edit_product_price_tax_excl').unbind('keyup').keyup(function() {631 var price_tax_excl = parseFloat($(this).val());632 if (price_tax_excl < 0 || isNaN(price_tax_excl))633 price_tax_excl = 0;634 var tax_rate = current_product.tax_rate / 100 + 1;635 $('.edit_product_price_tax_incl:visible').val(ps_round(price_tax_excl * tax_rate, 2));636 // Update total product637 editProductRefreshTotal($(this));638 });639 $('.edit_product_price_tax_incl').unbind('keyup');640 $('.edit_product_price_tax_incl').keyup(function() {641 var price_tax_incl = parseFloat($(this).val());642 if (price_tax_incl < 0 || isNaN(price_tax_incl))643 price_tax_incl = 0;644 var tax_rate = current_product.tax_rate / 100 + 1;645 $('.edit_product_price_tax_excl:visible').val(ps_round(price_tax_incl / tax_rate, 2));646 // Update total product647 editProductRefreshTotal($(this));648 });649 $('.edit_product_quantity').unbind('keyup');650 $('.edit_product_quantity').keyup(function() {651 var quantity = parseInt($(this).val());652 if (quantity < 1 || isNaN(quantity))653 quantity = 1;654 var stock_available = parseInt($(this).parent().parent().parent().find('td.product_stock').html());655 // total update656 editProductRefreshTotal($(this));657 });658 $('.delete_product_line').unbind('click').click(function(e) {659 if (!confirm(txt_confirm))660 return false;661 var tr_product = $(this).closest('.product-line-row');662 var id_order_detail = $(this).closest('.product-line-row').find('td .edit_product_id_order_detail').val();663 var query = 'ajax=1&action=deleteProductLine&token='+token+'&id_order_detail='+id_order_detail+'&id_order='+id_order;664 $.ajax({665 type: 'POST',666 url: admin_order_tab_link,667 cache: false,668 dataType: 'json',669 data : query,670 success : function(data)671 {672 if (data.result)673 {674 tr_product.fadeOut('slow', function() {675 $(this).remove();676 });677 updateAmounts(data.order);678 updateInvoice(data.invoices);679 updateDocuments(data.documents_html);680 updateDiscountForm(data.discount_form_html);681 }682 else683 jAlert(data.error);684 }685 });686 e.preventDefault();687 });688 $('.js-set-payment').unbind('click').click(function(e) {689 var amount = $(this).attr('data-amount');690 $('input[name=payment_amount]').val(amount);691 var id_invoice = $(this).attr('data-id-invoice');692 $('select[name=payment_invoice] option[value='+id_invoice+']').attr('selected', true);693 e.preventDefault();694 });695 $('#add_voucher').unbind('click').click(function(e) {696 $('.order_action').hide();697 $('.panel-vouchers,#voucher_form').show();698 e.preventDefault();699 });700 $('#cancel_add_voucher').unbind('click').click(function(e) {701 $('#voucher_form').hide();702 if (!has_voucher)703 $('.panel-vouchers').hide();704 $('.order_action').show();705 e.preventDefault();706 });707 $('#discount_type').unbind('change').change(function() {708 // Percent type709 if ($(this).val() == 1)710 {711 $('#discount_value_field').show();712 $('#discount_currency_sign').hide();713 $('#discount_value_help').hide();714 $('#discount_percent_symbol').show();715 }716 // Amount type717 else if ($(this).val() == 2)718 {719 $('#discount_value_field').show();720 $('#discount_percent_symbol').hide();721 $('#discount_value_help').show();722 $('#discount_currency_sign').show();723 }724 // Free shipping725 else if ($(this).val() == 3)726 {727 $('#discount_value_field').hide();728 }729 });730 $('#discount_all_invoices').unbind('change').change(function() {731 if ($(this).is(':checked'))732 $('select[name=discount_invoice]').attr('disabled', true);733 else734 $('select[name=discount_invoice]').attr('disabled', false);735 });736 $('.open_payment_information').unbind('click').click(function(e) {737 if ($(this).parent().parent().next('tr').is(':visible'))738 $(this).parent().parent().next('tr').hide();739 else740 $(this).parent().parent().next('tr').show();741 e.preventDefault();742 });743}744/* Refund system script */745var flagRefund = '';746$(document).ready(function() {747 $('#desc-order-standard_refund').click(function() {748 $('.cancel_product_change_link:visible').trigger('click');749 closeAddProduct();750 if (flagRefund == 'standard') {751 flagRefund = '';752 $('.partial_refund_fields').hide();753 $('.standard_refund_fields').hide();754 }755 else {756 flagRefund = 'standard';757 $('.partial_refund_fields').hide();758 $('.standard_refund_fields').fadeIn();759 }760 });761 $('#desc-order-partial_refund').click(function() {762 $('.cancel_product_change_link:visible').trigger('click');763 closeAddProduct();764 if (flagRefund == 'partial') {765 flagRefund = '';766 $('.partial_refund_fields').hide();767 $('.standard_refund_fields').hide();768 }769 else {770 flagRefund = 'partial';771 $('.standard_refund_fields, .product_action, .order_action').hide();772 $('.product_action').hide();773 $('.partial_refund_fields').fadeIn();774 }775 });776});777function checkPartialRefundProductQuantity(it)778{779 if (parseInt($(it).val()) > parseInt($(it).closest('td').find('.partialRefundProductQuantity').val()))780 $(it).val($(it).closest('td').find('.partialRefundProductQuantity').val());781}782function checkPartialRefundProductAmount(it)783{784 if (parseInt($(it).val()) > parseInt($(it).closest('td').find('.partialRefundProductAmount').val()))785 $(it).val($(it).closest('td').find('.partialRefundProductAmount').val());...

Full Screen

Full Screen

oneticket.js

Source:oneticket.js Github

copy

Full Screen

1/**2 * Created by qzz on 2016/7/13.3 */4"use strict";5(function () {6 //加载动画7 $("#status").fadeOut();8 $("#preloader").delay(400).fadeOut("medium");9 function init() {10 //特卖模块11 var greatSaleData = [12 {13 "ProductName": "圣淘沙鱼尾狮塔电子票",14 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/2609/Merlion%20Tower%204.jpg",15 "ProductIndex": "1",16 "ProductStartDate": "",17 "ProductEndDate": "",18 "IsEnabled": "1",19 "ProductCode": "",20 "ProductDesc": "见证了新加坡发展的中心地标",21 "ProductSite": "新加坡",22 "ProductPrice": "1",23 "ProductID": "512129",24 "ProductAttentionNum": "",25 "ProductType": "T",26 "oneticket": 'true'27 },28 {29 "ProductName": "新加坡双程缆车电子票",30 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/28054/3-compressed.jpg",31 "ProductIndex": "2",32 "ProductStartDate": "2015/7/14",33 "ProductEndDate": "2017/3/31",34 "IsEnabled": "1",35 "ProductCode": "PK00519LGK09",36 "ProductDesc": "穿梭于圣淘沙和新加坡花柏山顶两个繁华目的地",37 "ProductSite": "新加坡",38 "ProductPrice": "84",39 "ProductID": "507063",40 //"ProductID": "1064",41 "ProductAttentionNum": "",42 "ProductType": "T"43 },44 {45 "ProductName": "滨海湾花园电子票",46 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/2433/7-compressed.jpg",47 "ProductIndex": "3",48 "ProductStartDate": "2013/1/23",49 "ProductEndDate": "2016/9/30",50 "IsEnabled": "1",51 "ProductCode": "PK0382360SIN17",52 "ProductDesc": "城市中心的绿洲",53 "ProductSite": "新加坡",54 "ProductPrice": "85",55 "ProductID": "382792",56 "ProductAttentionNum": "",57 "ProductType": "T",58 },59 {60 "ProductName": "新加坡河川生态园电子票",61 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/31774/Giant%20River%20Otter.jpg",62 "ProductIndex": "4",63 "ProductStartDate": "2015/11/18",64 "ProductEndDate": "2016/12/31",65 "IsEnabled": "1",66 "ProductCode": "PK0505975SIN17",67 "ProductDesc": "参观亚洲首个亦是唯一一个以河川为主题的野生动物园",68 "ProductSite": "新加坡",69 "ProductPrice": "98",70 "ProductID": "509289",71 "ProductAttentionNum": "",72 "ProductType": "T",73 },74 {75 "ProductName": "时光之翼1940场电子票",76 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/1353/rh-SINGAPORE-ENTERTAINMENT-160714e_converted.jpg",77 "ProductIndex": "5",78 "ProductStartDate": "2014/6/19",79 "ProductEndDate": "2017/3/31",80 "IsEnabled": "1",81 "ProductCode": "PK04205SIN17",82 "ProductDesc": "关于勇气的故事",83 "ProductSite": "新加坡",84 "ProductPrice": "60",85 "ProductID": "4416",86 "ProductAttentionNum": "",87 "ProductType": "T",88 },89 {90 "ProductName": "新加坡动物园和电车电子票",91 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/31676/Zoo_RhinoFeeding_379_Main_04-compressed.jpg",92 "ProductIndex": "6",93 "ProductStartDate": "2015/11/11",94 "ProductEndDate": "2016/12/31",95 "IsEnabled": "1",96 "ProductCode": "PK0505901SIN17",97 "ProductDesc": "新加坡旅游局的最佳休闲景点体验奖的九冠王新加坡日间动物园含小火车",98 "ProductSite": "新加坡",99 "ProductPrice": "135",100 "ProductID": "509215",101 "ProductAttentionNum": "",102 "ProductType": "T",103 },104 {105 "ProductName": "杜莎夫人和万象LIVE",106 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/22589/MD112.jpg",107 "ProductIndex": "7",108 "ProductStartDate": "2014/10/25",109 "ProductEndDate": "2017/3/31",110 "IsEnabled": "1",111 "ProductCode": "PK0500367SIN17",112 "ProductDesc": "全球最受欢迎的蜡像馆与非凡名人体验馆",113 "ProductSite": "新加坡",114 "ProductPrice": "94",115 "ProductID": "503673",116 "ProductAttentionNum": "",117 "ProductType": "T",118 },119 {120 "ProductName": "高空观景台1-Altitude",121 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/23779/3.jpg",122 "ProductIndex": "8",123 "ProductStartDate": "2015/2/23",124 "ProductEndDate": "2016/12/31",125 "IsEnabled": "1",126 "ProductCode": "PK0501428SIN17",127 "ProductDesc": "娱乐的豪华场所,无与伦比的美景",128 "ProductSite": "新加坡",129 "ProductPrice": "80",130 "ProductID": "504739",131 "ProductAttentionNum": "",132 "ProductType": "T",133 }134 ];135 //亲子模块136 var childAllData = [137 {138 "ProductName": "新加坡环球影城电子票",139 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/200/USS.jpg",140 "ProductIndex": "1",141 "ProductStartDate": "2014/1/14",142 "ProductEndDate": "2016/6/30",143 "IsEnabled": "1",144 "ProductCode": "PK0489210SIN17",145 "ProductDesc": "嗨翻新加坡影城,进入惊心动魄的电影魔幻世界,身临其境的娱乐体验,让人身心愉悦",146 "ProductSite": "新加坡",147 "ProductPrice": "289",148 "ProductID": "492416",149 "ProductAttentionNum": "",150 "ProductType": "T",151 },152 {153 "ProductName": "S.E.A.水族馆™电子票",154 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/2542/S.E.A%20Aquarium%201.jpg",155 "ProductIndex": "2",156 "ProductStartDate": "2013/3/11",157 "ProductEndDate": "2016/7/31",158 "IsEnabled": "1",159 "ProductCode": "PK0449906SIN17",160 "ProductDesc": "沉醉于世界最大海洋馆,寓教于乐",161 "ProductSite": "新加坡",162 "ProductPrice": "92",163 "ProductID": "453034",164 "ProductAttentionNum": "",165 "ProductType": "T",166 },167 {168 "ProductName": "裕廊飞禽公园和电车电子票",169 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/31672/JBP_Birdz_036_Main_03.jpg",170 "ProductIndex": "3",171 "ProductStartDate": "2015/1/11",172 "ProductEndDate": "2016/12/31",173 "IsEnabled": "1",174 "ProductCode": "PK0505895SIN17",175 "ProductDesc": "与动物亲密接触",176 "ProductSite": "新加坡",177 "ProductPrice": "86",178 "ProductID": "509209",179 "ProductAttentionNum": "",180 "ProductType": "T",181 },182 {183 "ProductName": "河川生态园和夜间野生动物园半日游",184 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/2690/River%20Safari%205.jpg",185 "ProductIndex": "4",186 "ProductStartDate": "2013/4/11",187 "ProductEndDate": "2017/3/31",188 "IsEnabled": "1",189 "ProductCode": "PK0479507SIN17",190 "ProductDesc": "参观亚洲首个亦是唯一一个以河川为主题的野生动物园及世界夜间野生动物园",191 "ProductSite": "新加坡",192 "ProductPrice": "344",193 "ProductID": "482686",194 "ProductAttentionNum": "",195 "ProductType": "T",196 },197 {198 "ProductName": "圣淘沙名胜世界逸濠酒店 (Resorts World Sentosa - Equarius Hotel)",199 "ProductPicUrl": "http://images.asiatravel.com/Hotel/10472/front-image3.jpg",200 "ProductIndex": "1",201 "ProductStartDate": "",202 "ProductEndDate": "",203 "IsEnabled": "1",204 "ProductCode": "",205 "ProductDesc": "住海底套房与鱼共眠,拥有超大海洋馆观景窗的海景套房",206 "ProductSite": "圣淘沙",207 "ProductPrice": "1379",208 "ProductID": "10472",209 "ProductAttentionNum": "",210 "ProductType": "H",211 },212 {213 "ProductName": "圣淘沙名胜世界节庆酒店(Resorts World Sentosa - Festive Hotel) ",214 "ProductPicUrl": "http://images.asiatravel.com/Hotel/7765/attraction10.jpg?_ga=1.44722727.200375633.1463101167",215 "ProductIndex": "2",216 "ProductStartDate": "",217 "ProductEndDate": "",218 "IsEnabled": "1",219 "ProductCode": "",220 "ProductDesc": "集吃喝玩乐及住宿于一身, 配套设施一应俱全",221 "ProductSite": "圣淘沙",222 "ProductPrice": "909",223 "ProductID": "7765",224 "ProductAttentionNum": "",225 "ProductType": "H",226 },227 {228 "ProductName": "迈克尔酒店Resorts World Sentosa - Hotel Michael",229 "ProductPicUrl": "http://images.asiatravel.com/Hotel/7764/Deluxe.jpg",230 "ProductIndex": "3",231 "ProductStartDate": "",232 "ProductEndDate": "",233 "IsEnabled": "1",234 "ProductCode": "",235 "ProductDesc": "时尚创新设计,客房暖色调的温馨设计,舒适的入住体验",236 "ProductSite": "圣淘沙",237 "ProductPrice": "1208",238 "ProductID": "7764",239 "ProductAttentionNum": "",240 "ProductType": "H",241 },242 {243 "ProductName": "圣淘沙喜乐度假酒店Siloso Beach Resort, Sentosa",244 "ProductPicUrl": "http://images.asiatravel.com/Hotel/80/Exterior.jpg",245 "ProductIndex": "4",246 "ProductStartDate": "",247 "ProductEndDate": "",248 "IsEnabled": "1",249 "ProductCode": "",250 "ProductDesc": "尽情享受大自然的美丽风光,享受度假的悠闲时光",251 "ProductSite": "圣淘沙",252 "ProductPrice": "783",253 "ProductID": "80",254 "ProductAttentionNum": "",255 "ProductType": "H",256 }257 ];258 //闺蜜模块259 var bestieData = [260 {261 "ProductName": "Ducktour之游(电子船票)",262 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/2208/Singapore%20Ducktours%204.jpg",263 "ProductIndex": "1",264 "ProductStartDate": "2012/11/27",265 "ProductEndDate": "2016/9/30",266 "IsEnabled": "1",267 "ProductCode": "PK24831SIN17",268 "ProductDesc": "乘坐二战使用的越南战争军用机模型,开始水陆探险",269 "ProductSite": "新加坡",270 "ProductPrice": "155",271 "ProductID": "24850",272 "ProductAttentionNum": "",273 "ProductType": "T",274 },275 {276 "ProductName": "斜坡滑车与空中吊椅的电子票",277 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/2327/Luge%20with%20Skyride%202.jpg",278 "ProductIndex": "2",279 "ProductStartDate": "2012/12/27",280 "ProductEndDate": "2017/3/31",281 "IsEnabled": "1",282 "ProductCode": "PK0037721SIN17",283 "ProductDesc": "见证友谊,与小伙伴一起寻求刺激冒险挑战",284 "ProductSite": "新加坡",285 "ProductPrice": "54",286 "ProductID": "37937",287 "ProductAttentionNum": "",288 "ProductType": "T",289 },290 {291 "ProductName": "圣淘沙冲浪区电子票",292 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/2613/Wavehouse%202.jpg",293 "ProductIndex": "3",294 "ProductStartDate": "2013/3/20",295 "ProductEndDate": "2017/3/31",296 "IsEnabled": "1",297 "ProductCode": "PK0461871SIN17",298 "ProductDesc": "与闺蜜在亚洲顶级冲浪区感受热岛夏日的激情",299 "ProductSite": "新加坡",300 "ProductPrice": "59",301 "ProductID": "465004",302 "ProductAttentionNum": "",303 "ProductType": "T",304 },305 {306 "ProductName": "水上探险乐园电子票",307 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/2543/Adventure%20Cove%20Waterpark%204.jpg",308 "ProductIndex": "4",309 "ProductStartDate": "2013/3/11",310 "ProductEndDate": "2016/11/30",311 "IsEnabled": "1",312 "ProductCode": "PK0449909SIN17",313 "ProductDesc": "搭乘东南亚的第一个水电磁过山车",314 "ProductSite": "新加坡",315 "ProductPrice": "96",316 "ProductID": "453037",317 "ProductAttentionNum": "",318 "ProductType": "T",319 },320 {321 "ProductName": "新加坡文化大酒店Mandarin Orchard Singapore ",322 "ProductPicUrl": "http://images.asiatravel.com/Hotel/58/Facade-Day.jpg",323 "ProductIndex": "1",324 "ProductStartDate": "",325 "ProductEndDate": "",326 "IsEnabled": "1",327 "ProductCode": "",328 "ProductDesc": "文华大酒店是乌节路将传统东方文化和西方高雅的现代风格完美的结合的代表",329 "ProductSite": "乌节路",330 "ProductPrice": "1186",331 "ProductID": "58",332 "ProductAttentionNum": "",333 "ProductType": "H",334 },335 {336 "ProductName": "新加坡半岛怡东酒店Peninsula Excelsior Hotel",337 "ProductPicUrl": "http://images.asiatravel.com/Hotel/46/FRONT%202%20OK.jpg",338 "ProductIndex": "2",339 "ProductStartDate": "",340 "ProductEndDate": "",341 "IsEnabled": "1",342 "ProductCode": "",343 "ProductDesc": "半岛怡东酒店位于新加坡商业、娱乐区,距离历史悠久的新加坡河只有一街之隔",344 "ProductSite": "市政厅",345 "ProductPrice": "750",346 "ProductID": "46",347 "ProductAttentionNum": "",348 "ProductType": "H",349 },350 {351 "ProductName": "新加坡柏-伟诗酒店/瑞吉公园酒店Park Regis",352 "ProductPicUrl": "http://images.asiatravel.com/Hotel/8860/Facade.jpg",353 "ProductIndex": "3",354 "ProductStartDate": "",355 "ProductEndDate": "",356 "IsEnabled": "1",357 "ProductCode": "",358 "ProductDesc": "酒店紧靠来福士广场、滨海湾、新加坡商业及娱乐中心等知名景点",359 "ProductSite": "克拉码头",360 "ProductPrice": "693",361 "ProductID": "8860",362 "ProductAttentionNum": "",363 "ProductType": "H",364 },365 {366 "ProductName": "新加坡龙都大酒店Rendezvous Hotel Singapore",367 "ProductPicUrl": "http://images.asiatravel.com/Hotel/48/48_Facade.jpg",368 "ProductIndex": "4",369 "ProductStartDate": "",370 "ProductEndDate": "",371 "IsEnabled": "1",372 "ProductCode": "",373 "ProductDesc": "新加坡龙都大酒店是您来新加坡的最佳落脚点",374 "ProductSite": "",375 "ProductPrice": "985",376 "ProductID": "48",377 "ProductAttentionNum": "",378 "ProductType": "H",379 }380 ];381 //情侣模块382 var loversData = [383 {384 "ProductName": "夜游新加坡(含新加坡河游船)",385 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/2433/4-compressed.jpg",386 "ProductIndex": "1",387 "ProductStartDate": "2016/1/14",388 "ProductEndDate": "2017/3/31",389 "IsEnabled": "1",390 "ProductCode": "PK0506423SIN17",391 "ProductDesc": "和爱人泛舟新加坡河,感受古老建筑与现代摩天楼的对比,享受城市的美丽",392 "ProductSite": "新加坡",393 "ProductPrice": "238",394 "ProductID": "509737",395 "ProductAttentionNum": "",396 "ProductType": "T",397 },398 {399 "ProductName": "天空餐饮体验 - Cloud 9 Sky 餐厅 ",400 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/2449/116_31dec2013-compressed.jpg",401 "ProductIndex": "2",402 "ProductStartDate": "2016/3/22",403 "ProductEndDate": "2016/12/31",404 "IsEnabled": "1",405 "ProductCode": "PK0407866SIN17",406 "ProductDesc": "美妙的城市在浪漫夜空烘托下,与心爱人在摩天轮用餐,终身难忘",407 "ProductSite": "新加坡",408 "ProductPrice": "648",409 "ProductID": "409720",410 "ProductAttentionNum": "",411 "ProductType": "T",412 },413 {414 "ProductName": "老虎摩天塔电子票",415 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/2328/Sky%20Tower%205.jpg",416 "ProductIndex": "3",417 "ProductStartDate": "2012/12/27",418 "ProductEndDate": "2017/3/31",419 "IsEnabled": "1",420 "ProductCode": "PK0037730SIN17",421 "ProductDesc": "圣淘沙旅行最高点,可观及马来西亚甚至印尼全景",422 "ProductSite": "新加坡",423 "ProductPrice": "51",424 "ProductID": "37946",425 "ProductAttentionNum": "",426 "ProductType": "T",427 },428 {429 "ProductName": "2合1配套:新加坡摩天观景轮电子票+DuckTour之旅电子票",430 "ProductPicUrl": "http://packages.asiatravel.com/packageImage/Tour/AddtlImages/2137/Singapore%20Flyer%205.jpg",431 "ProductIndex": "4",432 "ProductStartDate": "2016/1/27",433 "ProductEndDate": "2016/9/30",434 "IsEnabled": "1",435 "ProductCode": "PK0506708SIN17",436 "ProductDesc": "360°无死角的标志性视觉盛宴",437 "ProductSite": "新加坡",438 "ProductPrice": "289",439 "ProductID": "510022",440 "ProductAttentionNum": "",441 "ProductType": "T",442 },443 {444 "ProductName": "新加坡喜来登大酒店Sheraton Towers",445 "ProductPicUrl": "http://images.asiatravel.com/Hotel/47/47facade.jpg",446 "ProductIndex": "1",447 "ProductStartDate": "",448 "ProductEndDate": "",449 "IsEnabled": "1",450 "ProductCode": "",451 "ProductDesc": "位于城市的心脏的国际五星豪华酒店",452 "ProductSite": "市中心",453 "ProductPrice": "776",454 "ProductID": "47",455 "ProductAttentionNum": "",456 "ProductType": "H",457 },458 {459 "ProductName": "圣淘沙安曼纳圣殿度假酒店Amara Sanctuary Resort Sentosa",460 "ProductPicUrl": "http://images.asiatravel.com/Hotel/5168/palawan-beach.jpg?_ga=1.252202889.1603362550.1458039440",461 "ProductIndex": "2",462 "ProductStartDate": "",463 "ProductEndDate": "",464 "IsEnabled": "1",465 "ProductCode": "",466 "ProductDesc": "圣淘沙阿玛拉私人度假村一个世界级综合度假胜地",467 "ProductSite": "圣淘沙",468 "ProductPrice": "1095",469 "ProductID": "5168",470 "ProductAttentionNum": "",471 "ProductType": "H",472 },473 {474 "ProductName": "新加坡圣淘沙嘉佩乐酒店 Capella Singapore",475 "ProductPicUrl": "http://images.asiatravel.com/Hotel/6822/6822exterior.jpg",476 "ProductIndex": "3",477 "ProductStartDate": "",478 "ProductEndDate": "",479 "IsEnabled": "1",480 "ProductCode": "",481 "ProductDesc": "一个远离尘嚣的世外桃源,新加坡最知名的度假天堂",482 "ProductSite": "圣淘沙",483 "ProductPrice": "2640",484 "ProductID": "6822",485 "ProductAttentionNum": "",486 "ProductType": "H",487 },488 {489 "ProductName": "新加坡泛太平洋酒店Pan Pacific Singapore",490 "ProductPicUrl": "http://images.asiatravel.com/Hotel/69/Facade1.jpg",491 "ProductIndex": "4",492 "ProductStartDate": "",493 "ProductEndDate": "",494 "IsEnabled": "1",495 "ProductCode": "",496 "ProductDesc": "尽情欣赏滨海湾的美丽风景",497 "ProductSite": "滨海湾",498 "ProductPrice": "1373",499 "ProductID": "69",500 "ProductAttentionNum": "",501 "ProductType": "H",502 }503 ];504 function oneticketTab(oneticketData) {505 var greatSalestr = $('#greatSale').html();506 var greatSaleList = ejs.render(greatSalestr, {greatSaleData: oneticketData})507 $('#one_sale_cont').html(greatSaleList);508 }509 oneticketTab(greatSaleData);510 //判断一元产品是否售罄511 var Parmeters = {512 "parameters": {"packageID": $('#oneticket_buy').attr('data-packageid')},513 "foreEndType": 2,514 "code": "20100003"515 }516 console.log(Parmeters);517 vlm.loadJson("", JSON.stringify(Parmeters), saleout);518 function saleout(ret) {519 var json = ret;520 if (json.success) {521 if ( ! json.data.tourAllotment.adultBalance) {522 //售罄523 $('#oneticket_buy').parents('.one_sale_show').find('.one_sale_bg').show();524 $('#oneticket_buy').parents('.one_sale_show').find('.one_price').css('color', '#ccc');525 $('#oneticket_buy').parents('.one_sale_show').find('.panic_buy').addClass('on');526 }527 }528 }529 //Tab切换530 $('.one_select >li').on('click', function () {531 var one_index = $(this).index();532 $(this).addClass('active').siblings().removeClass('active');533 switch (one_index) {534 case 0:535 $('.shortexhibition').attr('src', '../images/oneticket/great_sale.png');536 $('.one_sale_cont').css('backgroundColor', '#fed81d');537 $('.one_foot').css('backgroundColor', '#fed81d');538 oneticketTab(greatSaleData);539 break;540 case 1:541 $('.shortexhibition').attr('src', '../images/oneticket/child_all.png');542 $('.one_sale_cont').css('backgroundColor', '#7bc300');543 $('.one_foot').css('backgroundColor', '#7bc300');544 oneticketTab(childAllData);545 break;546 case 2:547 $('.shortexhibition').attr('src', '../images/oneticket/bestie.png');548 $('.one_sale_cont').css('backgroundColor', '#65ebe0');549 $('.one_foot').css('backgroundColor', '#65ebe0');550 oneticketTab(bestieData);551 break;552 case 3:553 $('.shortexhibition').attr('src', '../images/oneticket/lovers.png');554 $('.one_sale_cont').css('backgroundColor', '#4ad1ef');555 $('.one_foot').css('backgroundColor', '#4ad1ef');556 oneticketTab(loversData);557 break;558 }559 });560 }561 init();562})();563//立即抢购564function quickShop(obj) {565 var shopTarget = obj;566 var oneticketid = $(shopTarget).attr('data-packageId'), oneticket_scenic;567 if ($(shopTarget).attr('data-packagetype') == 'T') {568 if ($(shopTarget).attr('id') == 'oneticket_buy') {569 oneticket_scenic = '../scenic/scenic_detail.html?packageID=' + oneticketid + '&oneticket';570 } else {571 oneticket_scenic = '../scenic/scenic_detail.html?packageID=' + oneticketid;572 }573 //产品跳到景点详情574 window.location.href = oneticket_scenic;575 } else {576 //加国际酒店标识577 window.localStorage.hoPos = 'inter';578 //跳到酒店详情579 var oDate = new Date(),580 year = oDate.getFullYear(),581 month = oDate.getMonth(),582 day = oDate.getDate(),583 oDate1 = new Date(year, month, day + 2),584 oDate2 = new Date(year, month, day + 3),585 beginDate = vlm.Utils.format_date(oDate1.getFullYear() + '-' + (oDate1.getMonth() + 1) + '-' + oDate1.getDate(), 'Ymd'),586 leaveDate = vlm.Utils.format_date(oDate2.getFullYear() + '-' + (oDate2.getMonth() + 1) + '-' + oDate2.getDate(), 'Ymd');587 var hotelStr = '../hotel/hotel_detail.html?HotelID=' + oneticketid + '&HotelCode=' + oneticketid + '&InstantConfirmation=false&AllOccupancy=true&CheckInDate=' + beginDate + '&CheckOutDate=' + leaveDate + '&NumRoom=1&NumAdult=1&NumChild=0';588 window.location.href = hotelStr;589 }590}591//补零592function zero(num) {593 return num < 10 ? '0' + num : '' + num;...

Full Screen

Full Screen

pos_stock.js

Source:pos_stock.js Github

copy

Full Screen

...86 self.compute_qty_in_pos_location(res);87 done.resolve();88 });89 } else {90 self.load_qty_after_load_product();91 done.resolve();92 }93 return done;94 };95 },96 on_stock_notification: function (stock_quant) {97 var self = this;98 var product_ids = stock_quant.map(function (item) {99 return item.product_id[0];100 });101 if (this.config && this.config.show_qty_available && product_ids.length > 0) {102 $.when(self.qty_sync(product_ids)).done(function () {103 self.refresh_qty();104 });...

Full Screen

Full Screen

app.js

Source:app.js Github

copy

Full Screen

123const StoregeController = (function () {45 return{6 storeProduct:function (product){7 let products;8 if(localStorage.getItem('products')==null){9 10 products=[];11 products.push(product);12 13 }else{14 products=JSON.parse(localStorage.getItem('products'));15 products.push(product);16 }17 localStorage.setItem('products',JSON.stringify(products));18 },19 getProducts: function(){20 let products;21 if(localStorage.getItem('products')==null){22 products=[];23 24 }else{25 products=JSON.parse(localStorage.getItem('products'));26 }27 return products;28 },29 updateProduct: function(product){30 let products=JSON.parse(localStorage.getItem('products'));31 products.forEach((prd,index)=>{32 if(product.id==prd.id){33 products.splice(index,1,product);34 }3536 });37 localStorage.setItem('products',JSON.stringify(products));3839 },40 deleteProduct: function(id){41 let products=JSON.parse(localStorage.getItem('products'));42 products.forEach((prd,index)=>{43 if(id==prd.id){44 products.splice(index,1);45 }4647 });48 localStorage.setItem('products',JSON.stringify(products));4950 }51 }52 53 })();5455const ProductController = (function () {56 const Product = function (id, name, price) {57 this.id = id;58 this.name = name;59 this.price = price;60 };6162 const data = {63 products: StoregeController.getProducts(),64 selectedProducts: null,65 totalPrice: 0,66 };6768 return {69 getProduct: function () {70 return data.products;71 },72 getData: function () {73 return data;74 },75 getProductById: function (id) {76 let product;7778 data.products.forEach((prd)=>{79 if(prd.id == id) {80 product = prd;81 82 }83 })84 return product;85 },86 setCurrentProduct: function (product) {87 data.selectedProducts = product;88 },89 getCurrentProduct: function () {90 return data.selectedProducts;91 },92 addProduct: function (name, price) {93 let id;94 if (data.products.length > 0) {95 id = data.products[data.products.length - 1].id + 1;96 } else {97 id = 0;98 }99 const newProduct = new Product(id, name, parseFloat(price));100 data.products.push(newProduct);101 return newProduct;102 },103 updateProduct: function (name,price){104 let product= null;105106 data.products.forEach((prd)=>{107 if(prd.id==data.selectedProducts.id){108 prd.name=name;109 prd.price=parseFloat(price);110 product=prd;111 }112 });113114 return product;115116 },117 deleteProduct: function (product){118119 data.products.forEach((prd,index)=>{120121 if(prd.id==product.id){122 data.products.splice(index,1);123 }124125 })126 },127 getTotal: function () {128 let total = 0;129 data.products.forEach((item) => {130 total += item.price;131 });132 data.totalPrice = total;133 return data.totalPrice;134 },135 };136})();137138139140const UIController = (function () {141 const Selectors = {142 productList: "#item-list",143 productListItems: "#item-list tr",144 addButton: ".addBtn",145 productName: "#productName",146 productPrice: "#productPrice",147 productsCard: "#productCard",148 totalTL: "#totalTL",149 totalUSD: "#totalUSD",150 updateButton: ".updateBtn",151 deleteButton: ".deleteBtn",152 cancelButton: ".cancelBtn"153 };154 return {155 createProductList: function (products) {156 let html = "";157158 products.forEach((prd) => {159 html += `<tr>160 <td>${prd.id}</td>161 <td>${prd.name}</td>162 <td>${prd.price}$</td>163 <td class="text-right">164 165 <i class="far fa-edit edit-product"></i>166 167 168 </td>169 </tr>`;170 });171172 document.querySelector(Selectors.productList).innerHTML += html;173 },174 getSelectors: function () {175 return Selectors;176 },177 addProduct: function (prd) {178 document.querySelector(Selectors.productsCard).style.display = "block";179 let item = `<tr>180 <td>${prd.id}</td>181 <td>${prd.name}</td>182 <td>${prd.price}$</td>183 <td class="text-right">184 <i class="far fa-edit edit-product"></i>185 186 </td>187 </tr>`;188 document.querySelector(Selectors.productList).innerHTML += item;189 },190 clearInputs: function () {191 document.querySelector(Selectors.productName).value = "";192 document.querySelector(Selectors.productPrice).value = "";193 },194 clearInfo: function (){195 const items= document.querySelectorAll(Selectors.productListItems);196 items.forEach((item)=>{197 if(item.classList.contains("bg-info")){198 item.classList.remove("bg-info");199 item.classList.remove("text-white");200 }201 })202 },203 hideCard: function () {204 document.querySelector(Selectors.productsCard).style.display = "none";205 },206207 showTotal: function (total) {208 async function exchange() {209 const getCurrentUSD = await fetch(210 "https://api.exchangeratesapi.io/latest?symbols=USD,TRY"211 );212 const response = await getCurrentUSD.json();213 return response.rates;214 }215 exchange().then((rates) => {216 document.querySelector(Selectors.totalUSD).innerHTML = total;217 document.querySelector(Selectors.totalTL).innerHTML = parseFloat(218 total * rates.TRY219 ).toFixed(2);220 });221 },222 addProductForm: function(){223 const selectedProducts= ProductController.getCurrentProduct();224 225 document.querySelector(Selectors.productName).value=selectedProducts.name;226 document.querySelector(Selectors.productPrice).value=selectedProducts.price;227228 },229 deleteProduct:function(){230 let items=document.querySelectorAll(Selectors.productListItems);231 items.forEach((item)=>{232 if(item.classList.contains("bg-info")){233 item.remove();234 }235 })236 },237 addingState: function (item) {238 UIController.clearInfo();239 UIController.clearInputs();240 document.querySelector(Selectors.addButton).style.display='inline';241 document.querySelector(Selectors.updateButton).style.display='none';242 document.querySelector(Selectors.deleteButton).style.display='none';243 document.querySelector(Selectors.cancelButton).style.display='none';244 },245 editState: function (tr) {246247 248 tr.classList.add("bg-info");249 tr.classList.add("text-white");250 document.querySelector(Selectors.addButton).style.display='none';251 document.querySelector(Selectors.updateButton).style.display='inline';252 document.querySelector(Selectors.deleteButton).style.display='inline';253 document.querySelector(Selectors.cancelButton).style.display='inline';254 },255 updateProduct: function (prd){256257 let updatedItems =null;258 ;259 let items=document.querySelectorAll(Selectors.productListItems);260 items.forEach((item)=>{261 if(item.classList.contains("bg-info")){262 item.children[1].innerHTML=prd.name;263 item.children[2].innerHTML=prd.price+" $";264 265 updatedItems=item;266 }267268 })269270 return updatedItems;271272 }273274 };275})();276//main277const App = (function (ProductController, UIController, StoregeController) {278 const UISelectors = UIController.getSelectors();279280 const loadEventListeners = function () {281 document.querySelector(UISelectors.addButton).addEventListener("click", productAddSubmit);282 283 document.querySelector(UISelectors.productList).addEventListener("click",productEditClick)284 285 document.querySelector(UISelectors.updateButton).addEventListener("click", editProductSubmit);286287 document.querySelector(UISelectors.cancelButton).addEventListener("click",cancelUpdate);288 289 document.querySelector(UISelectors.deleteButton).addEventListener("click",deleteProductSubmit);290 };291292 const deleteProductSubmit = function(e) {293 e.preventDefault();294 const selectedProduct = ProductController.getCurrentProduct();295 ProductController.deleteProduct(selectedProduct);296 UIController.deleteProduct();297 const total = ProductController.getTotal();298299 UIController.showTotal(total);300301 StoregeController.deleteProduct(selectedProduct.id);302303 UIController.addingState();304 if(total==0) UIController.hideCard();305 306 }307308 const cancelUpdate=function(e) {309 e.preventDefault();310 UIController.addingState();311 UIController.clearInfo();312313314 }315316 const editProductSubmit = function(e){317 e.preventDefault();318 const productName = document.querySelector(UISelectors.productName).value;319 const productPrice = document.querySelector(UISelectors.productPrice).value;320 if(productName!=="" && productPrice!==""){321 const updatedProduct = ProductController.updateProduct(productName, productPrice);322 323 UIController.updateProduct(updatedProduct);324325 const total = ProductController.getTotal();326327 UIController.showTotal(total);328329 StoregeController.updateProduct(updatedProduct);330331 UIController.addingState();332333 }334335 }336337 const productEditClick = function(e){338 339 if(e.target.classList.contains('edit-product')){340 const id= e.target.parentNode.previousElementSibling.previousElementSibling.previousElementSibling.textContent;341 342 const product = ProductController.getProductById(id);343344 ProductController.setCurrentProduct(product);345 346 UIController.clearInfo();347348 UIController.addProductForm();349350 UIController.editState(e.target.parentNode.parentNode);351 352 }353 e.preventDefault();354 }355356 const productAddSubmit = function (e) {357 e.preventDefault();358 const productName = document.querySelector(UISelectors.productName).value;359 const productPrice = document.querySelector(UISelectors.productPrice).value;360361 if (362 productName !== "" &&363 productPrice !== "" &&364 isNaN(productPrice) == false365 ) {366 const newProduct = ProductController.addProduct(367 productName,368 productPrice369 );370 UIController.addProduct(newProduct);371372 StoregeController.storeProduct(newProduct);373374 const total = ProductController.getTotal();375 UIController.clearInputs();376 UIController.showTotal(total);377378 379 } else {380 alert("Price must be a number");381 }382 };383384 return {385 init: function () {386387 UIController.addingState();388389 const products = ProductController.getProduct();390391 if (products.length == 0) {392 UIController.hideCard();393 } else {394 UIController.createProductList(products);395 }396397 loadEventListeners();398 },399 };400})(ProductController, UIController, StoregeController);401 ...

Full Screen

Full Screen

services.js

Source:services.js Github

copy

Full Screen

1const Product = require("../models/Product")2const Category = require("../models/Category")3const Variant = require("../models/Variant")4const Summary = require("../models/Browsing")5const Inventory = require("../models/Inventory")6const Collection = require("../models/Collection")7const AwsStorageProvider = require("./StorageProvider/storageProvider")8const uuid = require('uuid')9const config = require('../config/index')10const keys = config.awsS311const AWS = require('aws-sdk')12const s3 = new AWS.S3({13 accessKeyId:keys.accessKey,14 secretAccessKey:keys.secretKey,15 region:"ap-south-1"16})17const createProduct = async (fastify,createProductRequest) =>{18 const subcategories = await getSubCategory(fastify)19 if (!subcategories[createProductRequest.mainCategory].includes(createProductRequest.subCategory)){20 return {21 response : "Not Found"22 }23 } else {24 const features = await getFeatures(fastify , {25 mainCategory: createProductRequest.mainCategory,26 subCategory: createProductRequest.subCategory27 })28 const feature={}29 features.forEach((fea)=>{30 feature[fea.featureName] = fea.featureValues31 32 })33 34 for(let fea in createProductRequest.features){35 if(feature[fea]){36 if(!feature[fea].includes(createProductRequest.features[fea])){37 return { response: "Feature Value not Allowed"}38 }39 }else{40 return {41 response: "Feature is not defined"42 }43 }44 }45 46 }47 const collection = await Collection.findOne({})48 collection.noOfProducts += 149 const product = new Product({50 productId:"Product_"+collection.noOfProducts,51 ...createProductRequest52 })53 await new Collection(collection).save()54 55 return product.save()56}57const createCategory = async (fastify,createCategoryRequest)=>{58 const category = new Category(createCategoryRequest)59 return category.save()60}61const getProductById = async (fastify,params) =>{62 return Product.findOne({productId:params.productId })63}64const getProducts = async (fastify,getProductRequest) => {65 if (getProductRequest.mainCategory && getProductRequest.subCategory){66 const subcategories = await getSubCategory(fastify)67 68 if (!subcategories[getProductRequest.mainCategory].includes(getProductRequest.subCategory)){69 return {70 response : "Not Found"71 }72 }73 }74 const Products = await Product.find(getProductRequest)75 const products = await Products.filter((product) => {76 return product.markForDelete === false77 })78 79 if(products.length === 0){80 return {81 response : "Product Not Found"82 }83 }84 return products85 86}87const getSubCategory = async (fastify) => {88 let categories = await Category.find({})89 let subcategories = {}90 categories.forEach((category)=>{91 if(subcategories[category.mainCategory]){92 subcategories[category.mainCategory] = [93 ...subcategories[category.mainCategory],94 category.subCategory95 ]96 }else {97 subcategories[category.mainCategory] = [category.subCategory]98 }99 })100 return subcategories101 102}103const getFeatures = async (fastify,getFeaturesRequest) => {104 const subcategories = await getSubCategory(fastify)105 106 if (subcategories[getFeaturesRequest.mainCategory].includes(getFeaturesRequest.subCategory)){107 let feature = await Category.findOne({...getFeaturesRequest})108 109 return feature["features"]110 } else {111 return {112 response : "Not Found"113 }114 }115 116}117const createVariant = async (fastify,createVariantRequestBody,createVariantRequestQuery)=>{118 const product = await getProducts(fastify,{productId: createVariantRequestBody.productId})119 120 if(product.length === 0) {121 return {122 "response" : "Product Not found"123 }124 }125 const collection = await Collection.findOne({})126 collection.noOfVariants += 1127 const variant = new Variant({128 variantId:"Variant_"+collection.noOfVariants,129 ...createVariantRequestBody130 })131 const inventory = new Inventory({132 variantId: "Variant_"+collection.noOfVariants,133 inventory: createVariantRequestQuery.inventory,134 reservedInventory: createVariantRequestQuery.reservedInventory135 })136 137 await inventory.save()138 await new Collection(collection).save()139 140 return variant.save()141}142const inputBrowse = async (fastify) => {143 const variants = await Variant.find({})144 const productss = await getProducts(fastify,{})145 const products = {}146 productss.forEach((product)=>{147 products[product.productId] = product148 })149 variants.forEach(async (variant) => {150 const product = products[variant.productId]151 const summary = new Summary({152 variantId : variant.variantId,153 productId: variant.productId,154 mainCategory: product.mainCategory,155 subCategory: product.subCategory,156 price:variant.price,157 productFeatures:{158 ...product.features,159 thumbnails:product.thumbnails,160 brand:product.brand}161 })162 163 await summary.save()164 })165 166 const summary = await Summary.find({})167 168 return summary169}170const uploadFile = async (fastify,uploadRequest,folderInfo,callback) =>{171 const storageProvider = new AwsStorageProvider(fastify,uploadRequest,folderInfo,callback)172 return storageProvider.uploadFile()173}174const filterBrowse = async (fastify,filterRequest)=>{175 let filter = {}176 for(var fea in filterRequest){177 if(fea === "productFeatures"){178 for(var feature in filterRequest.productFeatures){179 filter['productFeatures.'+feature] = filterRequest.productFeatures[feature] 180 }181 }else{182 filter[fea] = filterRequest[fea]183 }184 }185 186 var variants = await Summary.find(filter)187 188 const productsWithSameProductId = {}189 const products=[]190 variants.forEach((variant)=>{191 if(productsWithSameProductId[variant.productId]){192 productsWithSameProductId[variant.productId] = [...productsWithSameProductId[variant.productId], variant]193 }else{194 productsWithSameProductId[variant.productId] = [variant]195 }196 })197 for(var productId in productsWithSameProductId){198 products.push(productsWithSameProductId[productId][0])199 }200 201 return products202} 203const getProductPriority = async (fastify,getProductPriorityRequest) =>{204 const product = await Product.findOneAndUpdate({productId : getProductPriorityRequest.productId},205 {$inc : {priority:getProductPriorityRequest.priorityIcrement }})206 if (!product){207 return {208 response : "Not Found"209 }210 }211 212 return { "priority" : product["priority"]}213}214const getVariants = async (fastify,getVariantsRequest) =>{215 const product = await Product.findOne({productId : getVariantsRequest.productId})216 const variants = await Variant.find({productId : getVariantsRequest.productId})217 218 const productInfo = {...product, variants: variants}219 if (!product){220 return {221 response : "Not Found"222 }223 }224 225 return productInfo226}227module.exports ={228 createProduct,229 createCategory,230 createVariant,231 getProducts,232 getProductById,233 getFeatures,234 getSubCategory,235 uploadFile,236 inputBrowse,237 filterBrowse,238 getProductPriority,239 getVariants...

Full Screen

Full Screen

productController.js

Source:productController.js Github

copy

Full Screen

1const asyncHandler = require('express-async-handler');2const {Product} = require('../models/productModel');3// @desc Fetch all products4// @route GET /api/products5// @access Public6const getProducts = asyncHandler(async (req, res) =>{7 const pageSize = 48 const page = Number(req.query.pageNumber) || 19 const keyword = req.query.keyword ? {10 name: {11 $regex: req.query.keyword,12 $options: 'i'13 }14 } : {}15 const count = await Product.countDocuments({ ...keyword })16 const products = await Product.find({ ...keyword }).limit(pageSize).skip(pageSize * (page - 1))17 res.json({products, page, pages: Math.ceil(count / pageSize)});18})19// @desc Fetch single product20// @route GET /api/products/:id21// @access Public22const getProductById = asyncHandler(async (req, res) =>{23 const product = await Product.findById(req.params.id)24 if(product){25 res.json(product);26 } else {27 res.status(404)28 throw new Error('Product not found')29 };30})31// @desc Delete product32// @route DELETE /api/products/:id33// @access Private/Admin34const deleteProduct = asyncHandler(async (req, res) =>{35 const product = await Product.findById(req.params.id)36 if(product){37 await product.remove()38 res.json({ message: 'Product removed' })39 } else {40 res.status(404)41 throw new Error('Product not found')42 };43})44// @desc Create product45// @route POST /api/products46// @access Private/Admin47const createProduct = asyncHandler(async (req, res) =>{48 const product = new Product({49 name: 'Sample name',50 price: 0,51 user: req.user._id,52 image: '/images/sample.jpg',53 brand: 'Sample brand',54 category: 'Sample category',55 countInStock: 0,56 numReviews: 0,57 description: 'Sample description'58 })59 const createdProduct = await product.save()60 res.status(201).json(createdProduct)61})62// @desc Update a product63// @route PUT /api/products/:id64// @access Private/Admin65const updateProduct = asyncHandler(async (req, res) =>{66 const { 67 name, 68 price, 69 description, 70 image, 71 brand, 72 category, 73 countInStock 74 } = req.body75 const product = await Product.findById(req.params.id)76 if(product){77 product.name = name78 product.price = price79 product.description = description80 product.image = image81 product.brand = brand82 product.category = category83 product.countInStock = countInStock84 const updatedProduct = await product.save()85 res.json(updatedProduct)86 }else {87 res.status(404)88 throw new Error('Product not found')89 }90 91})92// @desc Create new review93// @route POST /api/products/:id/reviews94// @access Private95const createProductReview = asyncHandler(async (req, res) =>{96 const { rating, comment } = req.body97 const product = await Product.findById(req.params.id)98 if(product){99 const alreadyReviewed = product.reviews.find( r => r.user.toString() === req.user._id.toString())100 if(alreadyReviewed){101 res.status(400)102 throw new Error('Product already reviewed')103 }104 const review = {105 name: req.user.name,106 rating: Number(rating),107 comment,108 user: req.user._id109 }110 product.reviews.push(review)111 product.numReviews = product.reviews.length112 product.rating = product.reviews.reduce((acc, item) => item.rating + acc, 0) / product.reviews.length113 await product.save()114 res.status(201).json({ message: 'Review added' })115 }else {116 res.status(404)117 throw new Error('Product not found')118 }119 120})121// @desc Get top rated products122// @route GET /api/products/top123// @access Public124const getTopProducts = asyncHandler(async (req, res) =>{125 const products = await Product.find({}).sort({ rating: -1 }).limit(3)126 res.json(products)127})...

Full Screen

Full Screen

productReducers.js

Source:productReducers.js Github

copy

Full Screen

1import { 2 PRODUCT_LIST_REQUEST, 3 PRODUCT_LIST_SUCCESS, 4 PRODUCT_LIST_FAIL, 5 PRODUCT_DETAILS_REQUEST, 6 PRODUCT_DETAILS_SUCCESS, 7 PRODUCT_DETAILS_FAIL,8 PRODUCT_DELETE_REQUEST,9 PRODUCT_DELETE_SUCCESS,10 PRODUCT_DELETE_FAIL,11 PRODUCT_CREATE_REQUEST,12 PRODUCT_CREATE_SUCCESS,13 PRODUCT_CREATE_FAIL,14 PRODUCT_CREATE_RESET,15 PRODUCT_UPDATE_REQUEST,16 PRODUCT_UPDATE_SUCCESS,17 PRODUCT_UPDATE_FAIL,18 PRODUCT_UPDATE_RESET ,19 PRODUCT_CREATE_REVIEW_REQUEST,20 PRODUCT_CREATE_REVIEW_SUCCESS,21 PRODUCT_CREATE_REVIEW_FAIL,22 PRODUCT_CREATE_REVIEW_RESET,23 PRODUCT_TOP_REQUEST,24 PRODUCT_TOP_SUCCESS,25 PRODUCT_TOP_FAIL,26} from '../constants/productConstants'27export const productListReducer = (state={ products: []}, action)=>{28 switch(action.type){29 case PRODUCT_LIST_REQUEST:30 return { loading: true, products: []}31 case PRODUCT_LIST_SUCCESS:32 return {33 loading: false, 34 products: action.payload.products,35 pages: action.payload.pages,36 page: action.payload.page37 } 38 case PRODUCT_LIST_FAIL:39 return {loading: false, error: action.payload} 40 default:41 return state42 };43};44export const productDetailsReducer = (state={ product: { reviews: []}}, action)=>{45 switch(action.type){46 case PRODUCT_DETAILS_REQUEST:47 return { loading: true, ...state}48 case PRODUCT_DETAILS_SUCCESS:49 return {loading: false, product: action.payload} 50 case PRODUCT_DETAILS_FAIL:51 return {loading: false, error: action.payload} 52 default:53 return state54 };55};56export const productDeleteReducer = (state={}, action)=>{57 switch(action.type){58 case PRODUCT_DELETE_REQUEST:59 return { loading: true}60 case PRODUCT_DELETE_SUCCESS:61 return {loading: false, success: true} 62 case PRODUCT_DELETE_FAIL:63 return {loading: false, error: action.payload} 64 default:65 return state66 };67};68export const productCreateReducer = (state={}, action)=>{69 switch(action.type){70 case PRODUCT_CREATE_REQUEST:71 return { loading: true}72 case PRODUCT_CREATE_SUCCESS:73 return {loading: false, success: true, product: action.payload} 74 case PRODUCT_CREATE_FAIL:75 return {loading: false, error: action.payload} 76 case PRODUCT_CREATE_RESET:77 return {} 78 default:79 return state80 };81};82export const productUpdateReducer = (state={ product: {} }, action)=>{83 switch(action.type){84 case PRODUCT_UPDATE_REQUEST:85 return { loading: true}86 case PRODUCT_UPDATE_SUCCESS:87 return {loading: false, success: true, product: action.payload} 88 case PRODUCT_UPDATE_FAIL:89 return {loading: false, error: action.payload} 90 case PRODUCT_UPDATE_RESET:91 return { product: {} } 92 default:93 return state94 };95};96export const productReviewCreateReducer = (state={}, action)=>{97 switch(action.type){98 case PRODUCT_CREATE_REVIEW_REQUEST:99 return { loading: true}100 case PRODUCT_CREATE_REVIEW_SUCCESS:101 return {loading: false, success: true} 102 case PRODUCT_CREATE_REVIEW_FAIL:103 return {loading: false, error: action.payload} 104 case PRODUCT_CREATE_REVIEW_RESET:105 return {} 106 default:107 return state108 };109};110export const productTopRatedReducer = (state={ products: [] }, action)=>{111 switch(action.type){112 case PRODUCT_TOP_REQUEST:113 return { loading: true, products: []}114 case PRODUCT_TOP_SUCCESS:115 return {loading: false, products: action.payload} 116 case PRODUCT_TOP_FAIL:117 return {loading: false, error: action.payload} 118 default:119 return state120 };...

Full Screen

Full Screen

productConstants.js

Source:productConstants.js Github

copy

Full Screen

1export const PRODUCT_LIST_REQUEST = 'PRODUCT_LIST_REQUEST';2export const PRODUCT_LIST_SUCCESS = 'PRODUCT_LIST_SUCCESS';3export const PRODUCT_LIST_FAIL = 'PRODUCT_LIST_FAIL';4export const PRODUCT_DETAILS_REQUEST = 'PRODUCT_DETAILS_REQUEST';5export const PRODUCT_DETAILS_SUCCESS = 'PRODUCT_DETAILS_SUCCESS';6export const PRODUCT_DETAILS_FAIL = 'PRODUCT_DETAILS_FAIL';7export const PRODUCT_DELETE_REQUEST = 'PRODUCT_DELETE_REQUEST';8export const PRODUCT_DELETE_SUCCESS = 'PRODUCT_DELETE_SUCCESS';9export const PRODUCT_DELETE_FAIL = 'PRODUCT_DELETE_FAIL';10export const PRODUCT_CREATE_REQUEST = 'PRODUCT_CREATE_REQUEST';11export const PRODUCT_CREATE_SUCCESS = 'PRODUCT_CREATE_SUCCESS';12export const PRODUCT_CREATE_FAIL = 'PRODUCT_CREATE_FAIL';13export const PRODUCT_CREATE_RESET = 'PRODUCT_CREATE_RESET';14export const PRODUCT_UPDATE_REQUEST = 'PRODUCT_UPDATE_REQUEST';15export const PRODUCT_UPDATE_SUCCESS = 'PRODUCT_UPDATE_SUCCESS';16export const PRODUCT_UPDATE_FAIL = 'PRODUCT_UPDATE_FAIL';17export const PRODUCT_UPDATE_RESET = 'PRODUCT_UPDATE_RESET';18export const PRODUCT_CREATE_REVIEW_REQUEST = 'PRODUCT_CREATE_REVIEW_REQUEST';19export const PRODUCT_CREATE_REVIEW_SUCCESS = 'PRODUCT_CREATE_REVIEW_SUCCESS';20export const PRODUCT_CREATE_REVIEW_FAIL = 'PRODUCT_CREATE_REVIEW_FAIL';21export const PRODUCT_CREATE_REVIEW_RESET = 'PRODUCT_CREATE_REVIEW_RESET';22export const PRODUCT_TOP_REQUEST = 'PRODUCT_TOP_REQUEST';23export const PRODUCT_TOP_SUCCESS = 'PRODUCT_TOP_SUCCESS';...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.screenshot({path: 'example.png'});6 await browser.close();7})();8{9 "scripts": {10 },11 "dependencies": {12 }13}

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.screenshot({path: 'example.png'});6 await browser.close();7})();8{9 "scripts": {10 },11 "dependencies": {12 }13}

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.screenshot({path: 'example.png'});6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch();11 const page = await browser.newPage();12 await page.screenshot({path: 'example.png'});13 await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch();18 const page = await browser.newPage();19 await page.screenshot({path: 'example.png'});20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch();25 const page = await browser.newPage();26 await page.screenshot({path: 'example.png'});27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch();32 const page = await browser.newPage();33 await page.screenshot({path: 'example.png'});34 await browser.close();35})();36const puppeteer = require('puppeteer

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.screenshot({path: 'screenshot.png'});6 await browser.close();7})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const devices = require('puppeteer/DeviceDescriptors');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 await page.emulate(devices['iPhone 6']);7 await page.screenshot({path: 'example.png'});8 await browser.close();9})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3const browser = await puppeteer.launch();4const page = await browser.newPage();5await page.screenshot({path: 'google.png'});6await browser.close();7})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4(async () => {5 const browser = await puppeteer.launch();6 const page = await browser.newPage();7 await page.screenshot({path: 'google.png'});8 await browser.close();9})();10{11 "scripts": {12 },13 "dependencies": {14 }15}16{17 "dependencies": {18 "ansi-regex": {19 },20 "ansi-styles": {21 "requires": {22 }23 },24 "aproba": {

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const browser = await puppeteer.launch({headless: false});3const page = await browser.newPage();4await page.screenshot({path: 'example.png'});5await browser.close();6const puppeteer = require('puppeteer');7const browser = await puppeteer.launch({headless: false});8const page = await browser.newPage();9await page.screenshot({path: 'example.png'});10await browser.close();11const browser = await puppeteer.launch();12const page = await browser.newPage();13await page.goto(url, {waitUntil: 'networkidle0'});14await page.pdf({path: path, format: 'A4', printBackground: true});15await browser.close();16const browser = await puppeteer.launch();17const page = await browser.newPage();18await page.goto(url, {waitUntil: 'networkidle0'});19await page.pdf({path: path, format: 'A4', printBackground: true});20await browser.close();21await browser.close();22const browser = await puppeteer.launch();23const page = await browser.newPage();24await page.goto(url, {wait

Full Screen

Using AI Code Generation

copy

Full Screen

1const { product } = require('puppeteer');2const p = product();3console.log(p);4const { userAgent } = require('puppeteer');5const ua = userAgent();6console.log(ua);7const { executablePath } = require('puppeteer');8const path = executablePath();9console.log(path);10const { connect } = require('puppeteer');11var browser = null;12connect({13}).then((b) => {14 browser = b;15 console.log(browser);16}).catch((err) => {17 console.log(err);18});

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2function getProductDetails() {3 const productDetails = [];4 const productElements = document.querySelectorAll('.product');5 productElements.forEach(productElement => {6 const title = productElement.querySelector('.title').innerText;7 const price = productElement.querySelector('.price').innerText;8 const image = productElement.querySelector('img').src;9 productDetails.push({10 });11 });12 return productDetails;13}14(async () => {15 const browser = await puppeteer.launch();16 const page = await browser.newPage();17 await page.waitFor(2000);18 const productDetails = await page.evaluate(getProductDetails);19 await browser.close();20 console.log(productDetails);21})();22{23 "scripts": {24 },25 "dependencies": {26 }27}28const puppeteer = require('puppeteer');29function getProductDetails() {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful