Blame | Last modification | View Log | RSS feed
// Show Scratch Offers$(document).on('click', '.scratch-offers', function () {doGetAjaxRequestHandler(`${context}/store/offer/showScratchOffers`, function (response) {$('#main-content').html(response);});});// Offer image input$(document).on('click', '.add-offer-image', function () {const newEntry = `<div class="offer-image-entry"><input type="file" class="form-control offer-image-file" accept="image/*" required><input type="hidden" class="offer-image-id" name="offerImageIds[]"></div>`;$('.offer-images-container').append(newEntry);});// Handle offer image upload$(document).on('input', '.offer-image-file', function () {const $input = $(this);const $hiddenInput = $input.siblings('.offer-image-id');const files = Array.from($input[0].files);if (!files.length) {alert('Please select images');return;}console.log("files", files);// Process all filesconst uploadPromises = files.map(file => {return new Promise((resolve, reject) => {uploadDocument(file, (documentId) => {if (documentId) {resolve(documentId);} else {reject(`Upload failed for ${file.name}`);}});});});Promise.all(uploadPromises).then(newDocIds => {// Get existing IDs and append new onesconst existingIds = $hiddenInput.val()? $hiddenInput.val().split(','): [];const allIds = [...existingIds, ...newDocIds];$hiddenInput.val(allIds.join(','));console.log('Uploaded IDs:', allIds);}).catch(error => {console.error(error);alert(`Error: ${error}. Some files might not have uploaded.`);$input.val(''); // Clear input on error});});// Unified gift handling for both create/edit modals$(document).on('click', '.add-gift', function () {// Get current gift indexconst index = $('.gift-row').length;const giftRow = $('tr.gift-row:first').clone();giftRow.find('input, select, textarea').val('');giftRow.find('.default-gift-radio').prop('checked', false);giftRow.find('.multiselect-container').remove();giftRow.find('button.multiselect').remove();giftRow.append('<td class="align-middle">\n' +' <button type="button" class="btn btn-sm btn-danger remove-gift">' +' <i class="fa fa-times"></i>' +' </button>' +' </td>');console.log(giftRow);// Append new row to table body$(this).closest('table').find('tbody').append(giftRow);initMultiselect(giftRow.find('select[name="productCategory"]'), 'Categories');initMultiselect(giftRow.find('.partnerInfo'), 'Partner');});// Remove gift row$(document).on('click', '.remove-gift', function () {$(this).closest('tr').remove();});// Handle gift thumbnail uploads$(document).on('input', '.gift-thumbnail-file', function () {const file = this.files[0];const $hiddenInput = $(this).siblings('.gift-thumbnail-id');if (file && confirm('Confirm gift thumbnail upload?')) {uploadDocument(file, function (documentId) {if (documentId) {$hiddenInput.val(documentId);} else {alert('Thumbnail upload failed. Please try again.');$(this).val('');}});} else {$(this).val('');}});// Submit offer handler$(document).on('click', '.submit-offer', function () {const form = $('#offerForm');// console.log("this is the form data" + form);const requiredFields = form.find('[required]');const offerImageIds = $('[name="offerImageIds[]"]').map((i, el) => el.value).get();if (offerImageIds.some(id => !id)) {alert('Please complete all image uploads.');return;}if (!validateRequiredFields(requiredFields)) {window.alert('Please fill all required fields');return;}const formData = {name: form.find('[name="name"]').val(),description: form.find('[name="description"]').val(),offerType: "Scratch Card",startDate: form.find('[name="start_date"]').val(),endDate: form.find('[name="end_date"]').val(),termsCondition: form.find('[name="termsCondition"]').val(),userLimit: form.find('[name="userLimit"]').val(),scratchValidity: form.find('[name="scratchValidity"]').val(),productCategory: form.find('[name="productCategory"]').val().toString(),paymentMethod: form.find('[name="paymentMethod"]').val().toString(),offerImage: form.find('[name="offerImageIds[]"]').map(function () {return $(this).val();}).get().join(','),active: form.find('[name="isActive"]').is(':checked'),classification: form.find(".classification").val().toString(),gifts: []};$('#offerModal').on('show.bs.modal', function () {// Reset form inputs$('#offerForm')[0].reset();// Remove all dynamically added gift rows except the first$('.gift-row:not(:first)').remove();// Clear the first gift row's inputs$('.gift-row:first').find('input, select, textarea').val('');// Clear offer images container$('.offer-images-container').html(`<div class="offer-image-entry"><input type="file" class="form-control offer-image-file" accept="image/*" required><input type="hidden" class="offer-image-id" name="offerImageIds[]"></div>`);// Reinitialize multiselectsinitMultiselect('select[name="productCategory"]', 'Categories');initMultiselect('select[name="partnerInfo"]', 'Partner');initMultiselect('select[name="paymentMethod"]', 'Payment method');// Reset any file inputs in remaining gift rows$('.gift-thumbnail-file, .fofo-store-file').val('');$('.gift-thumbnail-id, .fofo-store-id').val('');});$('.dynamic-table tr.gift-row').each(function () {initMultiselect($(this).find('.product-category'), 'Categories');const row = $(this);console.log("Product categofy {}", row.find('.product-category').val());formData.gifts.push({id: row.find('[name="gifts[].id"]').val() || null,name: row.find('.gift-name').val(),minCartValue: row.find('.gift-min-cart').val(),maxCartValue: row.find('.gift-max-cart').val(),maxRedemptions: row.find('.gift-redemptions').val(),thumbnailUrl: row.find('.gift-thumbnail-id').val(),productCategory: row.find('.gift-product-category').val() ? row.find('.gift-product-category').val().toString() : "",fofoStore: row.find('.fofo-store-id').val() + row.find('.partnerInfo').val(),partnerInfo: row.find('.partnerInfo').val(),isDefault: row.find('.default-gift-radio').is(':checked')});});// Debug: Check collected dataconsole.log("Submitting gift data:", formData.gifts);doAjaxRequestWithJsonHandler(`${context}/store/offer/createoffer`,"POST",JSON.stringify(formData),function (response) {if (response) {$('#offerModal').modal('hide');$('body').removeClass('modal-open');$('.modal-backdrop').remove();refreshOfferTable();alert('Offer created successfully!');} else {alert("Cannot create the offer, please Try Again");}});});// Edit Form handler$(document).on('click', '.edit-offer', function () {const id = $(this).val();doGetAjaxRequestHandler(`${context}/store/offer/editOffer/${id}`, function (response) {$('#edit-modal-content').html(response);$('#editOfferModal').modal('show');});});// Delete offer handler$(document).on('click', '.delete-offer', function () {const id = $(this).val();console.log("this is the id" + id);if (confirm('Are you sure you want to delete this offer?')) {doDeleteAjaxRequestHandler(`${context}/store/offer/deleteOffer/${id}`,function (res) {if (res) {alert('Offer deleted successfully!');refreshOfferTable();} else {alert('Can Not Delete ongoing Offer!');}});}});// Delete gift handler$(document).on('click', '.delete-gift', function () {const id = $(this).val();console.log("this is the id" + id);if (confirm('Are you sure you want to delete this gift?')) {doDeleteAjaxRequestHandler(`${context}/store/gift/deleteGift/${id}`,function () {refreshOfferTable();$('#giftModal').modal('hide');$('body').removeClass('modal-open');$('.modal-backdrop').remove();alert('Gift deleted successfully!');});}});// Get Gift by id$(document).on('click', '.get-offerby-id', function () {const id = $(this).val();$('#loading-spinner').show();doGetAjaxRequestHandler(`${context}/store/giftsByOfferId/${id}`,function (response) {$('#gift-content').html(response);$('#giftModal').modal('show');$('#loading-spinner').hide();},function (error) {$('#loading-spinner').hide();console.error('API Error:', error);alert('Error loading gifts. Check the console for details.');});});// Referesh Offer Tablefunction refreshOfferTable() {doGetAjaxRequestHandler(`${context}/store/offer/showScratchOffers`, function (response) {$('#main-content').html(response);});}// Update the update button handler// Fixed Update button handler$(document).on('click', '.update-offer', function () {const form = $('#editofferForm');const offerId = $(this).data('offer-id');// Debug: Log form existence and fieldsconsole.log('Form found:', form.length);console.log('Offer ID:', offerId);const formData = {id: form.find('[name="id"]').val(),name: form.find('[name="name"]').val(),description: form.find('[name="description"]').val(),offerType: "Scratch Card",startDate: form.find('[name="start_date"]').val(),endDate: form.find('[name="end_date"]').val(),termsCondition: form.find('[name="termsCondition"]').val(),userLimit: parseInt(form.find('[name="userLimit"]').val()) || 0,scratchValidity: parseInt(form.find('[name="scratchValidity"]').val()) || 0,productCategory: form.find('[name="productCategory"]').val() ? form.find('[name="productCategory"]').val().join(',') : '',paymentMethod: form.find('[name="paymentMethod"]').val() ? form.find('[name="paymentMethod"]').val().join(',') : '',classification: form.find('[name="classification"]').val() || '',gifts: []};// Debug: Log basic form dataconsole.log('Basic form data collected:', formData);// Process gifts with better error handling// Simplified approach using class selectors$('#giftsContainer tbody tr.gift-row').each(function (index) {const row = $(this);// Use class-based selectors (more reliable)const giftId = row.find('input[name*="gifts"][name*="id"]').val();const giftName = row.find('.gift-name').val();const minCartValue = row.find('.gift-min-cart').val();const maxCartValue = row.find('.gift-max-cart').val();const maxRedemptions = row.find('.gift-redemptions').val();const thumbnailId = row.find('.gift-thumbnail-id').val();// Handle multiselectsconst productCategory = row.find('.gift-product-category').val() ?row.find('.gift-product-category').val().join(',') : '';const partnerInfo = row.find('.partnerInfo').val() ?row.find('.partnerInfo').val().join(',') : '';const fofoStoreHidden = row.find('.fofo-store-id').val() || '';const fofoStore = fofoStoreHidden + (partnerInfo ? (fofoStoreHidden ? ',' : '') + partnerInfo : '');console.log(`Gift ${index} data:`, {id: giftId,name: giftName,minCartValue,maxCartValue,maxRedemptions,productCategory,fofoStore});if (!giftName || !minCartValue || !maxCartValue || !maxRedemptions) {alert(`Gift ${index + 1} is missing required fields`);return false;}formData.gifts.push({id: giftId ? parseInt(giftId) : null,name: giftName,minCartValue: parseFloat(minCartValue),maxCartValue: parseFloat(maxCartValue),maxRedemptions: parseInt(maxRedemptions),thumbnailUrl: thumbnailId,productCategory: productCategory,fofoStore: fofoStore,partnerInfo: partnerInfo,isDefault: row.find('.default-gift-radio').is(':checked')});});// Validate main form dataif (!formData.name || !formData.startDate || !formData.endDate) {alert('Please fill in all required fields');return;}// Submit the formdoPutAjaxRequestWithJsonHandler(`${context}/store/offer/updateOffer/${parseInt(offerId)}`,JSON.stringify(formData),function (response) {console.log('Update response:', response);$('#editOfferModal').modal('hide');$('body').removeClass('modal-open');$('.modal-backdrop').remove();refreshOfferTable();alert('Offer updated successfully!');},function (error) {console.error('Update failed:', error);alert('Failed to update offer. Please try again.');});});// Update Offer Status$(document).on('change', '.switch-small input[name="isActive"]', function (e) {e.preventDefault();var $checkbox = $(this);var $switchContainer = $checkbox.closest('.switch-small');var offerId = $switchContainer.data('offer-id');var newStatus = $checkbox.is(':checked');var statusText = newStatus ? 'activate' : 'deactivate';if (!confirm('Are you sure you want to ' + statusText + ' this offer?')) {$checkbox.prop('checked', !newStatus);return;}var payload = {active: newStatus};doPutAjaxRequestWithJsonHandler(`${context}/store/offer/updateStatus/${offerId}`,JSON.stringify(payload),function (response) {alert('Offer status updated successfully!');},function (xhr, status, error) {alert('Error updating status: ' + error);$checkbox.prop('checked', !newStatus);});});// Upload fofo-store csv file$(document).on('change', '.fofo-store-file', function () {const file = this.files[0];const row = $(this).closest('.gift-row');const hiddenInput = row.find('.fofo-store-id');if (file && file.name.endsWith('.csv')) {const reader = new FileReader();reader.onload = function (e) {const text = e.target.result;const lines = text.split('\n').filter(line => line.trim() !== '');const fofoIds = [];// Skip header row (assuming first line is header)for (let i = 1; i < lines.length; i++) {const columns = lines[i].split(',');if (columns[2]) {fofoIds.push(columns[2].trim());}}hiddenInput.val(fofoIds.join(','));};reader.readAsText(file);} else {alert('Please upload a valid CSV file');hiddenInput.val('');}});function initMultiselect(selector, name) {$(selector).multiselect('destroy');$(selector).multiselect({includeSelectAllOption: true,maxHeight: 200,enableFiltering: true,nonSelectedText: 'Select ' + name,nSelectedText: name + ' selected',buttonWidth: '100%'});}