Subversion Repositories SmartDukaan

Rev

Rev 34427 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
33990 tejus.loha 1
$(document).on('click', '.mk-pur-sale-ratio-panel', function () {
34018 tejus.loha 2
    doGetAjaxRequestHandler(`${context}/pur-sale-ratio/panel`, function (response) {
33990 tejus.loha 3
        $('#main-content').html(response);
4
    });
5
});
6
 
34427 tejus.loha 7
$(document).on('change', '#purSaleStartDate, #purSaleEndDate, #purSaleBrand', function () {
34009 tejus.loha 8
    console.log("change clicked...");
33990 tejus.loha 9
    let startDate = $('input[name="startDate"]').val();
10
    let endDate = $('input[name="endDate"]').val();
34009 tejus.loha 11
    let brand = $('select[name="brand"]').val();
12
    let supplierId = $('select[name="supplier"]').val();
13
 
14
    if (!startDate) {
15
        alert("Please select start date");
16
        return;
17
    }
18
    if (!endDate) {
19
        alert("Please select end date");
20
        return;
21
    }
22
    if (!brand) {
23
        alert("Please select brand");
24
        return;
25
    }
26
 
27
    if (!supplierId) {
28
        supplierId = 0;
29
    }
36215 vikas 30
 
34018 tejus.loha 31
    doGetAjaxRequestHandler(`${context}/pur-sale-ratio/brandSuppliers?startDate=${startDate}&endDate=${endDate}&brand=${brand}&supplierId=${supplierId}`, function (response) {
34009 tejus.loha 32
        if (response.hasOwnProperty('purchaseSaleQuantities') && response.purchaseSaleQuantities.length) {
33
            createPurchaseSaleBarChart(response.purchaseSaleQuantities, startDate, endDate, brand, supplierId);
36215 vikas 34
        } else {
35
            if (salesChart) salesChart.destroy();
36
            if (catalogChart) catalogChart.destroy();
34009 tejus.loha 37
        }
36215 vikas 38
        console.log('Purchase sale ratio data fetched successfully',response);
33990 tejus.loha 39
        if (response.hasOwnProperty('brandWiseSuppliers') && response.brandWiseSuppliers.length) {
40
            $('.suppliersList').empty();
41
            $('.suppliersList').append(`<option selected disabled>Select Supplier</option>`);
34240 tejus.loha 42
            $('.suppliersList').append(`<option value="0">All Supplier</option>`);
33990 tejus.loha 43
            response.brandWiseSuppliers.forEach(function (supplier) {
44
                $('.suppliersList').append(`<option value="${supplier.supplierId}">${supplier.supplierName}</option>`);
45
            });
46
        }
47
    });
48
});
49
 
34427 tejus.loha 50
$(document).on('change', '#purSaleSupplier', function () {
33990 tejus.loha 51
    let startDate = $('input[name="startDate"]').val();
52
    let endDate = $('input[name="endDate"]').val();
53
    let brand = $('select[name="brand"]').val();
54
    let supplierId = $(this).val();
34018 tejus.loha 55
    doGetAjaxRequestHandler(`${context}/pur-sale-ratio/data?startDate=${startDate}&endDate=${endDate}&brand=${brand}&supplierId=${supplierId}`, function (response) {
33990 tejus.loha 56
        if (response.length) {
34009 tejus.loha 57
            createPurchaseSaleBarChart(response, startDate, endDate, brand, supplierId);
33990 tejus.loha 58
        }
59
    });
60
});
61
 
62
let salesChart, catalogChart;
36215 vikas 63
let currentPurchaseSaleData = [];
64
let currentCatalogData = [];
33990 tejus.loha 65
 
66
Chart.register(ChartDataLabels);
67
 
36215 vikas 68
$(document).on('click', '#exportCsvBtn', function () {
69
    exportPurchaseSaleCSV();
70
});
71
 
72
function exportPurchaseSaleCSV() {
73
    if (!currentPurchaseSaleData.length && !currentCatalogData.length) {
74
        alert('No data to export');
75
        return;
76
    }
77
 
78
    let csvContent = '';
79
 
80
    // Summary section
81
    if (currentPurchaseSaleData.length) {
82
        csvContent += 'Status,Purchase,Sale,Sale %\n';
83
        currentPurchaseSaleData.forEach(row => {
84
            let pct = row.totalQuantity > 0 ? ((row.soldQuantity / row.totalQuantity) * 100).toFixed(1) : '0.0';
85
            csvContent += `${row.status},${row.totalQuantity},${row.soldQuantity},${pct}%\n`;
86
        });
87
    }
88
 
89
    // Catalog detail section
90
    if (currentCatalogData.length) {
91
        csvContent += '\nCatalog Detail\n';
92
        csvContent += 'Model,Status,Purchase,Sale,Sale %\n';
93
        currentCatalogData.forEach(row => {
94
            let pct = row.purchase > 0 ? ((row.sale / row.purchase) * 100).toFixed(1) : '0.0';
95
            csvContent += `${row.model},${row.status},${row.purchase},${row.sale},${pct}%\n`;
96
        });
97
    }
98
 
99
    let startDate = $('input[name="startDate"]').val();
100
    let endDate = $('input[name="endDate"]').val();
101
    let brand = $('select[name="brand"]').val() || '';
102
    let fileName = `purchase_sale_ratio_${brand}_${startDate}_to_${endDate}.csv`;
103
 
104
    let blob = new Blob([csvContent], {type: 'text/csv;charset=utf-8;'});
105
    let link = document.createElement('a');
106
    link.href = URL.createObjectURL(blob);
107
    link.download = fileName;
108
    link.click();
109
    URL.revokeObjectURL(link.href);
110
}
111
 
33990 tejus.loha 112
function createPurchaseSaleBarChart(response, startDate, endDate, brand, supplierId) {
113
    response = arrangeLabelsOrder(response);
36215 vikas 114
    currentPurchaseSaleData = response;
115
    currentCatalogData = [];
116
    $('#exportCsvBtn').hide();
33990 tejus.loha 117
    let labels = [], totalQuantities = [], soldQuantities = [];
118
    labels = response.map(sale => sale.status);
119
    totalQuantities = response.map(sale => sale.totalQuantity);
120
    soldQuantities = response.map(sale => sale.soldQuantity);
121
    const ctx = document.getElementById('salesChart').getContext('2d');
122
 
123
    //destroy salesChart data if available
124
    if (salesChart) {
125
        salesChart.destroy();
126
    }
127
    if (catalogChart) {
128
        catalogChart.destroy();
129
    }
130
    const percentageData = soldQuantities.map((sale, i) => ((sale / totalQuantities[i]) * 100).toFixed(1));
131
    // Chart.js configuration
132
    salesChart = new Chart(ctx, {
133
        type: 'bar',
134
        data: {
135
            labels: labels, // Labels for each bar
136
            datasets: [
137
                {
138
                    label: 'Purchase',
139
                    data: totalQuantities,
140
                    backgroundColor: 'rgba(255, 99, 132, 0.6)', // Red bars
141
                    borderColor: 'rgba(255, 99, 132, 1)',
142
                    borderWidth: 1
143
                },
144
                {
145
                    label: 'Sale',
146
                    data: soldQuantities,
147
                    backgroundColor: 'rgba(144, 238, 144, 0.6)', // Green bars
148
                    borderColor: 'rgba(144, 238, 144, 1)',
149
                    borderWidth: 1
150
                }
151
            ]
152
        },
153
        options: {
154
            responsive: true,
155
            plugins: {
156
                tooltip: {
157
                    enabled: false,
158
                },
159
                legend: {
160
                    position: 'top',
161
                },
162
                datalabels: {
163
                    display: true,
164
                    color: 'black',
165
                    font: {
166
                        size: 12,
167
                    },
168
                    formatter: function (value, context) {
169
                        const index = context.dataIndex;
170
                        const purchase = totalQuantities[index];
171
                        const sale = soldQuantities[index];
172
                        const percentage = percentageData[index];
173
 
174
                        if (context.dataset.label === 'Purchase') {
175
                            return `${purchase}`;
176
                        } else {
177
                            return `${sale} (${percentage}%)`;
178
                        }
179
 
180
                    },
181
                    align: 'end', // Place labels at the center of the bars
182
                    anchor: 'center', // Align labels to the center of each bar pair
183
                    offset: 5, // Adjust positioning for better visibility if needed
184
                },
185
            }, onClick: function (event, activeElements) {
186
                if (activeElements.length > 0) {
187
                    const element = activeElements[0]; // Get the clicked element
188
                    const datasetIndex = element.datasetIndex; // Get the dataset (Sale or Purchase)
189
                    const dataIndex = element.index; // Get the index of the clicked bar
190
                    const label = this.data.labels[dataIndex]; // Get the label for the clicked bar
191
                    const value = this.data.datasets[datasetIndex].data[dataIndex]; // Get the value of the clicked bar
192
                    // Show an alert with the label and value
193
                    catalogPurchaseSaleChart(startDate, endDate, brand, supplierId, label);
194
                }
195
            },
196
            indexAxis: 'y',
197
            scales: {
198
                x: {
199
                    beginAtZero: true,
200
                    title: {
201
                        display: true,
202
                        text: 'Quantity',
203
                        color: '#000000'
204
                    }
205
                },
206
                y: {
207
                    title: {
208
                        display: true,
209
                        text: 'Status',
210
                        color: '#000000'
211
                    }
212
                }
213
            }
214
        }
215
    });
216
 
217
}
218
 
219
function catalogPurchaseSaleChart(startDate, endDate, brand, supplierId, label) {
34018 tejus.loha 220
    doGetAjaxRequestHandler(`${context}/pur-sale-ratio/catalog-quantity?startDate=${startDate}&endDate=${endDate}&brand=${brand}&supplierId=${supplierId}&label=${label}`, function (response) {
34230 tejus.loha 221
        console.log("response to check status - ",response);
34018 tejus.loha 222
        createCatalogPurchaseSaleBarChart(response, startDate, endDate, supplierId);
33990 tejus.loha 223
    });
224
}
225
 
34230 tejus.loha 226
function getCatalogAgeDetail(startDate, endDate, supplierId, label,status) {
34018 tejus.loha 227
    // /catalog-age-detail
228
    let modelNumber = label;
34230 tejus.loha 229
    doGetAjaxRequestHandler(`${context}/pur-sale-ratio/catalog-age-detail?startDate=${startDate}&endDate=${endDate}&modelNumber=${modelNumber}&supplierId=${supplierId}&status=${status}`, function (response) {
34018 tejus.loha 230
        $('#catalog-age-div #catalogModalBody').html(response);
231
        $('#catalog-age-div').modal('show');
232
    });
233
}
234
 
235
function createCatalogPurchaseSaleBarChart(response, startDate, endDate, supplierId) {
33990 tejus.loha 236
    let labels = [], totalQuantities = [], soldQuantities = [];
34230 tejus.loha 237
 
33990 tejus.loha 238
    let filterResponse = response.filter(res => res.sale !== res.purchase);
36215 vikas 239
    currentCatalogData = filterResponse;
240
    $('#exportCsvBtn').show();
34230 tejus.loha 241
 
33990 tejus.loha 242
    labels = filterResponse.map(sale => sale.model);
243
    totalQuantities = filterResponse.map(sale => sale.purchase);
244
    soldQuantities = filterResponse.map(sale => sale.sale);
34230 tejus.loha 245
    let status = filterResponse.map(sale => sale.status)[0];
246
    let charContainer = document.getElementById('chartContainer');
33990 tejus.loha 247
 
248
    //destroy old Catalog Chart Container
249
    $('#catalogChartContainer').remove();
34230 tejus.loha 250
 
33990 tejus.loha 251
    //create new Catalog Chart Container
252
    let newCatalogChartContainer = document.createElement('div');
253
    newCatalogChartContainer.id = 'catalogChartContainer';
254
    newCatalogChartContainer.classList.add('col-md-6');
255
 
256
    let canvas = document.createElement('canvas');
257
 
258
    let catalogChartHeight;
259
    switch (labels.length) {
260
        case 1:
261
            catalogChartHeight = 150;
262
            break;
263
        case 2:
264
            catalogChartHeight = 200;
265
            break;
266
        case 3:
267
            catalogChartHeight = 250;
268
            break;
269
        case 4:
270
            catalogChartHeight = 250;
271
            break;
272
        default:
273
            catalogChartHeight = labels.length * 2 * 25;
274
            break;
275
    }
276
    newCatalogChartContainer.style.height = catalogChartHeight + 'px';
277
    const ctx = canvas.getContext('2d');
278
 
279
    //destroy catalogChart data if available
280
    if (catalogChart) {
281
        catalogChart.destroy();
282
    }
283
 
284
    const percentageData = soldQuantities.map((sale, i) => ((sale / totalQuantities[i]) * 100).toFixed(1));
285
 
286
    // Chart.js configuration
287
    //Chart.register(ChartDataLabels);
288
    catalogChart = new Chart(ctx, {
289
        type: 'bar',
290
        data: {
291
            labels: labels, // Labels for each bar
292
            datasets: [
293
                {
294
                    label: 'Purchase',
295
                    data: totalQuantities,
296
                    backgroundColor: 'rgba(255, 99, 132, 0.6)', // Red bars
297
                    borderColor: 'rgba(255, 99, 132, 1)',
298
                    borderWidth: 1
299
 
300
                },
301
                {
302
                    label: 'Sale',
303
                    data: soldQuantities,
304
                    backgroundColor: 'rgba(144, 238, 144, 0.6)', // Green bars
305
                    borderColor: 'rgba(144, 238, 144, 1)',
306
                    borderWidth: 1,
307
 
308
 
309
                }
310
            ]
311
        },
312
        options: {
313
            responsive: true,
314
            maintainAspectRatio: false,
315
            plugins: {
316
                tooltip: {
317
                    enabled: false,
318
                },
319
                legend: {
320
                    position: 'top',
321
                },
322
                datalabels: {
323
                    display: true,
324
                    color: 'black',
325
                    font: {
326
                        size: 12,
327
                    },
328
                    formatter: function (value, context) {
329
                        const index = context.dataIndex;
330
                        const purchase = totalQuantities[index];
331
                        const sale = soldQuantities[index];
332
                        const percentage = percentageData[index];
333
 
334
                        if (context.dataset.label === 'Purchase') {
335
                            return `${purchase}`;
336
                        } else {
337
                            return `${sale} (${percentage}%)`;
338
                        }
339
 
340
                    },
341
                    align: 'end', // Place labels at the center of the bars
342
                    anchor: 'center', // Align labels to the center of each bar pair
343
                    offset: 5, // Adjust positioning for better visibility if needed
344
                },
34018 tejus.loha 345
            }, onClick: function (event, activeElements) {
346
                if (activeElements.length > 0) {
347
                    const element = activeElements[0]; // Get the clicked element
348
                    const datasetIndex = element.datasetIndex; // Get the dataset (Sale or Purchase)
349
                    const dataIndex = element.index; // Get the index of the clicked bar
34230 tejus.loha 350
                    const modelNumber = this.data.labels[dataIndex]; // Get the label for the clicked bar that is modelNumber this time
34018 tejus.loha 351
                    const value = this.data.datasets[datasetIndex].data[dataIndex]; // Get the value of the clicked bar
34230 tejus.loha 352
                    getCatalogAgeDetail(startDate, endDate, supplierId, modelNumber,status);
34018 tejus.loha 353
                }
33990 tejus.loha 354
            },
355
            indexAxis: 'y',
356
            scales: {
357
                x: {
358
                    beginAtZero: true,
359
                    title: {
360
                        display: true,
361
                        text: 'Quantity',
362
                        color: '#000000'
363
                    }
364
                },
365
                y: {
366
                    title: {
367
                        display: true,
368
                        text: 'Models',
369
                        color: '#000000'
370
                    }
371
                }
372
            }
373
        }
374
    });
375
    newCatalogChartContainer.appendChild(canvas);
376
    charContainer.appendChild(newCatalogChartContainer);
377
 
378
}
379
 
380
function arrangeLabelsOrder(responseData) {
381
    const requiredOrder = ['HID', 'FASTMOVING', 'SLOWMOVING', 'OTHER'];
382
    const orderMap = {};
383
    requiredOrder.forEach((label, index) => {
384
        orderMap[label] = index;
385
    });
386
    const sortedResponse = responseData.sort((a, b) => {
387
        const indexA = orderMap[a.status] !== undefined ? orderMap[a.status] : Infinity;
388
        const indexB = orderMap[b.status] !== undefined ? orderMap[b.status] : Infinity;
389
        return indexA - indexB;
390
    });
391
    return sortedResponse;
392
}