"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.shortageReport = void 0;
exports.shortageReport = {
    async shortageReport(_, params, context) {
        try {
            const { tx } = context.state;
            let bizplaceFilter = { name: '', operator: '', value: '' };
            let order = params.filters.find(items => items.name === 'order');
            let fromDate = params.filters.find(items => items.name === 'fromDate');
            let toDate = params.filters.find(items => items.name === 'toDate');
            let orderNo = params.filters.find(items => items.name === 'orderNo');
            let product = params.filters.find(items => items.name === 'product');
            let bizplace = params.filters.find(items => items.name === 'bizplace');
            if (!bizplace)
                throw 'Invalid input';
            let roFilter = '', queryFilter = '';
            if (product) {
                let productInfoValue = product.value
                    .toLowerCase()
                    .split(',')
                    .map(prod => {
                    return "'%" + prod.trim().replace(/'/g, "''") + "%'";
                })
                    .join(',');
                roFilter += `AND (
          Lower(drg.name) LIKE ANY(ARRAY[${productInfoValue}])
          OR Lower(p.sku) LIKE ANY(ARRAY[${productInfoValue}])
          OR Lower(p.sku) LIKE ANY(ARRAY[${productInfoValue}])
          OR Lower(p.sku) LIKE ANY(ARRAY[${productInfoValue}])
          OR Lower(p."name") LIKE ANY(ARRAY[${productInfoValue}])
          OR Lower(p."name") LIKE ANY(ARRAY[${productInfoValue}])
          OR Lower(p."name") LIKE ANY(ARRAY[${productInfoValue}])

        )`;
            }
            if (orderNo) {
                let orderValue = orderNo.value
                    .toLowerCase()
                    .split(',')
                    .map(prod => {
                    return "'%" + prod.trim().replace(/'/g, "''") + "%'";
                })
                    .join(',');
                roFilter += `AND (
          Lower(drg.name) LIKE ANY(ARRAY[${orderValue}])
          OR Lower(drg.ref_no) LIKE ANY(ARRAY[${orderValue}])
          OR Lower(drg.ref_no_2) LIKE ANY(ARRAY[${orderValue}])
          OR Lower(drg.ref_no_3) LIKE ANY(ARRAY[${orderValue}])
        )`;
            }
            if (bizplace) {
                queryFilter += ` AND drg.bizplace_id = '${bizplace.value}'`;
            }
            if (!bizplaceFilter || !fromDate || !toDate)
                throw 'Invalid input';
            await tx.query(`
          CREATE TEMP TABLE shortage_report ON COMMIT DROP AS (
              SELECT 
                  b."name" AS "company", 
                  drg.name AS "order_no",
                  drg.ref_no, 
                  p.sku AS "product_sku", 
                  p."name" AS "product_name", 
                  p."description" AS "product_description", 
                  op.release_qty AS "order_quantity",
                  COALESCE(src.av_qty, 0) AS available_qty, 
                  COALESCE(src.av_qty, 0) - op.release_qty AS "Nett_Stock",
                  CONCAT(
                      drg.delivery_address_1, ' ', 
                      drg.delivery_address_2, ' ', 
                      drg.delivery_address_3, ' ', 
                      drg.delivery_address_4, ' ', 
                      drg.delivery_address_5
                  ) AS "delivery_address",
                  drg.state,
                  drg.city, 
                  drg.country, 
                  drg.created_at 
              FROM 
                  draft_release_goods drg
              INNER JOIN 
                  bizplaces b ON b.id = drg.bizplace_id
              INNER JOIN 
                  order_products op ON op.draft_release_good_id = drg.id
              INNER JOIN 
                  products p ON p.id = op.product_id
              INNER JOIN
                  product_details pd ON pd.id = op.product_detail_id
              LEFT JOIN (
                  SELECT
                      i.domain_id AS "domain_id",
                      i.bizplace_id AS "bizplace_id",
                      i.product_id AS "product_id",
                      i.product_detail_id AS "product_detail_id",
                      COALESCE(SUM(COALESCE(i.qty, 0)) - SUM(COALESCE(i.locked_qty, 0))) AS "av_qty"
                  FROM 
                      inventories i
                  INNER JOIN 
                      locations l2 ON i.location_id = l2.id AND i.domain_id = l2.domain_id AND l2.type NOT IN ('QUARANTINE', 'RESERVE', 'DAMAGE')
                  INNER JOIN 
                      products p ON p.id = i.product_id
                  INNER JOIN 
                      product_details pd ON pd.id = i.product_detail_id
                  WHERE 
                      i.status = 'STORED'
                      AND i.obsolete IS FALSE
                      AND i.domain_id = $1
                      AND i.bizplace_id = '${bizplace.value}'
                  GROUP BY
                      i.domain_id,
                      i.bizplace_id,
                      i.product_id,
                      i.product_detail_id 
              ) src ON op.product_id = src.product_id AND op.product_detail_id = src.product_detail_id
              WHERE 
                  drg.domain_id = $1
                  AND (drg.status = 'DRAFT' OR drg.status = 'PARTIAL RELEASED')
                  AND op.status = 'DRAFT'
                  AND COALESCE(src.av_qty - op.release_qty, 0) <= 0
                  AND op.release_qty != COALESCE(src.av_qty, 0) 
                  AND drg.created_at >= $2
                  AND drg.created_at <= $3
                  ${roFilter}
                  ${queryFilter}
              ORDER BY 
                  drg.created_at DESC
          )
      `, [context.state.domain.id, fromDate.value, toDate.value]);
            const total = await tx.query(`
        select count(*) from shortage_report
      `);
            const result = await tx.query(`
        select * from shortage_report
        offset $1 limit $2
      `, [(params.pagination.page - 1) * params.pagination.limit, params.pagination.limit]);
            let items = result.map(itm => {
                return {
                    bizplaceName: itm.company,
                    orderNo: itm.order_no,
                    refNo: itm.ref_no,
                    productSku: itm.product_sku,
                    productName: itm.product_name,
                    productDescription: itm.product_description,
                    orderQty: itm.order_quantity,
                    avQty: itm.available_qty,
                    nettStock: itm.Nett_Stock,
                    deliveryAddress: itm.delivery_address,
                    state: itm.state,
                    city: itm.city,
                    country: itm.country,
                    createdAt: itm.created_at
                };
            });
            return {
                items,
                total: total[0].count
            };
        }
        catch (error) {
            throw error;
        }
    }
};
//# sourceMappingURL=shortage-report.js.map