Subversion Repositories SmartDukaan

Rev

Rev 33973 | Blame | Compare with Previous | Last modification | View Log | RSS feed


function initializeSelect(selector, type='catalogs') {
    if (type === 'catalogs') {
        $(selector).multiselect({
            includeSelectAllOption: false,
            multiple: false,
            maxHeight: 200,
            buttonWidth: '100%',
            numberDisplayed: 1,
            nonSelectedText: '-- Select One --',
            nSelectedText: ' - Selected',
            enableFiltering: true,
            enableCaseInsensitiveFiltering: true
        });
    } else {
        $(selector).select2({
            placeholder: "Select or add new",
            tags: true,
            createTag: params => ({ id: params.term, text: params.term, newOption: true }),
            templateResult: data => data.newOption ? $('<span class="new-option">Add: ' + data.text + '</span>') : data.text,
        });
    }
}

function validateRequiredFields(fields) {
    let isValid = true;
    fields.each(function () {
        if (!$(this).val()) {
            isValid = false;
            $(this).addClass('is-invalid');
        } else {
            $(this).removeClass('is-invalid');
        }
    });
    return isValid;
}

function loadCatalogOptions(brandId, targetElement, type = 'catalogs') {
    $.get(`/super-catalog/brand/${brandId}`, function (response) {
        let options = `<option value="">-- Select --</option>`;
        if (type === 'catalogs'){
            response.catalogs.forEach(row => { options += `<option value="${row.id}">${row.description}</option>`; });
        } else {
            response.superCatalogs.forEach(row => { options += `<option value="${row.id}">${row.superCatalogName}</option>`; });
        }
        $(targetElement).html(options);
        initializeSelect(targetElement, type);
    }).fail(() => {
        alert("Error: Unable to load catalogs for the selected brand.");
    });
}

$(document).on('click', ".super-catalog-list", function () {

    const freshTr = `
            <tr>
                <td>
                    <div class="form-group">
                        <select id="catalog_id" class="form-control"></select>
                    </div>
                </td>
                <td>
                    <div class="form-group">
                        <input id="variant_name" class="form-control" placeholder="Variant Name">
                        <input id="mapping_id" type="hidden" value="0">
                    </div>
                </td>
                <td>
                    <button class="btn btn-danger removeExisting"><i class="fa fa-minus"></i></button>
                </td>
            </tr>`;

    doGetAjaxRequestHandler(context + "/super-catalog",
        (response) => {
            $('#main-content').html(response);

            // Initialize multiSelect
            initializeSelect('#brand_id');

            // Add new catalog mapping row
            $('#manageSuperCatalogModal').on('click', '.addNew', function () {
                const brandId = $('#brand_id').val();
                if (brandId) {
                    $('#catalogMappingTable tbody').append(freshTr);
                    const lastRow = $('#catalogMappingTable tbody tr:last');
                    loadCatalogOptions(brandId, lastRow.find('#catalog_id'));
                } else {
                    alert("Please select a brand first.");
                }
            });

            // Remove catalog mapping row
            $('#manageSuperCatalogModal').on('click', '.removeExisting', function () {
                if (confirm("Are you sure you want to remove this row?")) {
                    $(this).closest('tr').remove();
                }
            });

            // Save super catalog
            $('.save_super_model').on('click', function () {
                const requiredFields = $('#brand_id, #super_catalog_name');
                if (!validateRequiredFields(requiredFields)) {
                    alert('Please fill all required fields.');
                    return;
                }
                alert('Super Catalog saved successfully!');
            });

            $('#super-catalog').on('click', '.view-super-catalog', function (ev) {
                ev.preventDefault();
                let superCatalogId = $(this).parent().parent('tr').data('id');
                doGetAjaxRequestHandler(context + "/super-catalog/"+superCatalogId,(response) => {
                    $('#manageSuperCatalogModalBody').empty();
                    $('#manageSuperCatalogModalBody').html(response);
                    initializeSelect('.selectOrCreate', 'superCatalog');
                    initializeSelect('#catalog_id, #brand_id');
                    $('#manageSuperCatalogModal').modal('show');
                });
            });

            // Initialize DataTable
            $('#super-catalog').DataTable();

        });
});

$(document).on('click', ".save_super_model", function () {
    let mappingArr = [];
    $('#catalogMapping').find('tr').each(function () {
        const catalogId = $(this).find('select#catalog_id').val();
        const variantName = $(this).find('input#variant_name').val();
        const mappingId = $(this).find('input#mapping_id').val();
        if (catalogId > 0) {
            mappingArr.push({
                catalogId: catalogId,
                variantName: variantName,
                superCatalogId: parseInt($('#super_catalog_name').val()) || null,
                id: mappingId
            })
        }
    });
    const params = {
        id: mappingArr.length ? mappingArr[0].id : 0,
        brandId: parseInt($('#brand_id').val()),
        mappingArr: mappingArr,
        superCatalogName: parseInt($('#super_catalog_name').val()) || $('#super_catalog_name').val(),
    };
    console.log('params',params);
    if (!params.brandId || mappingArr.length === 0 || !params.superCatalogName){
        alert("Please fill all details"); return;
    }
    doAjaxRequestWithJsonHandler(context + "/super-catalog", "POST", JSON.stringify(params), (response) => {
        if (response) {
            $('.super-catalog-list').trigger('click');
            $('#manageSuperCatalogModal').modal('hide');
            alert("Saved successfully");
        } else {
            alert("Something went wrong!");
        }
    });
});

$(document).on('click', ".delete-super-catalog-mapping", function() {
    const id = parseInt($(this).closest('td').data('id')) || 0;
    console.log("id",id);
    if (confirm("Are you sure you want to delete this record")) {
        if (id > 0) {
            doDeleteAjaxRequestHandler(context + "/super-catalog/" + id, (response) => {
                if (response) {
                    $(this).parent('td').closest('tr').remove();
                    $('.super-catalog-list').trigger('click');
                    alert("Deleted successfully");
                } else {
                    alert("Something went wrong!");
                }
            });
        } else {
            $(this).parent('td').closest('tr').remove();
        }
    }
});


$(document).on('change', "#brand_id", function() {
    loadCatalogOptions($(this).val(), 'select#super_catalog_name', 'superCatalogs');
});