def loadSalesOrderItemFact()

in bi/src/main/groovy/org/apache/ofbiz/bi/FactServices.groovy [208:513]


def loadSalesOrderItemFact() {
    Map inMap
    Map naturalKeyFields
    Map serviceResult
    GenericValue orderHeader = parameters.orderHeader
    GenericValue orderItem = parameters.orderItem
    GenericValue orderAdjustment = parameters.orderAdjustment

    List orderAdjustments
    GenericValue orderStatus

    if (!orderHeader) {
        orderHeader = from("OrderHeader").where(parameters).queryOne()
    }
    if (!orderItem) {
        orderItem = from("OrderItem").where(parameters).queryOne()
    }
    if (!orderAdjustment) {
        orderAdjustments = from("OrderAdjustment").where("orderId": orderItem.orderId).queryList()
    }
    if (!orderHeader) {
        String errorMessage = UtilProperties.getMessage("OrderErrorUiLabels", "OrderOrderIdDoesNotExists", parameters.locale)
        logError(errorMessage)
        return error(errorMessage)
    }
    if (!orderItem) {
        String errorMessage = UtilProperties.getMessage("OrderErrorUiLabels", "OrderOrderItemIdDoesNotExists", parameters.locale)
        logError(errorMessage)
        return error(errorMessage)
    }

    if ("ORDER_APPROVED".equals(orderHeader.statusId)) {
        GenericValue fact = from("SalesOrderItemFact").where(orderId: orderItem.orderId, orderItemSeqId: orderItem.orderItemSeqId).queryOne()
        // key handling
        if (!fact) {
            fact = makeValue("SalesOrderItemFact")
            fact.orderId = orderHeader.orderId
            fact.orderItemSeqId = orderItem.orderItemSeqId
            fact.productStoreId = orderHeader.productStoreId
            fact.salesChannelEnumId = orderHeader.salesChannelEnumId
            fact.statusId = orderItem.statusId

            // account
            if (orderHeader.productStoreId) {
                GenericValue account =  from("ProductStore").where(productStoreId: orderHeader.productStoreId).queryOne()
                fact.account = account.storeName
            }

            // pod
            if ("EUR".equals(orderHeader.currencyUom)) {
                fact.pod = "Latin"
            } else {
                fact.pod = "Engish"
            }

            // brand
            if (orderHeader.salesChannelEnumId) {
                GenericValue brand = from("Enumeration").where(enumId: orderHeader.salesChannelEnumId).queryOne()
                fact.brand = brand.description
            }

            // conversion of the order date
            orderStatus = from("OrderStatus")
                .where(orderId: orderHeader.orderId, statusId: "ORDER_APPROVED")
                .orderBy("-statusDatetime")
                .queryFirst()
            if (orderStatus.statusDatetime) {
                inMap = [:]
                naturalKeyFields = [:]
                inMap.dimensionEntityName = "DateDimension"
                Date statusDatetime = new Date(orderStatus.statusDatetime.getTime())
                naturalKeyFields.dateValue = statusDatetime
                inMap.naturalKeyFields = naturalKeyFields
                serviceResult = run service: "getDimensionIdFromNaturalKey", with: inMap
                fact.orderDateDimId = serviceResult.dimensionId
                if (!fact.orderDateDimId) {
                    fact.orderDateDimId = "_NF_"
                }
            } else {
                fact.orderDateDimId = "_NA_"
            }

            // conversion of the product id
            if (UtilValidate.isNotEmpty(orderItem.productId)) {
                inMap = [:]
                naturalKeyFields = [:]
                inMap.dimensionEntityName = "ProductDimension"
                naturalKeyFields.productId = orderItem.productId
                inMap.naturalKeyFields = naturalKeyFields
                serviceResult = run service: "getDimensionIdFromNaturalKey", with: inMap
                fact.productDimId = serviceResult.dimensionId
                if (!fact.productDimId) {
                    fact.productDimId = "_NF_"
                }
            } else {
                fact.productDimId = "_NA_"
            }

            // conversion of the order currency
            if (orderHeader.currencyUom) {
                inMap = [:]
                naturalKeyFields = [:]
                inMap.dimensionEntityName = "CurrencyDimension"
                naturalKeyFields.currencyId = orderHeader.currencyUom
                inMap.naturalKeyFields = naturalKeyFields
                serviceResult = run service: "getDimensionIdFromNaturalKey", with: inMap
                fact.origCurrencyDimId = serviceResult.dimensionId
                if (!fact.origCurrencyDimId) {
                    fact.origCurrencyDimId = "_NF_"
                }
            } else {
                fact.origCurrencyDimId = "_NA_"
            }

            // productCategoryId
            GenericValue productCategoryMember = from("ProductCategoryMember").where(productId: orderItem.productId, thruDate: null).queryFirst()
            if (productCategoryMember) {
                fact.productCategoryId = productCategoryMember.productCategoryId
            }

            // TODO
            fact.billToCustomerDimId = "_NA_"

            fact.create()
        }
        /*
         * facts handling
         */
        Map partyAccountingPreferencesCallMap = [:]

        OrderReadHelper orderReadHelper = new OrderReadHelper(orderHeader)
        Map billFromParty = orderReadHelper.getBillFromParty()
        partyAccountingPreferencesCallMap.organizationPartyId = billFromParty.partyId
        Map accountResult = run service:"getPartyAccountingPreferences", with: partyAccountingPreferencesCallMap
        GenericValue accPref = accountResult.partyAccountingPreference

        fact.quantity = orderItem.quantity as BigDecimal
        fact.extGrossAmount = 0 as BigDecimal
        fact.extGrossCost = 0 as BigDecimal
        fact.extDiscountAmount = 0 as BigDecimal
        fact.extNetAmount = 0 as BigDecimal
        fact.extShippingAmount = 0 as BigDecimal
        fact.extTaxAmount = 0 as BigDecimal

        fact.GS = 0 as BigDecimal
        fact.GMS = 0 as BigDecimal
        fact.GMP = 0 as BigDecimal
        fact.GSS = 0 as BigDecimal
        fact.GSC = 0 as BigDecimal
        fact.GSP = 0 as BigDecimal
        fact.GP = 0 as BigDecimal

        fact.countOrder = 0 as BigDecimal

        // extGrossAmount
        Map convertUomCurrencyMap = [:]
        convertUomCurrencyMap.uomId = orderHeader.currencyUom
        convertUomCurrencyMap.uomIdTo = accPref.baseCurrencyUomId
        if (UtilValidate.isNotEmpty(orderStatus)) {
        convertUomCurrencyMap.nowDate = orderStatus.statusDatetime
        }
        Map convertResult = run service: "convertUomCurrency", with: convertUomCurrencyMap
        BigDecimal exchangeRate = convertResult.conversionFactor

        if (exchangeRate) {
            BigDecimal unitPrice = orderItem.unitPrice * exchangeRate

            fact.extGrossAmount = fact.quantity * unitPrice
        }

        // extGrossCost
        GenericValue cost = from("SupplierProduct")
            .where(productId: orderItem.productId, availableThruDate: null, minimumOrderQuantity: 0 as BigDecimal)
            .queryFirst()
        if (cost) {
            convertUomCurrencyMap.uomId = cost.currencyUomId
            convertUomCurrencyMap.uomIdTo = accPref.baseCurrencyUomId
            if (orderStatus) {
                convertUomCurrencyMap.nowDate = orderStatus.statusDatetime
            }
            Map grossCostResult = run service: "convertUomCurrency", with: convertUomCurrencyMap
            exchangeRate = grossCostResult.conversionFactor

            if (exchangeRate) {
                BigDecimal costPrice = cost.lastPrice * exchangeRate
                fact.extGrossCost = fact.quantity * costPrice
            }
        }

        // extShippingAmount
        for (GenericValue shipping : orderAdjustments) {
            if ("SHIPPING_CHARGES".equals(shipping.orderAdjustmentTypeId)) {
                fact.extShippingAmount = fact.extShippingAmount + shipping.amount
            }
        }

        // extTaxAmount
        for (GenericValue tax : orderAdjustments) {
            if ("SALES_TAX".equals(tax.orderAdjustmentTypeId)) {
                fact.extTaxAmount = fact.extTaxAmount + tax.amount
            }
        }

        // extDiscountAmount
        for (GenericValue discount : orderAdjustments) {
            if ("PROMOTION_ADJUSTMENT".equals(discount.orderAdjustmentTypeId)) {
                fact.extDiscountAmount = fact.extDiscountAmount + discount.amount
                // product promo code
                GenericValue productPromoCode = from("ProductPromoCode").where(productPromoId: discount.productPromoId).queryFirst()
                if (productPromoCode) {
                    fact.productPromoCode = productPromoCode.productPromoCodeId
                } else {
                    fact.productPromoCode = "Not require code"
                }
            }
        }

        // extNetAmount
        fact.extNetAmount = fact.extGrossAmount - fact.extDiscountAmount

        // GS
        BigDecimal countGS = 0 as BigDecimal
        List checkGSList = from("SalesOrderItemFact").where(orderId: orderHeader.orderId).queryList()
        for (GenericValue checkGS : checkGSList) {
            if (checkGS.GS) {
                if (0 != checkGS.GS) {
                    countGS = 1
                }
            }
        }
        if (countGS == 0) {
            convertUomCurrencyMap.uomId = orderHeader.currencyUom
            convertUomCurrencyMap.uomIdTo = accPref.baseCurrencyUomId
            if (orderStatus) {
                convertUomCurrencyMap.nowDate = orderStatus.statusDatetime
            }
            Map GSResult = run service: "convertUomCurrency", with: convertUomCurrencyMap
            exchangeRate = GSResult.conversionFactor

            if (exchangeRate) {
                fact.GS = orderHeader.grandTotal * exchangeRate
            }
        }

        // GMS
        fact.GMS = fact.GMS + fact.extGrossAmount

        // GMP
        fact.GMP = fact.GMS - fact.extGrossCost

        // GSP
        BigDecimal countGSP = 0 as BigDecimal
        List checkGSPList = from("SalesOrderItemFact").where(orderId: orderHeader.orderId).queryList()
        for (GenericValue checkGSP : checkGSPList) {
            if (checkGSP.GSP) {
                if (checkGSP.GSP != 0) {
                    countGSP = 1
                }
            }
        }
        if (countGSP == 0) {
            List orderItemList = from("OrderItem").where(orderId: orderHeader.orderId).queryList()

            BigDecimal warrantyPrice = 0 as BigDecimal
            for (GenericValue warranty : orderAdjustments) {
                if ("WARRANTY_ADJUSTMENT".equals(warranty.orderAdjustmentTypeId)) {
                    warrantyPrice = warrantyPrice + warranty.amount
                }
            }
            BigDecimal GSS = fact.extShippingAmount + warrantyPrice

            convertUomCurrencyMap.uomId = orderHeader.currencyUom
            convertUomCurrencyMap.uomIdTo = accPref.baseCurrencyUomId
            if (orderStatus) {
                convertUomCurrencyMap.nowDate = orderStatus.statusDatetime
            }
            Map GSPResult = run service: "convertUomCurrency", with: convertUomCurrencyMap
            exchangeRate = GSPResult.conversionFactor

            if (exchangeRate) {
                GSS = GSS * exchangeRate
            }
            fact.GSS = GSS
            fact.GSP = GSS as BigDecimal
        }

        // GP
        fact.GP = fact.GMP + fact.GSP

        // countOrder
        BigDecimal countOrder = 0 as BigDecimal
        List checkCountOrderList = from("SalesOrderItemFact").where(orderId: orderHeader.orderId).queryList()
        for (GenericValue checkCountOrder : checkCountOrderList) {
            if (checkCountOrder.countOrder) {
                if (checkCountOrder.countOrder != 0) {
                    countOrder = 1
                }
            }
        }
        if (countOrder == 0) {
            fact.countOrder = 1 as BigDecimal
        }
        fact.store()
    }
    return success()
}