Map loadSalesOrderItemFact()

in bi/src/main/groovy/org/apache/ofbiz/bi/FactServices.groovy [197:492]


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

    List orderAdjustments
    GenericValue orderStatus

    orderHeader ?: from('OrderHeader').where(parameters).queryOne()
    orderItem ?: this.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 (orderHeader.statusId == 'ORDER_APPROVED') {
        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 (orderHeader.currencyUom == 'EUR') {
                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
                fact.orderDateDimId = fact.orderDateDimId ?: '_NF_'
            } else {
                fact.orderDateDimId = '_NA_'
            }

            // conversion of the product id
            if (orderItem.productId) {
                inMap = [:]
                naturalKeyFields = [:]
                inMap.dimensionEntityName = 'ProductDimension'
                naturalKeyFields.productId = orderItem.productId
                inMap.naturalKeyFields = naturalKeyFields
                serviceResult = run service: 'getDimensionIdFromNaturalKey', with: inMap
                fact.productDimId = serviceResult.dimensionId
                fact.orderDateDimId = fact.orderDateDimId ?: '_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
                fact.orderDateDimId = fact.orderDateDimId ?: '_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.with {
            quantity = orderItem.quantity as BigDecimal
            extGrossAmount = 0 as BigDecimal
            extGrossCost = 0 as BigDecimal
            extDiscountAmount = 0 as BigDecimal
            extNetAmount = 0 as BigDecimal
            extShippingAmount = 0 as BigDecimal
            extTaxAmount = 0 as BigDecimal

            GS = 0 as BigDecimal
            GMS = 0 as BigDecimal
            GMP = 0 as BigDecimal
            GSS = 0 as BigDecimal
            GSC = 0 as BigDecimal
            GSP = 0 as BigDecimal
            GP = 0 as BigDecimal
        }

        countOrder = 0 as BigDecimal

        // extGrossAmount
        Map convertUomCurrencyMap = [:]
        convertUomCurrencyMap.uomId = orderHeader.currencyUom
        convertUomCurrencyMap.uomIdTo = accPref.baseCurrencyUomId
        if (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.orderAdjustmentTypeId == 'SHIPPING_CHARGES') {
                fact.extShippingAmount = fact.extShippingAmount + shipping.amount
            }
        }

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

        // extDiscountAmount
        for (GenericValue discount : orderAdjustments) {
            if (discount.orderAdjustmentTypeId == 'PROMOTION_ADJUSTMENT') {
                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) {
            BigDecimal warrantyPrice = 0 as BigDecimal
            for (GenericValue warranty : orderAdjustments) {
                if (warranty.orderAdjustmentTypeId == 'WARRANTY_ADJUSTMENT') {
                    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()
}