Subversion Repositories SmartDukaan

Rev

Rev 28493 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

// Sellers & Warehouses screen. The server re-checks every rule (WarehouseSetupValidator); these checks only save a
// round trip. A refused request comes back as a 400 whose text the ajax helpers show as is.
var SellerSetup = (function () {

    var GSTIN = /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z][0-9A-Z]Z[0-9A-Z]$/;

    function loadPage() {
        doGetAjaxRequestHandler(context + "/getAllSeller", function (response) {
            $('#main-content').html(response);
        });
    }

    function loadSeller(sellerId) {
        doGetAjaxRequestHandler(context + "/getSellerWareHouse?sellerId=" + sellerId, function (response) {
            $('.seller-setup .warehouse-container').html(response);
        });
    }

    function currentSellerId() {
        return $('.seller-warehouses').data('seller-id');
    }

    // A page or panel reload replaces the modal's markup, so wait until it has closed and its backdrop is gone.
    function closeThen(modalSelector, next) {
        $(modalSelector).one('hidden.bs.modal', next).modal('hide');
    }

    function value(selector) {
        return $.trim($(selector).val() || '');
    }

    function postJson(url, payload, onSuccess) {
        doPostAjaxRequestWithJsonHandler(url, JSON.stringify(payload), onSuccess);
    }

    // Same split as WarehouseAddressMaster.getCustomAddress(): the last comma segment is the city, the rest is
    // divided between two lines.
    function invoiceLines(address, city) {
        var parts = address.split(',').map(function (part) {
            return $.trim(part);
        }).filter(function (part) {
            return part.length > 0;
        });
        var midpoint = Math.floor(parts.length / 2);
        return {
            line1: parts.slice(0, midpoint).join(', '),
            line2: parts.slice(midpoint).join(', '),
            city: city
        };
    }

    function renderAddressPreview() {
        var address = value('#new-address-address');
        var city = value('#new-address-city');
        if (!address || !city) {
            $('#new-address-preview').text('-');
            return;
        }
        var lines = invoiceLines(address, city);
        var state = $('#new-address-state option:selected').val() ? $('#new-address-state option:selected').text() : '';
        var preview = $('<div>');
        [lines.line1, lines.line2, lines.city + ' - ' + value('#new-address-pin'), state].forEach(function (line) {
            if (line) {
                preview.append($('<div>').text(line));
            }
        });
        $('#new-address-preview').empty().append(preview.children());
    }

    function createAddress() {
        var payload = {
            address: value('#new-address-address'),
            city: value('#new-address-city'),
            pin: value('#new-address-pin'),
            stateId: parseInt($('#new-address-state').val(), 10),
            contactPerson: value('#new-address-contact-person'),
            contactNumber: value('#new-address-contact-number')
        };
        if (!payload.address || !payload.city) {
            alert('Address and city are required');
            return;
        }
        if (payload.city.indexOf(',') >= 0) {
            alert('City must not contain a comma');
            return;
        }
        if (!/^\d{6}$/.test(payload.pin)) {
            alert('Pin must be 6 digits');
            return;
        }
        if (!payload.stateId && payload.stateId !== 0) {
            alert('Select a state');
            return;
        }
        if (!payload.contactPerson) {
            alert('Contact person is required');
            return;
        }
        if (!/^\d{10,15}$/.test(payload.contactNumber)) {
            alert('Contact number must be 10 to 15 digits');
            return;
        }
        postJson(context + '/createNewAddress', payload, function (response) {
            closeThen('#new-address-modal', loadPage);
        });
    }

    function renderGstinHint() {
        var gstin = value('#new-seller-gstin').toUpperCase();
        if (!gstin) {
            $('#new-seller-gstin-hint').text('State and PAN are read from the GSTIN.');
        } else if (GSTIN.test(gstin)) {
            $('#new-seller-gstin-hint').text('State code ' + gstin.substring(0, 2) + ' ยท PAN ' + gstin.substring(2, 12));
        } else {
            $('#new-seller-gstin-hint').text('Not a valid GSTIN yet');
        }
    }

    function createSeller() {
        var payload = {
            label: value('#new-seller-label'),
            gstin: value('#new-seller-gstin').toUpperCase(),
            address: value('#new-seller-address')
        };
        if (!payload.label || !payload.address) {
            alert('Label and registered address are required');
            return;
        }
        if (!GSTIN.test(payload.gstin)) {
            alert('GSTIN is not in the format the GST portal issues');
            return;
        }
        postJson(context + '/createNewSeller', payload, function () {
            closeThen('#new-seller-modal', loadPage);
        });
    }

    function createWarehouse() {
        var sellerId = currentSellerId();
        var payload = {
            sellerId: sellerId,
            name: value('#new-warehouse-name'),
            prefix: value('#new-warehouse-prefix').toUpperCase(),
            addressId: parseInt($('#new-warehouse-address').val(), 10)
        };
        if (!payload.name) {
            alert('Warehouse name is required');
            return;
        }
        if (!/^[A-Z]{2,7}$/.test(payload.prefix)) {
            alert('Branch code must be 2 to 7 letters, no digits or symbols');
            return;
        }
        if (!payload.addressId) {
            alert('Select an address');
            return;
        }
        if (!confirm('Create warehouse ' + payload.name + ' with branch code ' + payload.prefix + '?')) {
            return;
        }
        postJson(context + '/createNewWarehouse', payload, function () {
            closeThen('#new-warehouse-modal', function () {
                loadSeller(sellerId);
            });
        });
    }

    function toggleWarehouse(button) {
        var warehouseId = button.data('warehouse-id');
        var activate = String(button.data('active')) !== 'true';
        if (!activate && !confirm('Deactivate warehouse ' + warehouseId + '? It stops being offered as an active'
            + ' physical warehouse. Stock, billing and history are not touched.')) {
            return;
        }
        var sellerId = currentSellerId();
        doPostAjaxRequestHandler(context + '/physicalWarehouse/' + warehouseId + '/active?active=' + activate,
            function () {
                loadSeller(sellerId);
            });
    }

    function remapAddress() {
        var sellerId = currentSellerId();
        var warehouseId = $('#remap-address-modal').data('warehouse-id');
        var addressId = parseInt($('#remap-address').val(), 10);
        if (!addressId) {
            alert('Select an address');
            return;
        }
        if (!confirm('Change the address of warehouse ' + warehouseId + ' to #' + addressId
            + '? Its internal stores move to it as well.')) {
            return;
        }
        doPostAjaxRequestHandler(context + '/physicalWarehouse/' + warehouseId + '/address?addressId=' + addressId,
            function () {
                closeThen('#remap-address-modal', function () {
                    loadSeller(sellerId);
                });
            });
    }

    function toggleAddress(button) {
        var addressId = button.data('address-id');
        var activate = String(button.data('active')) !== 'true';
        if (!activate && !confirm('Deactivate address #' + addressId + '? It will no longer be offered for new'
            + ' warehouses. Warehouses already on it keep printing it.')) {
            return;
        }
        doPostAjaxRequestHandler(context + '/warehouseAddress/' + addressId + '/active?active=' + activate, loadPage);
    }

    return {
        loadPage: loadPage,
        loadSeller: loadSeller,
        renderAddressPreview: renderAddressPreview,
        renderGstinHint: renderGstinHint,
        createAddress: createAddress,
        createSeller: createSeller,
        createWarehouse: createWarehouse,
        toggleWarehouse: toggleWarehouse,
        remapAddress: remapAddress,
        toggleAddress: toggleAddress
    };
})();

$(document).on('click', '.seller-index', function () {
    SellerSetup.loadPage();
});
$(document).on('click', '.seller-setup .seller-open', function () {
    SellerSetup.loadSeller($(this).data('seller-id'));
});
$(document).on('input change', '.seller-setup .address-preview-source', function () {
    SellerSetup.renderAddressPreview();
});
$(document).on('input', '#new-seller-gstin', function () {
    SellerSetup.renderGstinHint();
});
$(document).on('click', '#new-address-submit', function () {
    SellerSetup.createAddress();
});
$(document).on('click', '#new-seller-submit', function () {
    SellerSetup.createSeller();
});
$(document).on('click', '#new-warehouse-submit', function () {
    SellerSetup.createWarehouse();
});
$(document).on('click', '.seller-setup .warehouse-active-toggle', function () {
    SellerSetup.toggleWarehouse($(this));
});
$(document).on('click', '.seller-setup .address-active-toggle', function () {
    SellerSetup.toggleAddress($(this));
});
$(document).on('click', '.seller-setup .warehouse-remap-open', function () {
    var button = $(this);
    $('#remap-warehouse-id').text(button.data('warehouse-id'));
    $('#remap-address').val(String(button.data('address-id') || ''));
    $('#remap-address-modal').data('warehouse-id', button.data('warehouse-id')).modal('show');
});
$(document).on('click', '#remap-address-submit', function () {
    SellerSetup.remapAddress();
});