Lorky

A opti (terrible code)

Apr 20th, 2024
1,167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 12.35 KB | Source Code | 0 0
  1. "use strict";
  2. const ExcelJS = require("exceljs");
  3.  
  4. module.exports = ({ strapi }) => ({
  5.   async getDropDownData() {
  6.     let excel = strapi.config.get("excel");
  7.     let dropDownValues = [];
  8.     let array = Object.keys(excel?.config);
  9.  
  10.     strapi?.db?.config?.models?.forEach((element) => {
  11.       if (element?.kind == "collectionType") {
  12.         array?.forEach((data) => {
  13.           if (element?.uid?.startsWith(data)) {
  14.             dropDownValues.push({
  15.               label: element?.info?.displayName,
  16.               value: element?.uid,
  17.             });
  18.           }
  19.         });
  20.       }
  21.     });
  22.     // Sort dropDownValues alphabetically by label in ascending order
  23.     dropDownValues.sort((a, b) => a.label.localeCompare(b.label));
  24.  
  25.     return {
  26.       data: dropDownValues,
  27.     };
  28.   },
  29.   async getTableData(ctx) {
  30.     let excel = strapi.config.get("excel");
  31.     let uid = ctx?.query?.uid;
  32.     let limit = ctx?.query?.limit;
  33.     let offset = ctx?.query?.offset;
  34.     let query = await this.restructureObject(
  35.       excel?.config[uid],
  36.       uid,
  37.       limit,
  38.       offset
  39.     );
  40.  
  41.     let response = await strapi.db.query(uid).findMany(query);
  42.  
  43.     let header = [
  44.       ...excel?.config[uid]?.columns,
  45.       ...Object.keys(excel?.config[uid]?.relation),
  46.     ];
  47.  
  48.     let where = {};
  49.  
  50.     if (excel?.config[uid]?.locale == "true") {
  51.       where = {
  52.         locale: "en",
  53.       };
  54.     }
  55.  
  56.     let count = await strapi.db.query(uid).count(where);
  57.  
  58.     let tableData = await this.restructureData(response, excel?.config[uid]);
  59.  
  60.     // Sort dropDownValues alphabetically by label in ascending order
  61.  
  62.     return {
  63.       data: tableData,
  64.       count: count,
  65.       columns: header,
  66.     };
  67.   },
  68.   async downloadExcel(ctx) {
  69.     try {
  70.       let excel = strapi.config.get("excel");
  71.       let uid = ctx?.query?.uid;
  72.       let query = await this.restructureObject(excel?.config[uid], uid);
  73.       let response = await strapi.db.query(uid).findMany(query);
  74.       let excelData = await this.restructureData(response, excel?.config[uid]);
  75.  
  76.       const workbook = new ExcelJS.Workbook();
  77.       const worksheet = workbook.addWorksheet("info commandes"); // Nouveau sheet
  78.  
  79.       const headers = [
  80.         ...excel?.config[uid]?.columns,
  81.         ...Object.keys(excel?.config[uid]?.relation).flatMap((relation) => {
  82.           return excel?.config[uid]?.relation[relation].column.map((column) => {
  83.             if (column === "quantity") return "Quantity";
  84.             if (column === "produit") return "Produit";
  85.             if (column === "createdAt") return "CreatedAt";
  86.             return `${relation}_${column}`;
  87.           });
  88.         }),
  89.       ];
  90.  
  91.       // Ajout titre au worksheet
  92.       worksheet.columns = headers.map((header) => ({
  93.         header,
  94.         key: header,
  95.         width: 20,
  96.         style: {
  97.           numFmt: header === "createdAt" ? "yyyy/mm/dd" : (header === "totalOrderAmount" ? "#,##0.00 €" : undefined)
  98.         }
  99.       }));
  100.  
  101.       // Ajout data au worksheet
  102.       excelData.forEach((row) => {
  103.         const produitValues = row["Produit"] ? row["Produit"].split(", ") : [];
  104.         const quantityValues = row["Quantity"] ? row["Quantity"].split(", ") : [];
  105.  
  106.         const maxItemCount = Math.max(produitValues.length, quantityValues.length);
  107.  
  108.         for (let i = 0; i < maxItemCount; i++) {
  109.           const newRow = {};
  110.  
  111.           headers.forEach((header) => {
  112.             if (header === "Quantity" && quantityValues[i]) {
  113.               newRow["Quantity"] = quantityValues[i];
  114.             } else if (header === "Produit" && produitValues[i]) {
  115.               newRow["Produit"] = produitValues[i];
  116.             } else if (header === "createdAt" && row["createdAt"]) {
  117.               // Convertion date
  118.               newRow["createdAt"] = row["createdAt"].split("T")[0].replace(/-/g, "/"); //  .replace(/g, "\");
  119.             } else {
  120.               newRow[header] = row[header];
  121.             }
  122.           });
  123.  
  124.           worksheet.addRow(newRow);
  125.         }
  126.       });
  127.  
  128.       worksheet.eachRow({ includeEmpty: false }, function (row, rowNumber) {
  129.         if (rowNumber > 1) { // PAS LE TITRE
  130.           const currentCell = row.getCell("createdAt");
  131.           if (typeof currentCell.value === "string") {
  132.             const dateParts = currentCell.value.split("/");
  133.             if (dateParts.length === 3) {
  134.               const month = parseInt(dateParts[1], 10);
  135.               let fillColor = "FFFFFFFF";
  136.               if ([1, , 5, 7, 9, 11].includes(month)) fillColor = "EEECE1";
  137.              
  138.              
  139.               row.eachCell({ includeEmpty: true, reverse: true }, function (cell, colNumber) {
  140.                 cell.fill = {
  141.                   type: "pattern",
  142.                   pattern: "solid",
  143.                   fgColor: { argb: fillColor },
  144.                 };
  145.                 // Bordure cellule
  146.                 cell.border = {
  147.                   top: { style: "thin", color: { argb: "FF000000" } },
  148.                   left: { style: "thin", color: { argb: "FF000000" } },
  149.                   bottom: { style: "thin", color: { argb: "FF000000" } },
  150.                   right: { style: "thin", color: { argb: "FF000000" } }
  151.                 };
  152.               });
  153.             }
  154.           }
  155.         }
  156.       });
  157.  
  158. // ---------------------------------------------------------- TOTAL STATS
  159.  
  160. const totalWorksheet = workbook.addWorksheet('Total Produits');
  161. let months = {};
  162.  
  163. worksheet.eachRow({ includeEmpty: false }, function (row, rowNumber) {
  164.   if (rowNumber > 1) { // pas le titre
  165.     const currentCell = row.getCell("createdAt");
  166.     if (typeof currentCell.value === "string") {
  167.       const dateParts = currentCell.value.split("/");
  168.       if (dateParts.length === 3) {
  169.         const year = parseInt(dateParts[0], 10);
  170.         const month = parseInt(dateParts[1], 10);
  171.         months[year] = months[year] || {};
  172.         months[year][month] = months[year][month] || {};
  173.         months[year][month].products = months[year][month].products || new Set();
  174.         months[year][month].quantities = months[year][month].quantities || {};
  175.         const produits = row.getCell("Produit").value;
  176.         const quantities = row.getCell("Quantity").value;
  177.         if (produits && quantities) {
  178.           const productArray = produits.split(", ");
  179.           const quantityArray = quantities.split(", ");
  180.           productArray.forEach((product, index) => {
  181.             const quantity = parseInt(quantityArray[index], 10);
  182.             months[year][month].products.add(product);
  183.             months[year][month].quantities[product] = (months[year][month].quantities[product] || 0) + quantity;
  184.           });
  185.         }
  186.       }
  187.     }
  188.   }
  189. });
  190.  
  191. // vvvvv A OPTI mais fonctionne vvvvv
  192.  
  193. // Tri décroissant
  194. const sortedYears = Object.keys(months).sort((a, b) => b - a);
  195.  
  196. function getFillColor(month, isHeader = false) {
  197.   const colors = {
  198.     1: "EEECE1",
  199.     5: "EEECE1",
  200.     7: "EEECE1",
  201.     9: "EEECE1",
  202.     11: "EEECE1"
  203.    
  204.   };
  205.  
  206.   return isHeader ? "D9D9D9" : (colors[month] || "FFFFFF");
  207. }
  208.  
  209. const monthNames = {
  210.   1: "janvier",
  211.   2: "février",
  212.   3: "mars",
  213.   4: "avril",
  214.   5: "mai",
  215.   6: "juin",
  216.   7: "juillet",
  217.   8: "août",
  218.   9: "septembre",
  219.   10: "octobre",
  220.   11: "novembre",
  221.   12: "décembre"
  222. };
  223.  
  224. let currentColumn = headers.length;
  225. sortedYears.forEach(year => {
  226.   const yearData = months[year];
  227.   const sortedMonths = Object.keys(yearData).sort((a, b) => b - a);
  228.   sortedMonths.forEach(month => {
  229.     const monthName = monthNames[parseInt(month)];
  230.     const productHeader = `${year}_${monthName}_Products`;
  231.     const quantityHeader = `${year}_${monthName}_Quantities`;
  232.     if (!headers.includes(productHeader)) {
  233.       headers.push(productHeader);
  234.       headers.push(quantityHeader);
  235.       headers.push("");
  236.       totalWorksheet.getColumn(currentColumn + 1).key = productHeader;
  237.       totalWorksheet.getColumn(currentColumn + 2).key = quantityHeader;
  238.       totalWorksheet.getColumn(currentColumn + 3).key = "";
  239.       totalWorksheet.getColumn(currentColumn + 1).width = 20;
  240.       totalWorksheet.getColumn(currentColumn + 2).width = 10;
  241.       totalWorksheet.getCell(1, currentColumn + 1).fill = {
  242.         type: "pattern",
  243.         pattern: "solid",
  244.         fgColor: { argb: getFillColor(parseInt(month), true) }
  245.       };
  246.       totalWorksheet.getCell(1, currentColumn + 2).fill = {
  247.         type: "pattern",
  248.         pattern: "solid",
  249.         fgColor: { argb: getFillColor(parseInt(month), true) }
  250.       };
  251.     }
  252.     totalWorksheet.getCell(1, currentColumn + 1).value = `${monthName} ${year} Produits`;
  253.     totalWorksheet.getCell(1, currentColumn + 2).value = `Quantité`;
  254.     const productArray = Array.from(yearData[month].products).sort(); // Tri par alphab
  255.     productArray.forEach((product, index) => {
  256.       const rowIndex = index + 2;
  257.       totalWorksheet.getCell(rowIndex, currentColumn + 1).value = product;
  258.       totalWorksheet.getCell(rowIndex, currentColumn + 2).value = yearData[month].quantities[product] || 0;
  259.  
  260.      
  261.       totalWorksheet.getCell(rowIndex, currentColumn + 1).fill = {
  262.         type: "pattern",
  263.         pattern: "solid",
  264.         fgColor: { argb: getFillColor(parseInt(month)) }
  265.       };
  266.      
  267.       totalWorksheet.getCell(rowIndex, currentColumn + 2).fill = {
  268.         type: "pattern",
  269.         pattern: "solid",
  270.         fgColor: { argb: getFillColor(parseInt(month)) }
  271.       };
  272.     });
  273.     currentColumn += 3;
  274.   });
  275. });
  276.  
  277.  
  278.  
  279.  
  280.  
  281. // ------------------------------------ END TOTAL STATS
  282.  
  283.  
  284.       // Write the workbook to a buffer
  285.       const buffer = await workbook.xlsx.writeBuffer();
  286.  
  287.       return buffer;
  288.     } catch (error) {
  289.       console.error("Error writing buffer:", error);
  290.     }
  291.   },
  292.  
  293.  
  294.  
  295.  
  296.  
  297.  
  298.  
  299.  
  300.  
  301.   async restructureObject(inputObject, uid, limit, offset) {
  302.     let excel = strapi.config.get("excel");
  303.  
  304.     let where = {};
  305.  
  306.     if (excel?.config[uid]?.locale == "true") {
  307.       where = {
  308.         locale: "en",
  309.       };
  310.     }
  311.     let orderBy = {
  312.       id: "asc",
  313.     };
  314.  
  315.     const restructuredObject = {
  316.       select: inputObject.columns || "*",
  317.       populate: {},
  318.       where,
  319.       orderBy,
  320.       limit: limit,
  321.       offset: offset,
  322.     };
  323.  
  324.     for (const key in inputObject.relation) {
  325.       restructuredObject.populate[key] = {
  326.         select: inputObject.relation[key].column,
  327.       };
  328.     }
  329.  
  330.     return restructuredObject;
  331.   },
  332.   async restructureData(data, objectStructure) {
  333.     return data.map((item) => {
  334.       const restructuredItem = {};
  335.  
  336.       // Restructure main data based on columns
  337.       for (const key of objectStructure.columns) {
  338.         if (key in item) {
  339.           restructuredItem[key] = item[key];
  340.         }
  341.       }
  342.  
  343.       // Restructure relation data based on the specified structure
  344.       for (const key in objectStructure.relation) {
  345.         if (key in item && item[key]) {
  346.           const relationData = item[key];
  347.           if (Array.isArray(relationData) && relationData.length > 0) {
  348.             // pas opti (mais fonctionne)
  349.             relationData.forEach((obj, index) => {
  350.               for (const column of objectStructure.relation[key].column) {
  351.                 if (column === 'quantity') {
  352.                   if (!restructuredItem['Quantity']) {
  353.                     restructuredItem['Quantity'] = `${obj[column]}`;
  354.                   } else {
  355.                     restructuredItem['Quantity'] += `, ${obj[column]}`;
  356.                   }
  357.                 }
  358.                 if (column === 'produit') {
  359.                   if (!restructuredItem['Produit']) {
  360.                     restructuredItem['Produit'] = `${obj[column]}`;
  361.                   } else {
  362.                     restructuredItem['Produit'] += `, ${obj[column]}`;
  363.                   }
  364.                 }
  365.                 restructuredItem[`${key}_${column}_${index + 1}`] = obj[column];
  366.               }
  367.             });
  368.           } else {
  369.             for (const column of objectStructure.relation[key].column) {
  370.               if (column === 'produit') {
  371.                 restructuredItem['Produit'] = item[key][column];
  372.               }
  373.               if (column === 'quantity') {
  374.                 restructuredItem['Quantity'] = item[key][column];
  375.               }
  376.               restructuredItem[`${key}_${column}`] = item[key][column];
  377.             }
  378.           }
  379.         }
  380.       }
  381.  
  382.       return restructuredItem;
  383.     });
  384.   },
  385. });
  386.  
Advertisement
Add Comment
Please, Sign In to add comment