Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

// Sidebar menu click handlers
$(document).on('click', '.wod-request-panel', function () {
    doGetAjaxRequestHandler(context + '/wod-request-panel', function (response) {
        $('#main-content').html(response);
        initFinServicePanel();
    });
});

$(document).on('click', '.wod-request-list', function () {
    doGetAjaxRequestHandler(context + '/wod-request-list', function (response) {
        $('#main-content').html(response);
    });
});

// Template Admin handlers
$(document).on('click', '.wod-template-admin', function () {
    doGetAjaxRequestHandler(context + '/wod-template-admin', function (response) {
        $('#main-content').html(response);
    });
});

$(document).on('click', '.wod-template-new', function () {
    doGetAjaxRequestHandler(context + '/wod-template/edit?id=0', function (response) {
        $('#main-content').html(response);
    });
});

$(document).on('click', '.wod-template-edit', function () {
    var id = $(this).data('id');
    doGetAjaxRequestHandler(context + '/wod-template/edit?id=' + id, function (response) {
        $('#main-content').html(response);
    });
});

$(document).on('click', '.wod-template-delete', function () {
    var id = $(this).data('id');
    if (!confirm('Are you sure you want to deactivate this template?')) return;
    $.post(context + '/wod-template/delete', {id: id}, function (resp) {
        var result = resp;
        try {
            if (typeof resp === 'string') result = JSON.parse(resp);
        } catch (e) {
        }
        if (result && result.success) {
            doGetAjaxRequestHandler(context + '/wod-template-admin', function (response) {
                $('#main-content').html(response);
            });
        }
    });
});

var finServiceTemplateId = null;
var finServiceFormData = null;

function initFinServicePanel() {
    $('#partnerSelect').select2({
        placeholder: '-- Search Partner --',
        allowClear: true,
        width: '100%'
    });
}

// Partner selected -> enable brand, reset downstream
$(document).on('change', '#partnerSelect', function () {
    finServiceTemplateId = null;
    if ($(this).val()) {
        $('#brandSelect').prop('disabled', false);
    } else {
        $('#brandSelect').prop('disabled', true).val('');
        $('#stateSelect').prop('disabled', true).html('<option value="">-- Select State --</option>');
        $('#distributorSelect').prop('disabled', true).val('');
        $('#loadFormBtn').prop('disabled', true);
        $('#dynamicFormContainer').hide();
    }
});

// Brand selected -> fetch states
$(document).on('change', '#brandSelect', function () {
    var brand = $(this).val();
    finServiceTemplateId = null;
    if (!brand) {
        $('#stateSelect').prop('disabled', true).html('<option value="">-- Select State --</option>');
        $('#distributorSelect').prop('disabled', true).val('');
        $('#loadFormBtn').prop('disabled', true);
        return;
    }
    doGetAjaxRequestHandler(context + '/wod-request/templates?brand=' + encodeURIComponent(brand), function (response) {
        var templates = typeof response === 'string' ? JSON.parse(response) : response;
        var html = '<option value="">-- Select State --</option>';
        templates.forEach(function (t) {
            html += '<option value="' + t.id + '">' + t.state + '</option>';
        });
        $('#stateSelect').html(html).prop('disabled', false);
    });
});

// State selected -> enable distributor dropdown
$(document).on('change', '#stateSelect', function () {
    finServiceTemplateId = $(this).val();
    if (finServiceTemplateId) {
        $('#distributorSelect').prop('disabled', false);
    } else {
        $('#distributorSelect').prop('disabled', true).val('');
        $('#loadFormBtn').prop('disabled', true);
    }
});

// Distributor selected -> enable load button
$(document).on('change', '#distributorSelect', function () {
    var val = $(this).val();
    $('#loadFormBtn').prop('disabled', !val || !finServiceTemplateId);
});

// Load form with error handling
$(document).on('click', '#loadFormBtn', function () {
    var fofoId = $('#partnerSelect').val();
    var distType = $('#distributorSelect').val();
    if (!fofoId || !finServiceTemplateId || !distType) {
        alert('Please select Partner, Brand, State and Distributor type');
        return;
    }
    var btn = $(this);
    btn.prop('disabled', true).text('Loading...');

    $.ajax({
        url: context + '/wod-request/form?templateId=' + finServiceTemplateId + '&fofoId=' + fofoId,
        type: 'GET',
        success: function (response) {
            var resp = typeof response === 'string' ? JSON.parse(response) : response;
            finServiceFormData = resp;
            renderFinServiceForm(resp, distType);
            btn.prop('disabled', false).text('Load Form');
        },
        error: function () {
            alert('Failed to load form. Please try again.');
            btn.prop('disabled', false).text('Load Form');
        }
    });
});

function renderFinServiceForm(resp, distType) {
    var columns = resp.columns;
    var prefill = resp.prefillValues;
    var existingDocs = resp.existingDocs || {};
    $('#templateId').val(resp.templateId);
    $('#fofoId').val(resp.fofoId);
    $('#distributorType').val(distType);

    var distLabel = distType === 'yes' ? 'Working with Distributor' : 'Non-Distributor / New Partner';
    $('#formTitle').text('WOD Request: ' + resp.brand + ' - ' + resp.state +
        ' | ' + resp.storeName + ' (' + resp.storeCode + ') | ' + distLabel);

    var html = '';
    columns.sort(function (a, b) {
        return (a.order || 0) - (b.order || 0);
    });

    columns.forEach(function (col) {
        var condition = col.condition || 'always';
        if (condition === 'distributor' && distType !== 'yes') return;
        if (condition === 'non_distributor' && distType !== 'no') return;

        var val = prefill[col.key] || '';
        var required = col.required ? 'required' : '';
        var reqStar = col.required ? ' <span style="color:red;">*</span>' : '';

        html += '<div class="col-md-4 fin-form-field" style="margin-bottom:12px;">';
        html += '<label>' + col.label + reqStar + '</label>';

        if (col.type === 'file') {
            var existingDocId = existingDocs[col.key];
            if (existingDocId) {
                html += '<input type="hidden" class="fin-doc-id" data-key="' + col.key + '" value="' + existingDocId + '">';
                html += '<div style="margin-bottom:4px;">';
                html += '<span class="label label-success"><i class="fa fa-check"></i> Already Uploaded</span> ';
                html += '<a href="' + context + '/open-attachment?documentId=' + existingDocId + '" target="_blank" class="btn btn-xs btn-info">View</a>';
                html += '</div>';
                html += '<input type="file" class="form-control fin-doc-upload" data-key="' + col.key + '">';
                html += '<small class="fin-upload-status" data-key="' + col.key + '" style="color:green;">Using existing. Upload new to replace.</small>';
            } else {
                html += '<input type="file" class="form-control fin-doc-upload" data-key="' + col.key + '" ' + required + '>';
                html += '<input type="hidden" class="fin-doc-id" data-key="' + col.key + '">';
                html += '<small class="fin-upload-status" data-key="' + col.key + '"></small>';
            }
        } else if (col.type === 'textarea') {
            html += '<textarea class="form-control fin-field" data-key="' + col.key + '" rows="3" ' + required + '>' + finEscapeHtml(val) + '</textarea>';
        } else {
            html += '<input type="' + (col.type || 'text') + '" class="form-control fin-field" data-key="' + col.key + '" value="' + finEscapeAttr(val) + '" ' + required + '>';
        }
        html += '</div>';
    });

    $('#formFieldsContainer').html(html);
    $('#dynamicFormContainer').show();
}

// File upload using same pattern as existing codebase (doAjaxUploadRequestHandler)
$(document).on('change', '.fin-doc-upload', function () {
    var input = this;
    var key = $(input).data('key');
    if (!input.files || !input.files[0]) return;

    var statusEl = $('small.fin-upload-status[data-key="' + key + '"]');
    statusEl.text('Uploading...').css('color', 'orange');

    doAjaxUploadRequestHandler(
        context + '/document-upload',
        'POST',
        input.files[0],
        function (response) {
            var docId = null;
            if (response && response.response && response.response.document_id) {
                docId = response.response.document_id;
            } else if (response && response.document_id) {
                docId = response.document_id;
            }
            if (docId) {
                $('input.fin-doc-id[data-key="' + key + '"]').val(docId);
                statusEl.text('Uploaded').css('color', 'green');
            } else {
                var msg = (response && response.response && response.response.message) || 'Unknown error';
                statusEl.text('Upload failed: ' + msg).css('color', 'red');
            }
        }
    );
});

// Form submit via button click (not form submit event — avoids page navigation)
$(document).on('click', '#submitBtn', function (e) {
    e.preventDefault();
    e.stopPropagation();

    // Validate required fields
    var missingFields = [];
    $('#formFieldsContainer .fin-field[required]').each(function () {
        if (!$(this).val() || !$(this).val().trim()) {
            var label = $(this).closest('.fin-form-field').find('label').text().replace(' *', '').trim();
            missingFields.push(label);
            $(this).css('border-color', 'red');
        } else {
            $(this).css('border-color', '');
        }
    });

    // Validate required file uploads
    $('#formFieldsContainer .fin-doc-upload[required]').each(function () {
        var key = $(this).data('key');
        var docId = $('input.fin-doc-id[data-key="' + key + '"]').val();
        if (!docId) {
            var label = $(this).closest('.fin-form-field').find('label').text().replace(' *', '').trim();
            missingFields.push(label);
            $(this).css('border-color', 'red');
        } else {
            $(this).css('border-color', '');
        }
    });

    if (missingFields.length > 0) {
        alert('Please fill the following required fields:\n\n- ' + missingFields.join('\n- '));
        return false;
    }

    var formData = {};
    $('#formFieldsContainer .fin-field').each(function () {
        formData[$(this).data('key')] = $(this).val();
    });
    formData['distributor_type'] = $('#distributorType').val();

    var docTypes = [];
    var docIds = [];
    $('#formFieldsContainer .fin-doc-id').each(function () {
        if ($(this).val()) {
            docTypes.push($(this).data('key'));
            docIds.push(parseInt($(this).val()));
        }
    });

    if (!confirm('Are you sure you want to submit this WOD request?')) {
        return false;
    }

    $('#submitBtn').prop('disabled', true).text('Submitting...');

    $.ajax({
        url: context + '/wod-request/submit',
        type: 'POST',
        data: {
            templateId: $('#templateId').val(),
            fofoId: $('#fofoId').val(),
            formData: JSON.stringify(formData),
            docTypes: JSON.stringify(docTypes),
            docIds: JSON.stringify(docIds)
        },
        success: function (resp) {
            var result = resp;
            try {
                if (typeof resp === 'string') result = JSON.parse(resp);
            } catch (e) {
            }

            // response.vm returns the JSON string directly
            var parsed = result;
            if (typeof result === 'string') {
                try {
                    parsed = JSON.parse(result);
                } catch (e) {
                }
            }

            if (parsed && parsed.success) {
                alert('WOD request submitted successfully! Request ID: ' + parsed.requestId);
                doGetAjaxRequestHandler(context + '/wod-request-list', function (response) {
                    $('#main-content').html(response);
                });
            } else {
                alert('Submission failed: ' + (parsed.error || 'Unknown error'));
                $('#submitBtn').prop('disabled', false).html('<i class="fa fa-paper-plane"></i> Submit WOD Request');
            }
        },
        error: function (xhr) {
            alert('Submission failed. Server error.');
            $('#submitBtn').prop('disabled', false).html('<i class="fa fa-paper-plane"></i> Submit WOD Request');
        }
    });

    return false;
});

function finEscapeHtml(str) {
    if (!str) return '';
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function finEscapeAttr(str) {
    if (!str) return '';
    return String(str).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}