Types DatabaseTypes Tables (category / subcategory) Views
CharDateDoubleDoubleDoubleFloatFloatHugeStringIdentityIntegerLongestStringLongStringNCharNLongestStringNLongStringNShortStringNStringPercentRealIdentityShortStringStringTextTimeStamp AllocationArrayAllocationRecordDDQ_Confirm_Reply_H_List_TDDQ_Confirm_Reply_H_TDDQ_Confirm_Reply_L_List_TDDQ_Confirm_Reply_L_TDDQ_Confirm_Reply_TDDQ_Confirm_Request_H_List_TDDQ_Confirm_Request_H_TDDQ_Confirm_Request_L_List_TDDQ_Confirm_Request_L_TDDQ_Confirm_Request_TDDQ_OperationArrayDDQ_OperationRecordDDQ_OrderArrayDDQ_OrderRecordDDQ_Schedule_Reply_H_List_TDDQ_Schedule_Reply_H_TDDQ_Schedule_Reply_L_List_TDDQ_Schedule_Reply_L_TDDQ_Schedule_Reply_O_List_TDDQ_Schedule_Reply_O_TDDQ_Schedule_Reply_TDDQ_Schedule_Request_H_Ext_TDDQ_Schedule_Request_H_List_TDDQ_Schedule_Request_H_TDDQ_Schedule_Request_H_T_ExtDDQ_Schedule_Request_L_Ext_TDDQ_Schedule_Request_L_List_TDDQ_Schedule_Request_L_TDDQ_Schedule_Request_L_T_ExtDDQ_Schedule_Request_TDDQ_Schedule_Request_T_ExtForecastCollaborationArrayForecastCollaborationRecordForecastEntryArrayForecastEntryRecordForecastItemArrayForecastItemObjectForecastSnapshotArrayForecastSnapshotRecordmyConsignmentSkuArraymyConsignmentSkuRecordmyDataArraymyDataRecordmyDateArraymyDateDemandArraymyDateDemandRecordmyDoubleFloatArraymyFieldPairArraymyFieldPairRecordmyFloatArraymyForecastArraymyForecastRecordmyFormatStringArraymyFormatStringRecordmyFourthArraymyFourthRecordmyFullSkuArraymyFullSkuRecordmyIdentityArraymyIdentityDateArraymyIdentityDateRecordmyIdentityFloatArraymyIdentityFloatRecordmyIdentityGroupedArraymyIdentityGroupedRecordmyLongestStringArraymyMovementArraymyMovementRecordmyOnHandInventoryArraymyOnHandInventoryRecordmyOnHandMovementArraymyOnHandMovementRecordmyPairArraymyPairDateArraymyPairDateRecmyPairRecordmyReportFieldArraymyReportFieldRecordmySkuArraymySkuRecordmySourcingAllocationArraymySourcingAllocationRecordmyStringArraymyStringPairArraymyStringPairRecordmyTripleArraymyTripleRecordmyUnitRecordParameterArrayRevisedAllocationEntryArrayRevisedAllocationEntryRecordSnoItemArraySnoItemRecordStockMonitoringArrayStockMonitoringRecord Block Scheduling  Block Scheduling     BSOAllocationData     BSOCampaignBatchUpdateData     BSOGradeProperties     BSOIndicativeData     BSOInputData     BSOOrdersData     BSOProgramGrades     BSOProgramRunsData     BSOPrograms     BSOProgramTemplates     BSORunsData     BSOTemplateGrades     CalculatedOppBlocks     CampaignChangesData     ChangeOverProperties     DeletedRuns     GradeMaterials     GradeProperties     MaterialBlocks     MaterialRunAttributes     MaterialRunProducts     MaterialRunProperties     MaterialRuns     MaterialRunStatuses     OptimizedRunOrders     OptimizedRunProperties     OptimizedRuns     PreTrimSolutions     RunInventoryProfiles     RunsForAdjustingData     SplitRunsData     WorkCentreAttributes     WorkCentreChangeOvers     WorkCentreROParameters     WorkCentreROResults
Block Scheduling  Temporary     AlternateRunsData     BSOWorkcentreData     GradeProductionRates     HistoryForOppBlocksData     MaterialRunParametersData     MaterialRunPropertiesData     MPBSAllocationData     MPBSComparisonData     OppBlockDurationData     OrdersForMovingData     ProductionInformationData     SourceWorkcentresData     WorkcentreROData
Core - Processes  Reference     ProcessStatusNames     Tasks
Core  Access rights     Actions     FavoritePages     Pages     Roles     RolesActions     RolesTasks     RolesWidgets     UsersRoles
Core  Calendars     CalendarRules     Calendars     CalendarSources
Core  Configuration     Bundles     BundleValues     ChartLines     Charts     FilterHistories     GridColumns     Grids     LoginInformation     MessageCharacteristics     Navigations     NavigationTasks     PageParameters     PurgeObsoleteData     SafetyStockMethods     SummaryHistories     SystemParameters     SystemParameterValues     UserAudit     UserNavigations     UserPageParameters     UserParameters     Users     UserSessionParameters
Core  Core     AccessWorkCentres     AlternateMaterials     BillOfMaterials     BOM     BOMMaterials     Characteristics     Companies     ConsignmentParameters     CoProducts     CostRules     Currencies     CustomerRanks     Dashboards     DashboardWidgets     DerivedCharacteristicRules     DerivedCharacteristics     EndUseProperties     EndUses     ExchangeRates     ExpandedCostRules     ExpandedExchangeRates     ExpandedHierarchies     ExpandedHierarchiesSpec     ExpandedLocations     ExpandedLocationsSpec     ExpandedMaterials     ExpandedPropertyValues     ExpandedSKUNominalCosts     ExternalFixedSources     FixedSourceSnapshots     ForecastMethodRules     Hierarchies     HierarchyLevels     HierarchyPropertyDetails     HoldingCosts     InitialSourceRules     InitialSourceRuleSources     InitialSources     Jobs     JobStates     Locations     MaterialGroups     MaterialPropsSpec     Materials     MaterialSupercessions     MaterialTypeProperties     MaterialTypes     MaterialUnits     MessageHierarchies     MessageProperties     MonthlyExchangeRates     NominalCostRules     OperationTypeConversions     OperationTypes     PriceRules     ProductCharacteristics     ProductionConfigurations     ProductionRates     ProductRoutes     ProductRouteStages     Properties     PropertyCharacteristics     PropertyValues     PropertyValuesSpec     ReplacedLocations     ReplenishmentHorizonRules     SecondPassRules     SiteMaterialUsages     SiteProperties     Sites     SkuDetails     SkuProperties     SkuValuesLogs     SourceLists     SourceListSources     SourcePriorities     SourcePriorityRules     SupercessionRules     Suppliers     UserGroupFilters     UserGroupGroups     UserGroupLocations     UserGroups     ValidSources     WidgetParameters     Widgets     WidgetTemplateParameters     WidgetTemplates     WorkCentreCapacities     WorkCentreParameters     WorkCentreParameterTypes     WorkCentres     WorkCentreShuts     WorkCentreShutTypes     WorkCentreTimeEfficiencies     WorkCentreTypes
Core  Language     DBDictionaries     Dictionaries     LanguageCategories     LanguageCategoryTypes     Languages     StorageEntries     Storages
Core  Logging     EventLogs     EventMessages     ExternalMessageLogs     FailedMessages     MessagesLog     Processes     ProcessingLog     ProcessLogs     SelfLog     SystemParameterLogs     UserIPLogging     UserPasswordsHistory     UserSessions
Core  Reference     EventTypes     Notifications     ProcessParts     ProcessResults     TaskResults     UserNotifications
Core  Schedules     ScheduleRules     Schedules     ScheduleSources
Core  Temporary     CheckData     ScenarioRates     SPValuesData     WorkCentreParametersData
Core  Temporary table     ProcessStatuses
Core  Units     Units     UnitTypeConverts     UnitTypes
Due date quoting  Due date quoting     DDQAmendedOrders     DDQConsignmentOrders     DDQInquiryMethodTypes     DDQLog     DDQPossibleQuantityData     DDQRequests     DDQResponseOperations     DDQResponseOperationsHistory     DDQResponses     DDQResponsesHistory     DDQResultCodes     DDQSplittedOrders     DDQTasks     DDQUnConfirmedOrders     GroupRealInventoryProfiles     RealInventoryProfiles     RealInventoryProfileSnapshot
Due date quoting  Logging     CTPMessagesLog     RestMessagesLog
Due date quoting  Temporary     OverallStockData
Due date quoting  Temporary table     AmendInventories     AmendInventoryProfilesData     AmendRuns     CheckDDQFGInventoryData     CheckDDQFLRunsData     CheckDDQPMRunsData     CheckDDQSFGInventoryData     DDQFGInventorySourcesData     DDQInventoryData     DDQProductionSourcesData     DDQResultData     DDQRunsData     DDQSiteData     DDQSitesData     DDQSiteSourceData     DDQSourceData     DDQSourcePrioritiesData     DDQTimeStamps     DDQWarehouseSourcesData     FLforPMData     OppBlockData     PMSourceData     PMSourceForFGData     RealInventoryForFlRunData     STODatesData     UsedOppQuantityData     UseOppRuns
Forecasting  Forecast Sample     ForecastSampleMethods
Forecasting  Forecasting     ArchivedForecastBodies     AverageExpandedPrices     CollaborationData     ExpandedNominalCosts     ExpandedPrices     ExpandedSKUPrices     FittedHistories     ForecastBodies     ForecastChangeDetails     ForecastChanges     ForecastChangeSku     ForecastCollaborationData     ForecastEvents     ForecastEventTypes     ForecastHistoryData     ForecastItemsData     ForecastLaunchProfiles     ForecastMethods     ForecastMethodTypeParameters     ForecastMethodTypes     ForecastOperations     ForecastParameters     ForecastParameterValues     ForecastPatterns     ForecastRanges     ForecastRangeValues     ForecastSampleBodies     ForecastSampleFittedHistories     ForecastSampleHistory     ForecastSnapshotBodies     ForecastStatisticData     ForecastStatistics     ForecastStatuses     ForecastViewData     ForecastWeeklyCoefs     FrozenEditingRules     GroupForecastViewData     HistoryData     MarketInfo     ProductGradeCosts     SkuForecastPatterns     SkuLaunchProfiles     SMIForecastData     UsageHistories
Forecasting  Forecasts     Forecasts     ForecastSamples     ForecastSnapshots
Forecasting  Temporary     CarryForecastData     CollaborationGraphData     ForecastSampleSku     ForecastSampleStatistics     HistoryComparisonData     MovingForecastGroupData     PropertyFilterData     SelectiveData     SupercessionConflictsData
General  General     IPlanHooks
Inventory Planning  Inventory Planning     InventoryLogs
Master Planning       AllocationSnapshots     UnallocatedReasons
Master Planning  Allocations     AllocationChangeDetails     AllocationChanges     ExcludedPropertiesFromSA     MandatorySettings     MandatorySettingSnapshots     MinimumAllocations     MinimumAllocationsSnapshot
Master Planning  Master Planning     AllocationBodies     AllocationBodies2     AllocationSnapshotBodies     ArchivedAllocationBodies     BomMaterialSnapshots     ConfigurationSnapshots     CoProductPriceSnapshots     CoProductSnapshots     CostRuleSnapshots     CustomerRankSnapshots     CycleFrequencySnapshots     CycleTypes     CycleTypeSnapshots     CycleUtilisationSnapshots     ExpandedMasterRouteSnapshots     ExternalAllocationSnapshots     ForecastBodySnapshots     HoldingCostSnapshots     Indicatives     InitialSourceSnapshots     InitialSourceSourceSnapshots     InventorySnapshots     LiveAllocationData     LiveAllocationStatData     MachineInformation     MandatorySnpItemSnapshots     MasterRouteSnapshots     MaterialRunsForPlan     OldSNPUnallocatedItemDetails     OrderOperationsForPlan     OrderOperationSnapshots     ProductionPlans     ProductionRateSnapshots     ProjectedInventory     ProjectedInventoryData     SafetyStockSnapshots     ScenarioActionParameters     ScenarioActions     ScenarioAnalysisSnapshots     ScenarioPeriodSnapshots     Scenarios     ScenarioSessions     SiteInventorySnapshots     SnapshotAllocationData     SnapshotTableInfos     SNOAllOrderSnapshots     SNOCustomersData     SNODemands     SNOForecastData     SNOInventoryCostData     SNOItemCoefs     SNOItems     SNOItemsShort     SNOMaterialCoefs     SNOPreNettingAllocations     SNOSFGInventoryData     SNOSolutionTempData     SNPEdges     SNPInventorySnapshots     SNPMaterialRunSnapshots     SNPProductionPlanSnapshots     SNPUnallocatedData     SNPUnallocatedItemDetails     SNPUnallocatedItems     SNPUnallocatedItems2     SNPWorkCentreFixedGrades     SourcingAllocation     StageAllocations     StageAllocationSources     TimeEfficiencySnapshots     TransportRouteSnapshots     WorkCentreParameterSnapshots     WorkCentreShutSnapshots
Master Planning  Temporary     IntraSiteTimeData     SAInventorySourcingData     SASiteInventoryData     SASourcingData     SATransportationData     ScenarioComparisonData     SNOSFGtoFGMapData     SNOSKUWeeklyData     TransportationAllocationsData
Reference  Reference     FilterBasedRules     SkuComments
Replenishment       ReplenishmentRestrictions
Replenishment  Order generation     CombinedRunCapacity     LatestGeneratedInventories     OrdersForNetting     ReplenishedCustomerSKU     ReplenishedPoints     ReplenishedSKU     ReplenishedSubstitutedSku     SourceRunMaterials     SourceRuns
Replenishment  Order Generation     RPTemporaryOrders
Replenishment  Replenishment     AdditionalProperties     AdjustedConsignmentOrdersData     CustomerOrdersFromStock     Deliveries     DeliveryStatuses     EntitiesForExternalSystem     GroupedSKU     Inventories     InventoryData     InventoryProfiles     JourneyRoutes     Journeys     MasterRoutes     NeedRebuildProfiles     OperationPredecessors     OperationProperties     OptStudioMessages     OrderBookDeliveries     OrderBookInventories     OrderBooks     OrderBookTypes     OrderInformation     OrderInformationCategories     OrderInformationItems     OrderLineProperties     OrderLines     OrderLinesForSplit     OrderLineStatuses     OrderOperationMaterials     OrderOperations     OrderOperationStatuses     PasteOrdersData     ProductionUpdates     Reasons     RebalancedOrderLines     RebalancedStock     RemainingOrdersData     RemovedOrderLineEntities     ReplenishedCustomerDemands     ReplenishmentReports     RPTemporarySTOOrders     RsoDemands     RsoPropertySets     RsoScenarios     RsoStockSizes     SKULeadTimes     StagedInventoryProfiles     SupplierInventories     TargetSystems     TempConsignmentOrdersData     TransportMethods     TransportRouteChains     TransportRoutePaths     TransportRoutes     TransportTimeTable     UploadedConsignmentOrders     WarehouseConsumption
Replenishment  Temporary     CampaignGraphData     ConsignmentOrderForSendData     ConsignmentOrdersData     CreateRealInventoryData     CustomersForWorkcentreData     InventoryProfilesData     ListOrdersData     OrderMaintenanceData     OrdersPerRunData     RealInventoryProfilesData     ReservationStockSKUData     SMIInventoryData     StockMonitoringData     StockReservationData
Replenishment  Temporary table     InnerPointForecast
Replenishment  Temptorary table     InnerPointHistory
Reports  Access rights     HiddenSharedReports     RolesDataSources
Reports  Reports     DataSourceFields     DataSourceFilters     DataSources     ReportFilterEntries     ReportFilters
Source Selection  Temporary table     WorkcentreCampaignRunData
Widgest  Temporary     WidgetGraphData
ActiveProcessStatusesViewAlternateMaterialsIplanViewAvailableWidgetsIPlanViewAverageGradePricesIPlanViewCurrenciesIPlanViewCustomerRanksIPlanViewDataSourcesIPlanViewDemandBalanceIPlanViewEndCustomerLevelsIPlanViewEndUsePropertiesIPlanViewEV#AllocationBodiesEV#AllSiteMaterialUSagesEV#ArchivedForecastBodiesEV#BSOInputEV#CarriedForecastEV#CarriedForecastNoSuperEV#ConsignmentSkuEV#CustomerReplenishedDemandEV#DailyForecastDistributionEV#ExpandedPricesEV#FixedSourceSnapshotsEV#ForecastBodiesEV#ForecastBodiesNoSuperEV#ForecastHistoryEV#ForecastHistoryNoSuperEV#ForecastUsedHistoryEV#ForecastUsedHistoryNoSuperEV#InnerPointForecastEV#InnerPointHistoryEV#InventoriesEV#InventoryProfilesEV#InventorySnapshotsEV#MaterialPropertiesEV#MaterialRunsEV#MaterialSupercessionsEV#MaterialUnitsEV#OrderLinesEV#RealInventoryProfilesEV#ReplenishedSubstitutedSkuEV#RequestedInventoryProfilesEV#RPCustomerDemandNoSuperEV#RPSourceRunsEV#SelectiveDataEV#SiteMaterialUSagesEV#SNODemandsEV#SNOForecastEV#SNOPrenettingAllocationsEV#SnpItemsEV#SNPLIndicativesEV#SNPLOpeningEV#SNPLOrdersEV#SNPLRunCapacityEV#SNPLTotalEV#SourceListsEV#SourceRunsRequestedDateEV#SourcingAllocationEV#supersededopeningprofilesEV#TentativeOrderLinesEV#TransportTimeTableEV#UsageHistoriesEV#UsageHistoriesNoSuperEV#WarehouseSkuEV#WeeklyForecastBodiesEV#WorkcentreTimeTableEV#WrongConsignmentCustomerEV#WrongConsignmentSkuEV#WrongSourceListsEVC#OverloadedStocksEVC#SourcePriorityDatesEVC#StockViolationsEVC#StockViolationsRunsExcludedSAMaterialsIPlanViewExcludedSKUFromSAIPlanViewExpandedEndUseSKUIPlanViewFinishingLinesViewFinishingWarehousesViewForecastMethodsIPlanViewGeneratedReplenishedOrdersViewGradeCostsIPlanViewGridsIPlanViewGroupedConsignmentSKUIPlanViewHierarchyLevelsIPlanViewIE#MaterialsIE#OrderLinesIE#SkuIE#SupercessionRulesIH#AllMaterialSupercessionsIH#AllMaterialUnitsIH#AllocationBodiesIH#AllocationForNettingIH#AllocationReasonsIH#AreaPageActionsIH#BaseUnitsIH#BOMMaterialsIH#BomSkuIH#BSODemandAnalysisIH#BSOGenerationPeriodIH#BSOGroupingPropertiesIH#BSOInputIH#BSOProgramsIH#BundlesIH#CalendarDailyCoefsIH#CalendarWeeklyCoefsIH#CalendarWeekMonthSourcesIH#CompanyGradeSafetyStockIH#CompanySafetyStocksIH#ConfigurationConversionsIH#ConfigurationOperationsIH#ConfigurationSourcesIH#ConsumptionProfilesIH#ConvertedExchangeRatesIH#CoProductListsIH#CustomerAdditiveConsumptionIH#CustomerEndConsumptionIH#CustomerSkuCalendarsIH#CustomerSkusIH#CustomerSourcePrioritiesIH#CycleAvailableDurationIH#CycleFixedPeriodsIH#CycleProductionPeriodsIH#CycleTypeMaterialsIH#CycleTypesIH#CycleUtilisationIH#DailyAllocationDistributionIH#DailyDemandDistributionIH#DailyForecastDistributionIH#DailyRangeIH#DataSourceFieldsIH#DefaultOperationTypesIH#DefaultParametersIH#DefaultWeeklyCoefsIH#DerivedCharacteristicsIH#DerivedRulesSkuIH#DetailsDescriptionIH#DetailsEndCustomerLocationIH#DetailsEndUseIH#DetailsHierarchyIH#DetailsLocationIH#DetailsMaterialIH#DetailsPropertyValueIH#DetailsSkuIH#EndCustomerHierarchiesIH#EndPointSkuPortionsIH#EndPointSkuPortions2IH#EOrderingOrderLinesIH#EOTOrderLinesIH#ExchangeRatesIH#ExpandedDetailsIH#ExpandedHierarchiesIH#ExpandedHierarchyDetailsIH#ExpandedLocationsIH#ExpandedPricesIH#ExpandedPropertiesIH#ExpandedPropertyValuesIH#FinForecastBudgetsIH#FlatForecastChangeDetailsIH#FlatForecastChangesIH#FlatSkuIH#ForecastBodiesIH#ForecastBudgetsIH#ForecastChangeDetailsIH#ForecastedLocationsIH#ForecastedPricesIH#ForecastOperationsIH#ForecastRangeValuesIH#ForecastReasonsIH#ForecastsIH#ForecastSampleMethodsIH#GridColumnsIH#GroupedProductRouteStagesIH#GroupedReplenishedSkuIH#GroupedSkuIH#HierarchyPropertyDetailsIH#IdealProfilesIH#IdenticalConfigurationsIH#InitialSourceRulesIH#InitialSourceRuleSourcesIH#InitialSourcesIH#InventoriesIH#InventoryProfilesIH#JourneysIH#LastDDQLogIH#LastForecastLogsIH#LastProcessLogsIH#LastReplenishmentLogsIH#LastReplenishmentTraceLogsIH#LastSupercessionsIH#LatestInventoriesIH#LatestSupplierInventoriesIH#LiveOptimizedRunsIH#LiveProductionPlansIH#LocationMasterRoutesIH#LocationsIH#LocationStockStatusIH#MainWarehousesIH#MappedCharacteristicsIH#MappedFieldsIH#MasterRoutesIH#MaterialCharacteristicsIH#MaterialConfigurationsIH#MaterialHashCodesIH#MaterialRunCapacitiesIH#MaterialRunDurationsIH#MaterialRunsIH#MaterialsIH#MaterialSubstitutionsIH#MaterialSupercessionsIH#MaterialTypeRoundingUnitsIH#ModelCharacteristicsIH#MonthlyAllSupersededHistoryIH#MonthlyExchangeRatesIH#MonthlyPricesIH#MonthlySupersededHistoryIH#MonthlyUsageHistoriesIH#NavigationTasksIH#NegativeDemandCalendarDaysIH#NegativeDemandWarehousesIH#NegativeDemandWorkingDaysIH#NominalCostsIH#NormalSkuStockStatusIH#OpeningRealProfilesIH#OrderDurationIH#OrderInformationCategoriesIH#OrderInformationConfigIH#OrderInquiryPricesIH#OrderLineDeliveryWeightsIH#OrderLineReasonsIH#OrderLinesIH#OrderOperationDurationIH#OrderOperationMovementsIH#OrderOperationsIH#OrdersForExternalSystemIH#OverrideWorkCentresIH#PageParametersIH#PaperMachinesIH#PriceParametersIH#PricesIH#ProcessLogsIH#ProductCharacteristicsIH#ProductCostsIH#ProductionConfigurationsIH#ProductionPlanIH#ProductionRatesIH#ProductionUtilisationIH#ProductionWorkcentresIH#ProductRoutesIH#ProductRouteStagesIH#ProductSiteCostsIH#PublishedReportsIH#RebalancedOrderLinesIH#ReplacedByLocationIH#ReplacedLocationsIH#ReplenishedCustomerDemandsIH#ReplenishedCustomerSkuIH#ReplenishedPointsIH#ReplenishedSkuIH#ReplenishedsubstitutedskuIH#ReplenishmentHorizonSKUIH#ReplenishmentParametersIH#ReplenishmentTraceIH#ReplenishmentTraceLogIH#ReplenishmentTraceLogsIH#ReportFilterEntriesIH#RequestedDateProfileIH#RunAvailableCapacitiesIH#RunAvailableDurationIH#RunCapacityByPeriodsIH#RunDurationByPeriodIH#RunInventoryProfilesIH#RunMaterialsIH#RunPropertiesIH#SAGradePropertyMapIH#SAInitialSourcesIH#SAInitialSourceSourcesIH#SAWeeklyCoefsIH#ScenarioPaperMachinesIH#ScenarioPeriodSnapshotsIH#ScenarioRatesIH#ScenariosIH#ScenarioSessionsIH#ScenarioSourcePeriodsIH#ScenarioWorkcentresIH#SimpleSkusIH#SimpleWarehouseSkusIH#SiteMonthlyHistoriesIH#SitesIH#SiteSupersededHistoriesIH#SiteSupersededOrdersIH#SiteTransportPeriodsIH#SiteWorkcentreOperationsIH#SiteWorkcentresIH#SkuIH#SkuRoundUnitsIH#SkusIH#SkuStockStatusIH#SkuWarehouseLocationsIH#SkuWorkingDaysIH#SNPProductionConfigurationsIH#SolutionTempDataIH#SourcePrioritiesIH#SourcePriorityRulesIH#SourceRunProductsIH#SplitMaterialRunsIH#StockMonitoringSkuIH#StockMovementsIH#StockStatesIH#SuccessReplenishmentLogsIH#SupersededOpeningProfilesIH#SupersededOrderLinesIH#SupersededOrdersIH#SupersededRealProfilesIH#SupersededSkuStockStatusIH#TradingDaysIH#TransportLocationLocationsIH#TransportLocationsIH#TransportMethodsForEdgeIH#TransportRoutesIH#TransposedMaterialsIH#UsedExternalTrendsIH#UserPageParametersIH#UserParametersIH#UserPermissionsIH#UserReportsIH#ValidOperationSourcesIH#ValidSourcesIH#WarehouseCapacitiesIH#WarehouseConsumptionIH#WarehousesIH#WastedTableSpaceIH#WeeklyUsageHistoriesIH#WeightUnitsIH#WHSkusIH#WHStockMonitoringIH#WorkCentreDestinationsIH#WorkcentreParametersIH#WorkcentresIH_ForecastSnapshotsIH_NavigationsIHBS#CorrespondRunsIHBS#GradePropertiesIHBS#HandlingDelayIHBS#NextAllocationBodiesIHBS#RunOutputDelayIHDP#ConvertLocationsIHDP#ConvertSkuIHDP#ConvertSkuEVGIHDP#ConvertSkuOnSameLocationIHDP#DayForSnapshotIHDP#DaySystemForecastIHDP#ForecastAccuracyIHDP#ForecastChangeDetailsIHDP#ForecastMethodsSkuIHDP#HistoryAndOrdersPricesIHDP#MonthForSnapshotIHDP#MonthSystemForecastIHDP#OrderLinePricesIHDP#OrderWorkingDaysIHDP#QuarterForSnapshotIHDP#QuarterSystemForecastIHDP#SourcingDatesIHDP#UsageHistoryPricesIHDP#WeekForSnapshotIHDP#WeeklyForecastBodiesIHDP#WeeklyForecastBudgetsIHDP#WeeklyForecastSnapshotsIHDP#WeekMonth2ForSnapshotIHDP#WeekMonth2SystemForecastIHDP#WeekMonthForSnapshotIHDP#WeekMonthSystemForecastIHDP#WeekSystemForecastIHForecastSnapshotsIHL#OrderOperationsIHMP#AllocationIHMP#AllocationIndicativesIHMP#MonthlySnapshotAllocationIHMP#SkuWorkcentrePairs2IHRP#SourceRunCombinedCapacityIHSA#AllocationMTDIHSA#AllocationsVsOrdersIHSA#AllocationVsHistoryIHSA#CoProductAllocationsIHSA#CoProductCoefsIHSA#CycleCapacityIHSA#CycleFixedPeriodsIHSA#CycleFrequencyIHSA#CycleTypesIHSA#CycleUtilisationIHSA#DefaultOperationsIHSA#DefaultProductRoutesIHSA#IgnoredSmallDemandsIHSA#IndicativesMTDIHSA#IndicativesVsOrdersIHSA#MaterialRunSnapshotsIHSA#NettedLiveAllocationIHSA#OrderOperationsIHSA#ProductionConfigurationsIHSA#ProductionPlanSnapshotsIHSA#ProductionUtilisationIHSA#ReplenishedMaterialsIHSA#ScenarioPeriodsIHSA#SiteMapeIHSA#SnapshotPeriodTypesIHSA#SnapshotTablesIHSA#SNODemandsIHSA#SNPItemConfigurationsIHSA#SolutionTempDataIHSA#SourcingAllocationIHSA#SourcingAllocation2IHSA#UnallocatedItemDetailsIHSA#WeeklyMonthPeriodsIHSA#WorkcentreShutSnapshotsIM$CharacteristicsIM$EndUsePropertiesIM$HierarchyLevelsIM$ProductPropertiesIM$ProductTypesIM$PropertiesIM$SkuPropertiesIM$WorkCentreTypesIRH#ScenarioAllocationIT#ActionsIT#CurrenciesIT#CustomerRanksIT#DataSourceFieldsIT#EventMessagesIT#ForecastMethodsIT#NavigationsIT#OrderLineReasonsIT#PageParametersIT#PagesIT#ProcessPartsIT#RolesIT#SafetyStockMethodsIT#TasksIT#UnitsIV#CostRulesIV#DataSourceFiltersIV#HierarchiesIV#MaterialPropertiesIV#MAterialsIV#PriceRulesIV#ProductionRatesIV#PropertyValuesIV#RangePropertiesIV#WorkcentreRangePropertiesIVBS#ActualProductionRatesIVBS#MaterialRunsIVDP#HistoryDataIVDP#HistoryStartDateIVDP#UsageHistoriesIVMP#IndicativesIVMP#LiveAllocationsIVMP#TransportAllocationsIVRP#MaterialRunProductsIVRP#MaterialRunsIVRP#OrderInformationIVRP#OrderLinesIVRP#OrderOperationsIVSA#DemandAllocationsIVSA#PaperMachineCapacitiesIVSA#PMCapacitiesIVSA#ProductionRatesIVSA#SourcingAllocationsIVSA#TransportAllocationsIVSN#CustomerSourcePrioritiesIVSN#SiteSourcePrioritiesIVT#InventoriesIVT#InventoryProfilesIVT#OrderLinesIVT#RealInventoryProfilesIVT#SkusIVT#TentativeOrderLinesJourneyRoutsIPlanViewJourneysIPlanViewJourneyViewLocationsIPlanViewMaterialRunsViewMaterialsIPlanViewMaterialTypesIPlanViewMaterialUnitsIPlanViewOrderInventoryIPlanViewOrderLineReasonsIPlanViewPackageVersionsViewProcessStatusesIPlanViewPropertiesIPlanViewRealInventoryProfilesIPlanViewReplenishmentChainsViewSafetyStockMethodsIPlanViewScenarioAllocationIPlanViewSemiFinishingWarehousesViewSessionParametersIPlanViewSitePropertiesIPlanViewSkuPropertiesIPlanViewSKUViewSKUWorkcentresDFIPlanViewSourcePrioritiesViewSourcePriorityViewStockLocationSKUIPlanViewSystemDashboardsIPlanViewTransportRoutesViewUnitsIPlanViewUploadTemplateIPlanViewUserPermissionsIPlanViewUserWidgetsIPlanViewWeeklyMonthMapIPlanView
Types
name oracle mssql description array subtype
Char CHAR(1) CHAR(1) one char
Date Date DateTime date and time yes
DoubleDouble NUMBER(21,20) DECIMAL(21,20) double number with big precision yes yes
DoubleFloat NUMBER(23,8) DECIMAL(23,8) double number yes yes
Float NUMBER(23,4) DECIMAL(23,4) real number yes yes
HugeString VARCHAR2(4000 char) Varchar(4000) huge string yes yes
Identity NUMBER(10) DECIMAL(10) Identity yes yes
Integer NUMBER(5) DECIMAL(5) int yes yes
LongestString VARCHAR2(2000 char) Varchar(2000) longest string yes yes
LongString VARCHAR2(255 char) Varchar(255) long string yes yes
NChar NCHAR(1) NCHAR(1) one unicode char
NLongestString NVARCHAR2(2000) NVarchar(850) longest unicode string
NLongString NVARCHAR2(255) NVarchar(255) long unicode string
NShortString NVARCHAR2(40) NVarchar(40) short unicode string
NString NVARCHAR2(80) NVarchar(80) unicode string
Percent NUMBER(5,2) DECIMAL(5,2) percent yes yes
RealIdentity NUMBER(10) DECIMAL(10) IDENTITY(1, 1) Identity
ShortString VARCHAR2(40 char) Varchar(40) short string yes yes
String VARCHAR2(80 char) Varchar(80) string yes yes
Text Clob Long raw character data
TimeStamp TimeStamp TimeStamp Time stamp
top
Database Types
AllocationArray TABLE AllocationRecord
top
AllocationRecord OBJECT
name type description
SiteMaterialUsageId NUMBER(10)
WorkcentreId NUMBER(10)
GroupId NUMBER(10)
OrderNo NUMBER(10)
Dividend DoubleFloat
Divisor DoubleFloat
SummaryFields VARCHAR2(4000 char)
CommentLink VARCHAR2(4000 char)
top
DDQ_Confirm_Reply_H_List_T TABLE DDQ_Confirm_Reply_H_T
top
DDQ_Confirm_Reply_H_T OBJECT
name type description
HeaderCode VARCHAR2(40) Inquiry header number
LineList DDQ_Confirm_Reply_L_List_T List of lines
top
DDQ_Confirm_Reply_L_List_T TABLE DDQ_Confirm_Reply_L_T
top
DDQ_Confirm_Reply_L_T OBJECT
name type description
LineCode VARCHAR2(80) Line number
OldLineCode VARCHAR2(80) Old line number
SolutionNumber NUMBER(2) Number of solution
ReturnCode VARCHAR2(20) Return message
top
DDQ_Confirm_Reply_T OBJECT
name type description
RequestId VARCHAR2(40) Request confirmation ID
Recipient VARCHAR2(40) The sender of the request
HeaderList DDQ_Confirm_Reply_H_List_T The list of headers
top
DDQ_Confirm_Request_H_List_T TABLE DDQ_Confirm_Request_H_T
top
DDQ_Confirm_Request_H_T OBJECT
name type description
HeaderCode VARCHAR2(40) Inquiry header number
OldHeaderCode VARCHAR2(40) Inquiry old header number
LineList DDQ_Confirm_Request_L_List_T List of lines
top
DDQ_Confirm_Request_L_List_T TABLE DDQ_Confirm_Request_L_T
top
DDQ_Confirm_Request_L_T OBJECT
name type description
LineCode VARCHAR2(80) Inquiry line number
OldLineCode VARCHAR2(80) Inquiry old line number
SolutionNumber NUMBER(2) Number of solution
Status VARCHAR2(20) COMMIT/ROLLBACK
top
DDQ_Confirm_Request_T OBJECT
name type description
RequestId VARCHAR2(40) Confirmation identifier
Sender VARCHAR2(40) Unique identifier of the client
HeaderList DDQ_Confirm_Request_H_List_T The list of headers
top
DDQ_OperationArray TABLE DDQ_OperationRecord
top
DDQ_OperationRecord OBJECT
name type description
StageNo NUMBER(10)
MaterialRunId NUMBER(10)
WorkCentreId NUMBER(10)
Weight NUMBER(23,4)
OperationTypeId NUMBER(10)
top
DDQ_OrderArray TABLE DDQ_OrderRecord
top
DDQ_OrderRecord OBJECT
name type description
Type VARCHAR2(40)
OrderType VARCHAR2(40)
Weight NUMBER(23,4)
SiteId NUMBER(10)
WorkCentreId NUMBER(10)
StockWorkCentreId NUMBER(10)
DeliveryDate DATE
DespatchDate DATE
JourneyId NUMBER(10)
ConsignmentLocationId NUMBER(10)
Status VARCHAR2(40)
IsConfirmed NUMBER(1)
OperationList DDQ_OperationArray List of operation
top
DDQ_Schedule_Reply_H_List_T TABLE DDQ_Schedule_Reply_H_T
top
DDQ_Schedule_Reply_H_T OBJECT
name type description
HeaderCode VARCHAR2(40) Inquiry header number
WorkcentreSourceCode VARCHAR2(80) Workcentre where
PossibleQuantity NUMBER(23,4) Possible Quantity on requested date
LineList DDQ_Schedule_Reply_L_List_T The list of lines
top
DDQ_Schedule_Reply_L_List_T TABLE DDQ_Schedule_Reply_L_T
top
DDQ_Schedule_Reply_L_T OBJECT
name type description
LineCode VARCHAR2(80) Line code
SolutionNumber NUMBER(2) Solution number
Status VARCHAR2(20) Confirmed/Information/Reservation
DeliveryDate DATE Delivery date
DispatchDate DATE Dispatch date
Quantity NUMBER(23,4) Quantity
Unit VARCHAR2(80) Unit name
Weight NUMBER(23,4) Weight
ProductCode VARCHAR2(80) Product code
WareHouseCode VARCHAR2(80) Stock warehouse code
InitialPaperMachine VARCHAR2(80) Initial paper machine ( The one that was selected by the DDQ engine)
ReturnStatus VARCHAR2(20) Failure/Success/Partial Success
ReturnCode VARCHAR2(40) Return error code
OperationList DDQ_Schedule_Reply_O_List_T List of operations
JourneyCode VARCHAR2(80) Code of Journey
ConsignmentLocation VARCHAR2(40) To indicate the consignment location code, if consignment stock is used by the search
top
DDQ_Schedule_Reply_O_List_T TABLE DDQ_Schedule_Reply_O_T
top
DDQ_Schedule_Reply_O_T OBJECT
name type description
OperationNumber NUMBER(2) Source number, if multiple sources used
WorkCentreCode VARCHAR2(80) Workcentre code
ReservationCode VARCHAR2(40) Reservation order code, if Confirmed=FALSE; order number otherwise
RunEndDate DATE The date when the run finished
BlockCode VARCHAR2(40) Block code
RunCode VARCHAR2(255) Run code
SFGProductCode VARCHAR2(80) The code of the SFG product to use
Quantity NUMBER(23,4) Quantity of the request
Unit VARCHAR2(80) The name of unit
top
DDQ_Schedule_Reply_T OBJECT
name type description
RequestId VARCHAR2(40) Return the RequestID
Recipient VARCHAR2(40) Return the Sender
HeaderList DDQ_Schedule_Reply_H_List_T List of headers
top
DDQ_Schedule_Request_H_Ext_T TABLE DDQ_Schedule_Request_H_T_Ext
top
DDQ_Schedule_Request_H_List_T TABLE DDQ_Schedule_Request_H_T
top
DDQ_Schedule_Request_H_T OBJECT
name type description
HeaderCode VARCHAR2(40) Inquiry header code
OldHeaderCode VARCHAR2(40) Header number of the old order (Which is to be deleted when requoting)
autoCreate NUMBER(1) Create orders instead of inquiry reservations
autoConfirm NUMBER(1) Auto confirm
LineList DDQ_Schedule_Request_L_List_T The list of lines
top
DDQ_Schedule_Request_H_T_Ext OBJECT
name type description
HeaderCode VARCHAR2(40) Inquiry header number
OldHeaderCode VARCHAR2(40) Header number of old Order to be deleted with requote
autoCreate NUMBER(1) Create 'Orders' instead of inquiry reservations
autoConfirm NUMBER(1) Auto confirm
LineList DDQ_Schedule_Request_L_Ext_T List of lines
top
DDQ_Schedule_Request_L_Ext_T TABLE DDQ_Schedule_Request_L_T_Ext
top
DDQ_Schedule_Request_L_List_T TABLE DDQ_Schedule_Request_L_T
top
DDQ_Schedule_Request_L_T OBJECT
name type description
LineCode VARCHAR2(80) Inquiry line number
OldLineCode VARCHAR2(80) Inquiry old line number
LocationCode VARCHAR2(40) I-Plan's unique code of the customer
MultiLine NUMBER(1) A flag (Y/N) - Joined delivery
ProductCode VARCHAR2(80) I-Plan's product code
EndCustomerCode VARCHAR2(40) I-Plan's unique code of the endcustomer
EndUseCode VARCHAR2(40) I-Plan's unique code of the enduse
SFGProductCode VARCHAR2(80) I-Plan's SFG product code to use
RequestDate DATE The date, that the customer requested (can be empty)
LateDays NUMBER(3) The number of days of delay, after which the customer will still accept the order
InquiryMethodCode VARCHAR2(40) Inquiry method code (JIT, JITP, ASAP)
Quantity NUMBER(23,4) Quantity of the request
Unit VARCHAR2(80) The name of unit
TransportMethod VARCHAR2(80) The code of transport method
TypeOfDelivery VARCHAR2(1) A switch: E/A (ex-mill/arrival)
ExpiryDate DATE The date, after which order reservation expires
CheckAllocationMethod VARCHAR2(10) A switch: can be Strict (fail immediately), None or Warn (continue but response will be a partial failure)
TransportAreaCode VARCHAR2(40) Ovveride for the transport area against the location
SourceWarehouseCode VARCHAR2(40) Defines warehouse source. Blank or valid warehouse code
FixSourceAssignment VARCHAR2(80) The order has to be sourced from the specified source (PM)
SourceTypes NUMBER(1) Defines, which types of sources to check
OrderSplit NUMBER(1) A flag (Y/N) - is it allowed to split an order to parts?
SingleSourcing NUMBER(1) A flag (Y/N) - if an order is split, is it allowed to source order parts from different paper machines?
FinishingLock NUMBER(1) A flag (Y/N) - no logic should be applied, but information has to be passed through
UseOpportunisticRuns NUMBER(1) A flag (Y/N) - is it allowed to use opportunistic runs?
PartialDelivery NUMBER(1) A flag (Y/N) - is it allowed to generate partial deliveries?
Quality NUMBER(1) Useup second choice
StartNotBefore DATE Starting date for source search
LoggingLevel NUMBER(3) Determines the level of DDQ process logging. (0-255) 255 - the most extensive logging
DisregardAllocation NUMBER(1) A flag: 1 (On) allows to use PM sources, which do not have any allocation, if normal PM sources search failed
RequestType NUMBER(1) A switch: type of request (0-New, 1-Requote, 2-Delete, 3-Resend, 4-Amend, 5-Accept, 6-Rollback)
JourneyCode VARCHAR2(80) Code of Journey
ConsignmentParameters NUMBER(4) Is required to indicate if consignment stock should be used, and preferences
ConsignmentLocation VARCHAR2(40) Parameter is required to optionally specify a customer’s location code
ReplaceConsignment NUMBER(3) Possible value 000,100,102,110,111,112
ConsignmentOrder NUMBER(3) This indicates that the order will produce consignment inventory.
AllowLateOrders NUMBER(1) A flag (Y/N) - Allow Late Orders
UseInventory NUMBER(1)
UseProjectedInventory NUMBER(1)
UseConsignmenmtInventory NUMBER(1)
UseProduction NUMBER(1)
ReATPRequired NUMBER(1)
SourcingCategories VARCHAR2(255)
AlternateProducts VARCHAR2(255)
top
DDQ_Schedule_Request_L_T_Ext OBJECT
name type description
LineCode VARCHAR2(40) Inquiry line number
OldLineCode VARCHAR2(40) Inquiry old line number
LocationCode VARCHAR2(40) I-Plan's unique code of the customer
MultiLine NUMBER(1) A flag (Y/N) - Joined delivery
ProductCode VARCHAR2(80) I-Plan's product code
EndCustomerCode VARCHAR2(40) I-Plan's unique code of the endcustomer
EndUseCode VARCHAR2(40) I-Plan's unique code of the enduse
SFGProductCode VARCHAR2(80) I-Plan's SFG product code to use
RequestDate DATE The date, that the customer requested (can be empty)
LateDays NUMBER(3) The number of days of delay, after which the customer will still accept the order
InquiryMethodCode VARCHAR2(40) Inquiry method code (JIT, JITP, ASAP)
Quantity NUMBER(23,4) Quantity of the request
Unit VARCHAR2(80) The name of unit
TransportMethod VARCHAR2(80) The code of transport method
TypeOfDelivery VARCHAR2(1) A switch: E/A (ex-mill/arrival)
ExpiryDate DATE The date, after which order reservation expires
CheckAllocationMethod VARCHAR2(10) A switch: can be Strict (fail immediately), None or Warn (continue but response will be a partial failure)
TransportAreaCode VARCHAR2(40) Ovveride for the transport area against the location
FixSourceAssignment VARCHAR2(80) The order has to be sourced from the specified source (PM)
SourceTypes NUMBER(1) Defines, which types of sources to check
OrderSplit NUMBER(1) A flag (Y/N) - is it allowed to split an order to parts?
SingleSourcing NUMBER(1) A flag (Y/N) - if an order is split, is it allowed to source order parts from different paper machines?
FinishingLock NUMBER(1) A flag (Y/N) - no logic should be applied, but information has to be passed through
UseOpportunisticRuns NUMBER(1) A flag (Y/N) - is it allowed to use opportunistic runs?
PartialDelivery NUMBER(1) A flag (Y/N) - is it allowed to generate partial deliveries?
Quality NUMBER(1) Useup second choice
StartNotBefore DATE Starting date for source search
LoggingLevel NUMBER(3) Determines the level of DDQ process logging. (0-255) 255 - the most extensive logging
DisregardAllocation NUMBER(1) A flag: 1 (On) allows to use PM sources, which do not have any allocation, if normal PM sources search failed
RequestType NUMBER(1) A switch: type of request (0-New, 1-Requote, 2-Delete, 3-Resend, 4-Amend, 5-Accept, 6-Rollback)
ReferReasonCode VARCHAR2(80) Reason code
ReferReasonDescription VARCHAR2(255) Reason description
SalesPerson VARCHAR2(40) Sales person
AvailableDate DATE Available date
top
DDQ_Schedule_Request_T OBJECT
name type description
RequestId VARCHAR2(40) Request identifier
Sender VARCHAR2(40) Unique indentifier of the client
HeaderList DDQ_Schedule_Request_H_List_T The list of headers
top
DDQ_Schedule_Request_T_Ext OBJECT
name type description
RequestId VARCHAR2(40) Request identifier
Sender VARCHAR2(40) Client's unique identifier
HeaderList DDQ_Schedule_Request_H_Ext_T List of headers
top
ForecastCollaborationArray TABLE ForecastCollaborationRecord
top
ForecastCollaborationRecord OBJECT
name type description
GroupId Identity
DateFrom Date
SystemForecast Float
CustomerForecast Float
FinalForecast Float
ForecastAllocation Float
IsWorking Integer
ForecastStatusId Integer
EditablePriceFlag Integer
Revenue Float
TotalCost DoubleFloat
TotalValueAdd Float
NominalCost DoubleFloat
ValueAdd Float
SystemPrice Float
ForecastedPrice Float
NominalCostAdjustment Float
ValueAddAdjustment Float
OriginalNCAdjustment Float
OriginalVAAdjustment Float
OriginalPrice Float
top
ForecastEntryArray TABLE ForecastEntryRecord
top
ForecastEntryRecord OBJECT
name type description
SiteMaterialUsageId Identity
ForecastStatusId Identity
CurrencyId Identity
CalendarId Identity
Dividend DoubleFloat
Divisor DoubleFloat
top
ForecastItemArray TABLE ForecastItemObject
top
ForecastItemObject OBJECT
name type description
SiteMaterialUsageId Identity
Dividend Float
Divisor Float
top
ForecastSnapshotArray TABLE ForecastSnapshotRecord
top
ForecastSnapshotRecord OBJECT
name type description
GroupId Identity
DateFrom Date
FinalForecast Float
Unallocated Float
ForecastStatusId Integer
EditablePriceFlag Integer
Revenue Float
UnallocatedRevenue Float
TotalCost DoubleFloat
UnallocatedTotalCost Float
TotalValueAdd Float
UnallocatedValueAdd Float
NominalCost DoubleFloat
ValueAdd Float
SystemPrice Float
ForecastedPrice Float
NominalCostAdjustment Float
ValueAddAdjustment Float
OriginalNCAdjustment Float
OriginalVAAdjustment Float
OriginalPrice Float
top
myConsignmentSkuArray TABLE myConsignmentSkuRecord
top
myConsignmentSkuRecord OBJECT
name type description
SiteMaterialUsageId NUMBER(10)
ConsignmentLocationId NUMBER(10)
top
myDataArray TABLE myDataRecord
top
myDataRecord OBJECT
name type description
Id Identity
DateFrom Date
Value Float
top
myDateArray TABLE DATE
top
myDateDemandArray TABLE myDateDemandRecord
top
myDateDemandRecord OBJECT
name type description
GroupId NUMBER(10)
DateFrom DATE
DateFromMonth DATE
PlacedDateFrom DATE
PlacedDateFromMonth DATE
top
myDoubleFloatArray TABLE NUMBER(23,8)
top
myFieldPairArray TABLE myFieldPairRecord
top
myFieldPairRecord OBJECT
name type description
Name VARCHAR2(80)
Value VARCHAR2(80)
top
myFloatArray TABLE NUMBER(23,4)
top
myForecastArray TABLE myForecastRecord
top
myForecastRecord OBJECT
name type description
SiteMaterialUsageId NUMBER(10)
ForecastStatusId NUMBER(10)
GroupId NUMBER(10)
CurrencyId NUMBER(10)
CommentLink VARCHAR2(4000)
Dividend NUMBER(23,8)
Divisor NUMBER(23,8)
Status NUMBER(5)
top
myFormatStringArray TABLE myFormatStringRecord
top
myFormatStringRecord OBJECT
name type description
Name VARCHAR2(80)
Value VARCHAR2(4000)
top
myFourthArray TABLE myFourthRecord
top
myFourthRecord OBJECT
name type description
Id1 NUMBER(10)
Id2 NUMBER(10)
Id3 NUMBER(10)
Id4 NUMBER(10)
String VARCHAR2(4000 char)
Dividend NUMBER(23,8)
Divisor NUMBER(23,8)
top
myFullSkuArray TABLE myFullSkuRecord
top
myFullSkuRecord OBJECT
name type description
SiteMaterialUsageId NUMBER(10)
ConsignmentLocationId NUMBER(10)
OrderNo NUMBER(10)
Dividend NUMBER(23,8)
Divisor NUMBER(23,8)
top
myIdentityArray TABLE NUMBER(10)
top
myIdentityDateArray TABLE myIdentityDateRecord
top
myIdentityDateRecord OBJECT
name type description
Id NUMBER(10)
DateFrom Date
top
myIdentityFloatArray TABLE myIdentityFloatRecord
top
myIdentityFloatRecord OBJECT
name type description
Id NUMBER(10)
Dividend NUMBER(23,8)
Divisor NUMBER(23,8)
top
myIdentityGroupedArray TABLE myIdentityGroupedRecord
top
myIdentityGroupedRecord OBJECT
name type description
Id NUMBER(10)
GroupId NUMBER(10)
Dividend NUMBER(23,8)
Divisor NUMBER(23,8)
top
myLongestStringArray TABLE LongestString
top
myMovementArray TABLE myMovementRecord
top
myMovementRecord OBJECT
name type description
Id NUMBER(10) Delivery or order line id
Key VARCHAR2(80) delivery or order line
SkuKey VARCHAR2(80) delivery or order line
SourceSkuKey VARCHAR2(80) delivery or order line
DateFrom Date
OrdersIn NUMBER(23,4)
OrdersOut NUMBER(23,4)
MovementType VARCHAR2(80) delivery or order line
IsFirm NUMBER(1) Tentative or firm orders
IsForecasted NUMBER(1) Is Forecasted
IsArrived NUMBER(1) Is Arrived
top
myOnHandInventoryArray TABLE myOnHandInventoryRecord
top
myOnHandInventoryRecord OBJECT
name type description
SkuKey VARCHAR2(80) Sku Key
DateFrom Date
Opening Float
ActualIn Float incoming production updates and incoming delivered deliveries
ActualOut Float outgoing InTransit and Delivered deliveries
OnHandStock Float Available on-hand stock
OrdersIn Float
OrdersOut Float
AllocatedStock Float
Closing Float
MinClosing Float
top
myOnHandMovementArray TABLE myOnHandMovementRecord
top
myOnHandMovementRecord OBJECT
name type description
SkuKey VARCHAR2(80) SkuKey
DateFrom Date
Opening NUMBER(23,4)
OrdersIn NUMBER(23,4) Planned firm incoming orders and deliveries
OrdersOut NUMBER(23,4) Planned firm outgoing order and deliveries
AllocatedStock NUMBER(23,4) Allocated stock to orders
MovementId NUMBER(10) Delivery/orderLine/OrderOperation/ProductionUpdate id
MovementType VARCHAR2(80) Opening/AllocatedStock/Delivery/orderLine/OrderOperation/ProductionUpdate
MovementStatus ShortString Can be: Actual - for production updates and in-transit and delivered deliveries, or Firm or Tentative
OrderLineId NUMBER(10) Order Line Id
DeliveryId NUMBER(10) Delivery Id
OrderOperationId NUMBER(10) Order Operation Id
Comments VARCHAR2(2000) Comments
top
myPairArray TABLE myPairRecord
top
myPairDateArray TABLE myPairDateRec
top
myPairDateRec OBJECT
name type description
DateFromIW DATE
DateFromMonth DATE
top
myPairRecord OBJECT
name type description
Id NUMBER(10)
ParentId NUMBER(10)
top
myReportFieldArray TABLE myReportFieldRecord
top
myReportFieldRecord OBJECT
name type description
Name VARCHAR2(80)
Value VARCHAR2(80)
DataType VARCHAR2(80)
top
mySkuArray TABLE mySkuRecord
top
mySkuRecord OBJECT
name type description
SiteMaterialUsageId Identity
EndUseId Identity
LocationId Identity
MaterialId Identity
top
mySourcingAllocationArray TABLE mySourcingAllocationRecord
top
mySourcingAllocationRecord OBJECT
name type description
SnpItemId Identity
CoProductId Identity
SourcePropertyValueId Identity
WorkcentreId Identity
SiteId Identity
HierarchyId Identity
Id Identity
SummaryFields HugeString
top
myStringArray TABLE String
top
myStringPairArray TABLE myStringPairRecord
top
myStringPairRecord OBJECT
name type description
Id NUMBER(10)
Parent VARCHAR2(80)
top
myTripleArray TABLE myTripleRecord
top
myTripleRecord OBJECT
name type description
Id1 NUMBER(10)
Id2 NUMBER(10)
Id3 NUMBER(10)
String VARCHAR2(4000)
Dividend NUMBER(23,8)
Divisor NUMBER(23,8)
top
myUnitRecord OBJECT
name type description
UnitId Identity
Dividend DoubleFloat
Divisor DoubleFloat
top
ParameterArray TABLE HugeString
top
RevisedAllocationEntryArray TABLE RevisedAllocationEntryRecord
top
RevisedAllocationEntryRecord OBJECT
name type description
SiteMaterialUsageId Identity
WorkCentreId Identity
OrderNo Identity
Dividend DoubleFloat
Divisor DoubleFloat
top
SnoItemArray TABLE SnoItemRecord
top
SnoItemRecord OBJECT
name type description
SnoItemId Identity
SummaryFields VARCHAR2(4000)
GroupId Identity
top
StockMonitoringArray TABLE StockMonitoringRecord
top
StockMonitoringRecord OBJECT
name type description
SiteMaterialUsageId NUMBER(10)
ConsignmentLocationId NUMBER(10)
LocationId NUMBER(10)
IsSubstituted NUMBER(5)
SkuKey VARCHAR2(4000)
OrderNo NUMBER(10)
Dividend NUMBER(23,8)
Divisor NUMBER(23,8)
Replenished NUMBER(10)
top
Tables
AccessWorkCentres Core
Core
The table stores infomation about workcentres assignment to users
name type identity null description
Id Identity yes no Identity
UserId Identity no User ID
WorkCentreId Identity no Workcentre ID
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Actions Core
Access rights
The table stores actions defined in the system
name type identity null description
Id Identity yes no Identity
ActionName String no Action name
ActionDescription String no Action description
ActionHint LongString yes Action hint (explanation)
Title String yes Action title
GridName LongString yes Grid name
GridColumnName LongestString yes Grid column name
GridAction String no Grid action - none, page, row
IsDefault Integer no A flag: is this a default action?
MultiSelect Integer no A flag: action allowed for several rows in the grid
PageId Identity yes Page ID
Icon String yes Icon name
GroupName String yes Group name for actions in toolbar
OverrideActionId Identity yes OverrideActionId
ParentActionId Identity yes Parent ActionId
IsVisible Integer no A flag: is this a visible action?
IsDevMode Integer no A flag: is this a dev mode action?
IsEtc Integer no A flag: is this an "et cetera" action? (shown in a dropdown)
IsConfigurable Integer no Whether the action can be configured through Page Parameters
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
AdditionalProperties Replenishment
Replenishment
The table stores information additional properties for product type or product
name type identity null description
Id Identity yes no Identity
MaterialTypeId Identity yes Material type ID
MaterialId Identity yes Material ID
Type String no
Code ShortString no
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
AdjustedConsignmentOrdersData Replenishment
Replenishment
The table is used for storing Adjusted Consignment Orders
name type identity null description
OperatorUserId Identity no A reference to the Users table
SiteMaterialUsageId Identity no A reference to SiteMaterialUsages
WorkcentreId Identity yes Workcentre ID of the paper machine
SiteId Identity yes Site Id of the paper machine
DateFrom Date no Date from
OpeningNonForecasted Float no Opening non forecasted weight
OpeningForecasted Float no Opening forecasted weight
top
AllocationBodies Master Planning
Master Planning
The table stores weekly allocation for SKUs
name type identity null description
Id Identity yes no Identity
DeliveryWeek Date yes Delivery Week
DeliveryMonth Date yes Delivery Month
SourceWeek Date yes Source Week
SourceMonth Date yes Source Month
SiteMaterialUsageId Identity no A reference to the corresponding SKU
WorkcentreId Identity no A reference to Workcentres
NonMoveableWeight Float no nonmoveableorders
System Float no Forecast value generated by system
Customer Float no Forecast value edited by customer
Revised Float no Revised Allocation
AllocationId Identity yes Allocation Id (links stages)
StageNo Integer no Stage No
SeqNo Integer no Stage No
IsLastStage Integer no Is Last Stage
OperationTypeId Identity yes Flag
NextOperationTypeId Identity yes Flag
ProductRouteId Identity yes Flag
ConversionFactor Float no Production rate conversion factor
FGPropertyValueId Identity yes Flag
SourceMaterialId Identity yes Source material (from BOM)
MasterRouteId Identity yes Flag
IsWorking Integer no A switch. Possible values: 0 - forecast state unchanged, or the forecast released; 1 - the forecast has been carried from the previous forecast, 2 - the forecast has been modified (edited) )
AllocationChangeId Identity yes Allocation Change id
RevisedAllocationChangeId Identity yes Allocation Change id
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
AllocationBodies2 Master Planning
Master Planning
The table stores weekly allocation for SKUs
name type identity null description
Id Identity yes no Identity
SourceWeek Date yes Source Week
MaterialId Identity no A reference to the corresponding SKU
WorkCentreId Identity no A reference to Workcentres
Orders Float no orders
System Float no Forecast value generated by system
Customer Float no Forecast value edited by customer
AllocationId Identity yes Allocation Id (links stages)
StageNo Integer no Stage No
IsLastStage Integer no Is Last Stage
OperationTypeId Identity yes Flag
ProductRouteId Identity yes Flag
ConversionFactor Float no Production rate conversion factor
SourceMaterialId Identity yes Source material (from BOM)
MasterRouteId Identity yes Master Route Id
ReplenishmentFlag Integer no Flag
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
AllocationChangeDetails Master Planning
Allocations
The table stores detailed set of property values for each edit action
name type identity null description
AllocationChangeId Identity no Edit action Id
FieldName String no Field from filter
Operation String no Comparison operation
Value String yes Value, can be null for isnull operations
top
AllocationChanges Master Planning
Allocations
The table stores the list of forecast changes and comments
name type identity null description
Id Identity yes no Identity
PeriodRange String no Period range - Week or Month
Period String no Period - Source or Delivery
DeliveryMonth Date yes delivery month
DeliveryWeek Date yes delivery week
SourceMonth Date yes source month
SourceWeek Date yes source week
ReasonId Identity yes A reference to Reasons
UnitId Identity no The unit on which the edit has been made (A reference to Units)
IsDisplayComment Identity no A flag: is this record a forecast comment?
IsHidden Integer no A flag: used for revised allocations
InitValue Float no Forecast value before modification
LastValue Float no Forecast value after modification
AllocationComment LongestString yes Allocation comment
CommentLink HugeString yes Complex link to this comment from matrix or collaboration screen
IsSent Integer no Is such allocation was sent
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
AllocationSnapshotBodies Master Planning
Master Planning
The table stores weekly allocation for SKUs
name type identity null description
Id Identity yes no Identity
AllocationSnapshotId Identity no A reference to the corresponding SKU
DeliveryWeek Date yes Delivery Week
DeliveryMonth Date yes Delivery Month
SourceWeek Date yes Source Week
SourceMonth Date yes Source Month
SiteMaterialUsageId Identity no A reference to the corresponding SKU
WorkcentreId Identity no A reference to Workcentres
Allocation Float no Forecast value edited by customer
AllocationId Identity yes Allocation Id (links stages)
StageNo Integer no Stage No
SeqNo Integer no Stage No
IsLastStage Integer no Is Last Stage
OperationTypeId Identity yes Flag
NextOperationTypeId Identity yes Flag
ProductRouteId Identity yes Flag
ConversionFactor Float no Production rate conversion factor
FGPropertyValueId Identity yes Flag
SourceMaterialId Identity yes Source material (from BOM)
MasterRouteId Identity yes Flag
IsWorking Integer no A switch. Possible values: 0 - forecast state unchanged, or the forecast released; 1 - the forecast has been carried from the previous forecast, 2 - the forecast has been modified (edited) )
AllocationChangeId Identity yes Allocation Change id
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
AllocationSnapshots Master Planning
The table stores the list of forecasts existing in the system
name type identity null description
Id Identity yes no Identity
StartDate Date no The first month after the forecast horizon
FinishDate Date no The first month after the forecast horizon
Name String no Forecast snapshot name
Description String no Forecast snapshot description
UserId Identity no Snapshot owner identifier
InsertUserId Identity yes Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
AlternateMaterials Core
Core
The table stores the list of alternative material names. Each company can have its own set of material names
name type identity null description
Id Identity yes no Identity
LocationId Identity yes A reference to Locations table
MaterialId Identity no A reference to Materials table
MaterialName LongString no Alternative name of the material
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
AlternateRunsData Block Scheduling
Temporary
Keeps the list of alternate runs.
name type identity null description
Id Identity no Reference to MaterialRuns table
WorkCentreId Identity no Reference to Workcentres table
RunCode LongestString yes Material run code
StartDate Date yes Start date of material run
FinishDate Date yes Finish date of material run
Quantity Float yes Capacity of material run
AvailableCapacity Float yes Available capacity of material run
Duration Float no Duration of material run
AvailableDuration Float no Available duration of material run
IsValid Integer yes 0 - is not valid run; 1 - is valid run
UserId Identity no User identificator
top
AmendInventories Due date quoting
Temporary table
The table contains information about inventories by modification order
name type identity null description
SiteMaterialUsageId Identity no A reference to the SKU
Quantity Float no Used quantity
InventoryDate Date no Inventory date
OrderLineId Identity no A reference to the order line
ConsignmentLocationId Identity yes A reference to Locations
top
AmendInventoryProfilesData Due date quoting
Temporary table
The table contains information that is used when recalculating real inventory profile due to requests of Amend type
name type identity null description
Id Identity yes no Identity
SiteMaterialUsageId Identity yes A reference to the site material usage
DateFrom Date no Date of result calculation
Opening Float no Opening value on the date
OrdersIn Float yes Incoming orders on the date
OrdersOut Float yes Outgoing orders on the date
Closing Float yes Closing value on the date
MinOpening Float yes MinOpening value on the date
ConsignmentLocationId Identity yes A reference to Locations
Delivered Float no Delivered movements
OnHandInventory Float no Delivered movements
OnHandMinOpening Float no Delivered movements
top
AmendRuns Due date quoting
Temporary table
The table contains information about runs by modification order
name type identity null description
MaterialRunId Identity yes A reference to the material run
Quantity Float no Used quantity
Duration Float no Used duration
OrderLineId Identity no A reference to the order line
top
ArchivedAllocationBodies Master Planning
Master Planning
The table stores weekly allocation for SKUs
name type identity null description
Id Identity no Identity
UniqueId String no Identity
Stamp TimeStamp no Identity
DeliveryWeek Date yes Delivery Week
DeliveryMonth Date yes Delivery Month
SourceWeek Date yes Source Week
SourceMonth Date yes Source Month
SiteMaterialUsageId Identity no A reference to the corresponding SKU
WorkcentreId Identity no A reference to Workcentres
NonMoveableWeight Float no nonmoveableorders
System Float no Forecast value generated by system
Customer Float no Forecast value edited by customer
Revised Float no Revised Allocation
AllocationId Identity yes Allocation Id (links stages)
StageNo Integer no Stage No
IsLastStage Integer no Is Last Stage
OperationTypeId Identity yes Flag
ProductRouteId Identity yes Flag
ConversionFactor Float no Production rate conversion factor
FGPropertyValueId Identity yes Flag
MasterRouteId Identity yes Flag
IsWorking Integer no A switch. Possible values: 0 - forecast state unchanged, or the forecast released; 1 - the forecast has been carried from the previous forecast, 2 - the forecast has been modified (edited) )
AllocationChangeId Identity yes Allocation Change id
RevisedAllocationChangeId Identity yes Allocation Change id
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
ArchivedForecastBodies Forecasting
Forecasting
The table stores the archive of previous forecasts
name type identity null description
Id Identity no Identity
DateFrom Date no Month
ForecastId Identity no A reference to Forecasts
SiteMaterialUsageId Identity no A reference to SiteMaterialUsages
OriginalSystem Float no Forecast value generated by system at firts pass of generation
System Float no Forecast value generated by system
Customer Float no Forecast value edited by customer
Final Float no Final forecast value
ForecastAllocation Float no Forecasr allocation
Upper Float yes Upper percentile generated by ForecastPro
Lower Float yes Lower percentile generated by ForecastPro
IsWorking Integer no
SafetyStock Float yes Safety Stock generated by ForecastPro
ForecastStatusId Identity no
EditGroupId Identity yes forecast changes id
EditGroupFinalId Identity yes forecast changes id
WeeklyEdited Integer yes A flag
PriceCurrencyId Identity no Currency id
SystemPrice Float no System Price
ForecastedPrice Float no Forecasted Price
CostCurrencyId Identity no Cost Currency Id
NominalCost DoubleFloat no Nominal Cost
NominalCostAdjustment Float no Nominal Cost adjustment
ValueAddAdjustment Float no Nominal Cost adjustment
SystemWeeklyCoefId Identity yes System weekyl coef id
CustomerWeeklyCoefId Identity yes System weekyl coef id
FinalWeeklyCoefId Identity yes System weekyl coef id
DeletedFlag Integer no A flag
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
AverageExpandedPrices Forecasting
Forecasting
The table stores prices calculated from history or/and order records for each SKU
name type identity null description
DateFrom Date no Day from
DateTo Date no Day toMonth
SiteMaterialUsageId Identity no A reference to the corresponding SKU
Price Float no Price for SKU
CurrencyId Identity yes A reference to the corresponding currencies
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
BillOfMaterials Core
Core
The table stores information about which materials can be used as source to produce the new material
name type identity null description
Id Identity yes no Identity
LocationId Identity no A reference to Locations
FromMaterialId Identity no Source material ID
ToMaterialId Identity no Product material ID
Percentage Float no Percentage. Reserved for future use
ConversionLoss Float no
top
BOM Core
Core
The table stores source priority rules
name type identity null description
Id Identity yes no Identity
BomCode String no Weight of rule
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was inserted?
top
BOMMaterials Core
Core
The table stores source priority rules
name type identity null description
Id Identity yes no Identity
BomId Identity no BOM identity
MaterialId Identity no Weight of rule
OperationTypeId Identity no Weight of rule
InputUnitId Identity no Weight of rule
OutputUnitId Identity no Weight of rule
Multiplier Float no Site
Divider Float no Who inserted the record?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
BomMaterialSnapshots Master Planning
Master Planning
The table contains detailed information about grades/paper machines per SNP period
name type identity null description
SnapshotUserId Identity no
MaterialId Identity no
PropertyValueId Identity no
BomId Identity no
Id Identity no Reference for SNP
Replenished Integer no Is product replenished somewhere
top
BSOAllocationData Block Scheduling
Block Scheduling
The table stores allocations as input for BSO engine
name type identity null description
WorkcentreId Identity no Workcentre
OperationTypeId Identity no Operation type
GroupLevel Identity no Grouping Level
DateFrom Date no
GradeId Identity no
FinishingId Identity yes
OriginalWeight Float no
Weight Float no
Duration Float no
TotalDuration Float no
ReducedTotalDuration Float no Run Status Name
RemainingDuration Float no Who inserted the record?
Coef DoubleFloat no When the record was inserted?
Priority Integer no
Rate Float no
IsLiveRun Integer no LiveRun: 1 - production run, 0 - optimized run
NextWorkcentreId Identity yes Next Workcentre in Chain
NextOperationTypeId Identity yes Next Operation type in Chain
NextSourcePeriod Date yes Source period for next operation
NextWeight Float yes Allocation for next operation
NextCoef Float yes Coef for next operation
OperatorUserId Identity no User identity
top
BSOCampaignBatchUpdateData Block Scheduling
Block Scheduling
The table stores runs for workcentres for batch update
name type identity null description
WorkCentreId Identity no Workcentre identity
RunId Identity no Run identity
OperatorUserId Identity no Operator User ID (A reference to Users)
top
BSOGradeProperties Block Scheduling
Block Scheduling
The table stores block schedule optimiser Grade properties.
name type identity null description
GradeId Identity no BSO Grade Id
PropertyId Identity no Property Id
Code String no Code
top
BSOIndicativeData Block Scheduling
Block Scheduling
The table stores Indicatives
name type identity null description
WorkcentreId Identity no Workcentre
GroupLevel Identity no Grouping Level
DateFrom Date no
GradeId Identity no
OperationTypeId Identity no Operation type
Weight Float no
Duration Float no
TotalDuration Float no
ReducedTotalDuration Float no Run Status Name
RemainingDuration Float no Who inserted the record?
Coef DoubleFloat no When the record was inserted?
Priority Integer no
Rate Float no
IsLiveRun Integer no LiveRun: 1 - production run, 0 - optimized run
OperatorUserId Identity no User identity
top
BSOInputData Block Scheduling
Block Scheduling
The table stores allocations as inputfor BSO engine
name type identity null description
Id Identity no Identity
WorkcentreId Identity no Workcentre
OperationTypeId Identity no Operation type
DateFrom Date no
GradeId Identity no
FinishingId Identity yes
Weight Float no
Duration Float no
Priority Integer no
OrderLineId Identity no
Rate Float yes
IsLiveRun Integer no LiveRun: 1 - production run, 0 - optimized run
NextWorkcentreId Identity yes Next Workcentre in Chain
NextOperationTypeId Identity yes Next Workcentre in Chain
NextSourcePeriod Date yes Source period for next operation
NextWeight Float yes Allocation for next operation
NextCoef Float yes Coef for next operation
SourceRunId Identity yes Optimized source Run (used as demand)
SourceAllocationId Identity yes REference to BSOInput as input allocation
top
BSOOrdersData Block Scheduling
Block Scheduling
The table stores allocations as inputfor BSO engine
name type identity null description
WorkcentreId Identity no Workcentre
OperationTypeId Identity no Operation type
GroupLevel Identity no Grouping Level
OrderLineId Identity no Order Line
DateFrom Date no
GradeId Identity no
FinishingId Identity yes
NextWorkcentreId Identity yes
NextOperationTypeId Identity yes
Weight Float no
Duration Float no
Priority Integer no
Rate Float yes
IsLiveRun Integer no LiveRun: 1 - production run, 0 - optimized run
OperatorUserId Identity no User identity
top
BSOProgramGrades Block Scheduling
Block Scheduling
BSO program grades
name type identity null description
Id Identity yes no Run Identity
BSOProgramId Identity no BSO Program Id
BSOProgramTemplateId Identity no BSO Program Template Id
BSOTemplateGradeId Identity no BSO Template Grade Id
SequenceNo Identity no Sequence number of grade in template
GradeId Identity yes Reference to GradeProperties.GradeId
Mandatory Integer no Is mandatory grade? (1 - yes, 0 - no)
Duration Float no Nominal duration
MinDuration Float no Minimum allowed run length
MaxDuration Float no Maximum allowed run length
RunProperties LongString yes Run properties
top
BSOProgramRunsData Block Scheduling
Block Scheduling
The table stores BSO program runs for workcentre
name type identity null description
BSOProgramId Identity no BSO program identity
BSOProgramSequenceNo Identity no BSO program sequence no
BSOProgramStartDate Date no Start date BSO program
RunFinishDate Date yes Finish date run
BSOProgramGradeId Identity no BSO Program grade identity
GradeId Identity no Grade identity
BSOTemplateGradesequenceNo Identity no BSO grade sequence no
TemplateDuration Float no Template duration
DemandDuration Float no Demand duration
RunDuration Float no Run duration
OperatorUserId Identity no Operator User ID (A reference to Users)
top
BSOPrograms Block Scheduling
Block Scheduling
The table stores block schedule optimiser programs.
name type identity null description
Id Identity yes no Identity
WorkcentreId Identity no Workcentre Id
ProgramTemplateId Identity no Program Template Id
SequenceNo Integer no Sequence Number
StartDate Date yes The date and time that the start of the template is assigned to
StartRunId Identity yes Run identity
FinishDate Date yes The date and time that the finish of the template is assigned to
OppRunLength Identity no Opp.Run length
FixOppRuns Identity no Defines whether the opp.run of the Program Tem-pate Assignment to the workcentre should not be recalculated based on forecast
DurationAdj Identity no Duration adjusted by user
ShutLength Identity no The length of 'floating' shut to be added at the end of the template
AllowIdleForShut Identity no Allow idle time for shut
EarlyFixedPenalty Float no Early fixed penalty
DailyEarlyPenalty Float no Daily early penalty
LateFixedPenalty Float no Late fixed penalty
DailyLatePenalty Float no Daily late penalty
FirstGradeNo Identity no First BSO Grade SequenceNo
LastGradeNo Identity no Last BSO Grade Sequence No
FirstRunMandatory Identity yes Allows to override the first run’s mandatory flag
LastRunMandatory Identity yes Allows to override the last run’s mandatory flag
top
BSOProgramTemplates Block Scheduling
Block Scheduling
The table stores the list of templates for the selected workcentre type
name type identity null description
Id Identity yes no Identity
WorkCentreTypeId Identity no Workcentre type Id
ProgramName String no Program name
OppRunLength Float no Duration of the default opp.run to be created for this template
FixOppRuns Integer no Defines whether the opp.run of the Program Template should not be recalculated based on forecast
RunsAssigned Integer yes Number of runs from the template which are as-signed to this workcentre
FirstRunProperties LongString yes First run properties
LastRunProperties LongString yes Last run properties
Workcentres LongString yes Workcentres that used this BSO Program Template
AutoSizeRunDuration Integer no Option to allow template runs to be autosized (1 - yes; 0 - no)
TemplateDuration Float no Template duration
IsWeightUse Integer no Option to allow template runs to be weight (1 - yes; 0 - no)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
BSORunsData Block Scheduling
Block Scheduling
The table stores allocations as inputfor BSO engine
name type identity null description
WorkcentreId Identity no Workcentre
GroupLevel Identity no Grouping Level
DateFrom Date no
GradeId Identity no
Weight Float no
Duration Float no
IsLiveRun Integer no LiveRun: 1 - production run, 0 - optimized run
OperatorUserId Identity no User identity
top
BSOTemplateGrades Block Scheduling
Block Scheduling
BSO template grades
name type identity null description
Id Identity yes no Identity
ProgramTemplateId Identity no Program Template Id
GradeId Identity yes Reference to GradeProperties.GradeId
OperationTypeId Identity yes Reference to OperationTypes
RunProperties LongString yes Run properties
SequenceNo Identity no Sequence number of grade in template
Mandatory Integer no Is mandatory grade? (1 - yes, 0 - no)
Duration Float no Nominal duration
MinDuration Float no Minimum allowed run length
MaxDuration Float no Maximum allowed run length
top
BSOWorkcentreData Block Scheduling
Temporary
The list of workcentres to be processed in BSO per user.
name type identity null description
WorkcentreId Identity no Workcentre Id
BSOStartDate Date yes BSO Start Date for optimization
BSOFrozenPeriodEnd Date yes BSO Frozen Period End
Required Integer yes Required for calculation
GenerateBSODate Date yes Genetate date BSO input for optimization
OperatorUserId Identity no Who inserted the line?
top
Bundles Core
Configuration
The table stores system parameter values
name type identity null description
Id Identity yes no Identity
Name String no Identity
TableName String yes Source table
Condition HugeString yes Condition
FieldKey String yes Key source field
FieldValue String yes Value source field
FieldDescription String yes Value source field
FieldOrderBy String yes Value source field
IncludeNone Integer no Include None as value?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
BundleValues Core
Configuration
The table stores system parameter values
name type identity null description
Id Identity yes no Identity
BundleId Identity no Key
Key String yes Key
Value LongString yes Parameter value
OrderNo Integer no Ordinal number in the list of parameter values.
Description HugeString yes Description of the parameter value.
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
CalculatedOppBlocks Block Scheduling
Block Scheduling
After the Run Optimiser engine has generated campaigns, it is possible to calculate opportunistic blocks based on the information from forecast statistics of actual materials being produced each week. This calculation is done for each week of the campaign. The table contains calculated opportunistic blocks by ISO weeks.
name type identity null description
WorkcentreId Identity no A reference to workcentres.Id
DateFromIW Date no ISO week
Duration Float yes Duration of opportunistic block for the specified week, hours
OperatorUserId Identity no Operator user ID
top
CalendarRules Core
Calendars
The table stores rules for calendars.
name type identity null description
Id Identity yes no Identity
CalendarId Identity no A reference to calender
CalendarRuleNo String no Rule type
Day Integer yes Day of month
DayOfWeek Integer yes Day of week
NumOfWeek Integer yes Number of week
Month Integer yes Month
Year Integer yes Year
IsWorkingDay Integer no A flag: is it a working day?
IsReceivingDay Integer no A flag: is it a receiving day?
Description LongString no Rule description
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Calendars Core
Calendars
In this table calendars are stored. A calendar defines when customer can receive orders, and when customer is expected to have consumption.
name type identity null description
Id Identity yes no Identity
CalendarName String no Calendar name
GeneralCalendarId Identity yes Parent calendar
LastGeneratedDate Date yes When schedule was last time regenerated.
LastExistingDate Date yes Schedule last existing date.
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
CalendarSources Core
Calendars
The table stores detailed information on each day of calendars. Calendar rules are expanded into this table.
name type identity null description
CalendarId Identity no A reference to calendar
DateFrom Date no Date
DateFromIW Date no Date IW
DateFromMonth Date no Date Month
IsWorkingDay Integer yes A flag: is it a working day?
IsReceivingDay Integer yes A flag: is it a receiving day?
WeekSum Integer yes A flag: is it a receiving day?
WeekMonthCoef Float no Week month coef
Description LongString yes Description (copied from rule)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
CampaignChangesData Block Scheduling
Block Scheduling
Temporary table for storing campaign changes
name type identity null description
DateChanges Date yes Date
WorkCentreId Identity no WorkCentre Id
OrderNo Identity no OrderNo
UndoAction String no Action
UndoParams LongestString no Parameters
RedoAction String no Action
RedoParams LongestString no Parameters
UserId Identity no User ID
top
CampaignGraphData Replenishment
Temporary
This table store data for creation of campaign graph.
name type identity null description
MaterialRunId Identity no Reference to MaterialRuns table
RunCode LongString no Block code from MaterialBlocks + run code from MaterialRuns
MaterialBlockId Identity no Reference to MaterialBlocks table
WorkCentreId Identity no Reference to WorkCentres table
WorkCentreName String no Work centre name
PropertyValue LongString no Property value
StartDate Date yes Start date of run
FinishDate Date yes Finish date of run
Capacity Float yes Quntity of run
AllocationQuantity Float yes Allocation quantity for preset values PropertyValueId and HierarchyId
AllocationOther Float yes AllocationAll - AllocationQuantity
AllocationAll Float yes All allocation
TentativeQuantity Float yes Quantity tentative orders for preset values PropertyValueId and HierarchyId
TentativeAll Float yes Quantity all tentative orders
TentativeOther Float yes TentativeAll - TentativeQuantity
FirmQuantity Float yes Quantity firm orders for preset values PropertyValueId and HierarchyId
FirmOther Float yes FirmAll - FirmQuantity
FirmAll Float yes Quantity all firm orders
Native Integer yes Native runs
PropertyValueId Identity yes Reference to PropertyValues table
OperatorUserId Identity no User which insert line
top
CarryForecastData Forecasting
Temporary
Temp table for storing forecast data for carrying forecast
name type identity null description
SiteMaterialUsageId Identity no SMU Id
DateFrom Date no date (month)
IsWorking Integer no Is working flag
Final Float no Final forecast value
WeeklyEdited Integer yes flag
EditGroupId Identity yes Group Id
EditGroupFinalId Identity yes Group Id
CustomerHash HugeString yes Customer edits hash
FinalHash HugeString yes final edits hash
OperatorUserId Identity no User Id
top
ChangeOverProperties Block Scheduling
Block Scheduling
The table stores changeover properties
name type identity null description
ChangeOverId Identity no A reference to WorkcentreChangeOvers.Id
PropertyId Identity no A reference to Properties.Id
CodeFrom String no Source code
CodeTo String no Destination code
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Characteristics Core
Core
The table stores characteristics
name type identity null description
Id Identity no PriceRuleId, SupercessionId, etc.
FieldName String no Entity
EntityType String yes Entity
Value String no Value
ExpandedValues HugeString yes Value
FieldViewName String yes Entity
top
ChartLines Core
Configuration
The table contains the list columns of grids
name type identity null description
Id Identity yes no Identity
ChartId Identity no Grid Id
orderNo Identity no Grid Id
Caption ShortString no Column name
FieldName ShortString no Field name
Type ShortString no Type: (Decimal, Integer, String, Date, DateTime, bool)
ControlType ShortString no Control Type (CheckBox, ComboBox, TextBox, DatePicker, MonthPicker, WeekPicker)
IsEditable Integer no Is editable (yes/no)
IsShowTotal Integer no Is show total (yes/no)
State ShortString no State = (normal, fixed, hidden)
DataForColumn String yes this column will place into column cell data object
colorColumn String yes
BackgroundColorColumn String yes
dataColumns String yes
dataColumnsMapping LongestString yes
editableColumn String yes
tooltipColumn String yes
classColumn String yes
Color ShortString yes Default chart serie colour
Pattern ShortString yes Default chart line pattern (e.g. "3,3" is dotted etc)
IsResizable Integer no (yes/no)
IsTransformColumn Integer no (yes/no)
IsTransformable Integer no (yes/no)
TransformFormat String yes format for transformation
IsShowToolTip Integer no (yes/no)
IsConfigurable Integer no (yes/no)
MaxWidth Integer no Max width for multi-line column
MinWidth Integer no Min width for multi-line column
Style String yes (string)
Format String yes (string)
Sort Integer no (yes/no)
Filter ShortString yes (text/select)
top
Charts Core
Configuration
The table contains the list of charts
name type identity null description
Id Identity yes no Identity
Name ShortString no Grid name
Description String no Grid description
PageId Identity yes Page
Type ShortString yes (serial/stock)
Configuration String yes json config
top
CheckData Core
Temporary
Temporary table for data checks
name type identity null description
Id Identity no Identity
OperatorUserId Identity no OperatorUserId
Description LongString yes Description for data check
top
CheckDDQFGInventoryData Due date quoting
Temporary table
The table stores temporary results of an FG search. The table is filled when searching for FG, and is cleared after DDQ process finished
name type identity null description
Id Identity no Identity
SiteMaterialUsageId Identity no SKU ID
WarehouseId Identity no Warehouse ID
WHLocationId Identity yes location ID on the warehouse
DespatchDate Date no Despatch date from the warehouse
DeliveryDate Date no Delivery date to the destination area
Success Identity no A flag: was the full quantity found? (0, 1)
Quantity Float no Rounded Found quantity
OriginalQuantity Float no Original Found quantity
QuantityWholeUnit Float no Quantity Whole Unit
SourcePriority Identity no Source Priority for the SKU
JourneyId Identity yes Journey Id
ConsignmentLocationId Identity yes A reference to Locations
OrderBy Integer yes Order of select
OnHandStock Integer no OnHandStock
ProductId Identity no Product ID
ProductPriority Identity no Product Priority
top
CheckDDQFLRunsData Due date quoting
Temporary table
Temporary data of the FL runs search is stored in the table. It is filled when searching for FL runs, and is cleared after ddq request processed.
name type identity null description
Id Identity no Identity
SourceWorkCentreId Identity yes Paper machine ID
FGWarehouseId Identity yes FG warehouse ID on the site
FGWHLocationId Identity yes Location of the FG warehouse on the site
SiteId Identity yes Site ID of the paper machine
TransportRouteId Identity yes Transport route ID
TransportMethodId Identity yes Transport method ID
JourneyId Identity yes Journey ID
DespatchDate Date yes Despatch date from the FG warehouse
DeliveryDate Date yes Delivery date to the destination area
FLWorkCentreId Identity no FL workcentre ID
FLMaterialBlockId Identity yes Material block ID
FLMaterialRunId Identity yes Material run ID
FLOppRunId Identity yes Opportunistic run ID
StartRunDate Date yes Run start date
FinishRunDate Date yes Run end date
EnabledQuantity Float no Found quantity on the run
OppQuantity Float no Found quantity on the opportunistic run
SFGWorkCentreId Identity yes SFG warehouse ID
SFGMaterialId Identity yes SFG material ID
SFGQuantity Float no Found SFG quantity
Success Identity no A flag: was the full quantity found? (0, 1)
Loss Float no Losses on the wirkcentre
PMMaterialRunId Identity yes Run ID for PM
top
CheckDDQPMRunsData Due date quoting
Temporary table
The table stores temporary data of a PM run search. It is filled when searching for PM runs, and is cleared after ddq request processed.
name type identity null description
Id Identity no Identity
ProductPriority Identity yes Product Priority
MaterialId Identity yes A reference to Materials
SourceWorkCentreId Identity yes A reference to PaperMachines
FLMaterialRunId Identity yes A reference to FL Material run ID
PMMaterialBlockId Identity yes A reference to PM material block ID
PMMaterialRunId Identity yes A reference to PM material run ID
OppRunId Identity yes A reference to opportunistic run ID
OppQuantity Float no Opportunistic quantity found
StartRunDate Date no PM run start date
FinishRunDate Date no PM run end date
EnabledQuantity Float no Quantity found on the run
Temp Identity no A flag: is the record temporary? (1, 0)
Success Identity no A flag: was the full quantity found? (0, 1)
Loss Float no Losses on the paper machine
DespatchDateSS Date yes Despatch date from the FG warehouse (used for Single Stage branch)
DeliveryDateSS Date yes Delivery date to the destination area (used for Single Stage branch)
WorkcentreWHid Identity yes A reference to the FG warehouse on the site (used for SingleStage branch)
LocationWHid Identity yes A reference to the location of the FG Warehouse on the site (used for Single Stage branch)
SiteId Identity yes Site ID of the paper machine
TransportMethodIdSS Identity yes A reference to the transport method (used for Single Stage branch)
TransportRouteIdSS Identity yes A reference to the transport route (used for Single Stage branch)
JourneyIdSS Identity yes A reference to the transport route (used for Single Stage branch)
StageNo Integer no
top
CheckDDQSFGInventoryData Due date quoting
Temporary table
The table stores intermediate data (results of the SFG search)
name type identity null description
Id Identity no Identity
WorkCentreId Identity no A reference to the workcentre
SiteId Identity yes Site ID of the paper machine
MaterialId Identity no A reference to the material
Quantity Float no Found quantity
SourceWorkCentreId Identity yes A reference to the paper machine
InventoryDate Date no Inventory date
top
CollaborationData Forecasting
Forecasting
A temporary table for forecast collaboration
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
Id Identity no Grouped Identity
History1 Float no History1
History2 Float no History2
History3 Float no History3
History4 Float no History4
History5 Float no History5
History6 Float no History6
History7 Float no History7
ForecastStatusId Integer no
IsWorking Integer no
CurrentForecast Float no
MTD Float no
SystemTotal Float no
CustomerTotal Float no
FinalTotal Float no
ForecastAllocationTotal Float no
OrdersTotal Float no
AllocationsTotal Float no
BudgetTotal Float no
NominalCostTotal Float no
ValueAddTotal Float no
RevenueTotal Float no
TotalEditableCustomer Integer no
TotalEditableFinal Integer no
TotalEditForecastAllocation Integer no
TotalCustomerCssClass String yes
TotalFinalCssClass String yes
TotalToolTip String yes
WarningCssClass String yes
top
CollaborationGraphData Forecasting
Temporary
Temporary table for data for Serial Graph screen and History screen
name type identity null description
DateFrom Date no Date (month)
Usage Float yes total usage
AdjustedUsage Float yes total usage
AllUsage Float yes all usage with superceded history
FittedUsage Float yes all fitted usage with superceded history
System Float yes system forecast value
Customer Float yes customer forecast value
Final Float yes final forecast value
Upper Float yes upper limit
Lower Float yes lower limit
Trend Float yes trend
Budget Float yes budget value
Snapshot1 Float yes Snapshot 1 value
Snapshot2 Float yes Snapshot 2 value
Snapshot3 Float yes Snapshot 3 value
Snapshot4 Float yes Snapshot 4 value
Snapshot5 Float yes Snapshot 5 value
Snapshot6 Float yes Snapshot 6 value
Snapshot7 Float yes Snapshot 7 value
Snapshot8 Float yes Snapshot 8 value
Snapshot9 Float yes Snapshot 9 value
Snapshot10 Float yes Snapshot 10 value
Snapshot11 Float yes Snapshot 11 value
Snapshot12 Float yes Snapshot 12 value
Snapshot13 Float yes Snapshot 13 value
Snapshot14 Float yes Snapshot 14 value
Snapshot15 Float yes Snapshot 15 value
FinalForecastComment String yes final comment
CustomerForecastComment String yes customer comment
OperatorUserId Identity no user id
top
CombinedRunCapacity Replenishment
Order generation
The table stores data about available runs and material which when can produce for allocation based replenishment process
name type identity null description
SiteId Identity no A reference to MaterialRuns
WorkcentreId Identity no A reference to MaterialRuns
MaterialId Identity no Material identity
Capacity Float no Calculate production cost for combination Material/Paper Machine
Rate Float no Calculate production cost for combination Material/Paper Machine
top
Companies Core
Core
The table stores the list of companies registered in the system
name type identity null description
Id Identity yes no Identity
CompanyName String no Company name
CompanyCode ShortString no Company external code
CustomerRankId Identity yes Company rank
Internal Integer no A flag: is the company internal? (i.e. I-Plan system owner)
SafetyStockMethodId Identity yes Default safety stock method
GroupReplenishedLocations Integer yes Group Replenished locations
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ConfigurationSnapshots Master Planning
Master Planning
The table contains detailed information about grades/paper machines per SNP period
name type identity null description
SnapshotUserId Identity no
ProductionConfigurationId Identity no
ProductRouteId Identity no
OperationTypeId Identity no
SiteMaterialUsageId Identity no
MaterialId Identity no
LocationId Identity no for initial source rules
PropertyValueId Identity no for initial source rules
CycleTypeId Identity yes for initial source rules
ValidSources HugeString yes
PrimaryValidSources HugeString yes
Multiplier Float no
Divider Float no
ConfigurationHash HugeString no
BomId Identity yes
IsLastCoProductStage Integer no Is Last coproduct stage
IsLastStage Integer no Is Last stage
StageOrderNo Integer no stage order no from prod. route
IsCoProductStage Integer no stage order no from prod. route
Id Identity no
top
ConsignmentOrderForSendData Replenishment
Temporary
A temporary table for Consignment Orders for send (ticket 51626)
name type identity null description
OrderLineID Identity yes Order Line ID
Action String yes
OperatorUserId Identity no Operator User ID (A reference to Users)
top
ConsignmentOrdersData Replenishment
Temporary
A temporary table for Consignment Orders (ticket 51626)
name type identity null description
Id Identity yes no Unique identifier of the record
OrderLineID Identity yes
OrderCode String yes
LineCode String yes
DeliveryID Identity yes
DeliveryCode String yes
AlternateCode2 String yes
MovementDate Date no
StockLevel Float yes
Incoming Float yes
Outgoing Float yes
Source_Destination String yes
StatusCode String yes
DeliveryDate Date yes Critical date
OperatorUserId Identity no Operator User ID (A reference to Users)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ConsignmentParameters Core
Core
The table stores the list of SKU parameters
name type identity null description
Id Identity yes no Identity
SiteMaterialUsageId Identity no Warehouse SKU
CustomerId Identity no Customer Location Id
Replenished Integer no A flag: is the SKU replenished? (0 - not replenished, 1 - replenished)
ReplenishmentStartDate Date yes Replenishment start date
ReplenishmentFinishDate Date yes Replenishment start date
ReplenishmentFrequency Identity no Frequency of warehouse replenishment
MaxReplenishmentFrequency Identity no Frequency of warehouse replenishment
MinOrderQuantity Float yes Minimal order quantity
OrderUnitId Identity yes A reference to Units
DaysOfSupply Integer no Days of supply (delivery time)
MaxDaysOfSupply Integer no Days of supply (delivery time)
HighQuantity Float no Maximal quantity
LowQuantity Float no Minimal quantity
UpperPercentile Float yes Upper percentile
LowerPercentile Float yes Lower percentile
SafetyStockMethodId Identity yes ID of the SafetyStock calculation method
MaxSafetyStockMethodId Identity yes ID of the SafetyStock calculation method
LastInventoryDate Date yes Last known inventory date
GroupKey String yes Group key for grouping in replenishment
AlternateProduct String yes Alternate Product
ExistingAlternateProduct String yes Alternate Product
SkuKey String no Destination SKU Code - SKU-CS.
SafetyStockPercentWarning Float yes Safety stock percent warning
ReplenishmentHorizon Integer yes Replenishment horizon
InsertUserId Identity no Who inserted the record?
UpperPercentileMethod String no Method for upper percentile
UpperPercentileMonths Integer no Method for upper percentile
IsActiveSku Integer no Is suck sku have inventory or movements
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
CoProductPriceSnapshots Master Planning
Master Planning
The table contains the list of SNO issues (problems) within the specified user snapshots
name type identity null description
SnapshotUserId Identity no User ID (reference to Users )
CoProductId Identity no Property value ID (reference to PropertyValues)
DateFrom Date no Demand date for price
Price Float no Percentage
top
CoProducts Core
Core
The table stores co-products
name type identity null description
Id Identity yes no Identity
MaterialId Identity no Material Identity
CoProductMaterialId Identity no Co Product Identity
Percentage Float no Co Product percentage
PricePercentage Float no Co Product price percentage of price for main product
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
CoProductSnapshots Master Planning
Master Planning
The table contains the list of SNO issues (problems) within the specified user snapshots
name type identity null description
SnapshotUserId Identity no User ID (reference to Users )
SnpItemId Identity no SNP Item Id
CoProductId Identity no Co Product Id
Percentage Float no CoProduct Percentage
PricePercentage Float no Price Percentage
TotalPercentage Float no Percentage
TotalPricePercentage Float no Percentage
top
CostRules Core
Core
The table stores the rules of calculation of PM product prime costs
name type identity null description
Id Identity yes no Identity
WorkcentreId Identity no A reference to Workcentres table
CostRuleCode LongString yes Production rate code (It is used for fast comparison)
Effective Date no The date when the rule becomes active
Cost DoubleFloat no Cost
RuleWeighting Identity no Rule weighting
OperationTypeId Identity no Operation type Identity
DetailId Identity no Reference to Characteristis (HierarchyPropertyDetails)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
CostRuleSnapshots Master Planning
Master Planning
The table contains snapshots of production cost rules for SNO.
name type identity null description
ScenarioId Identity no ScenarioId
SnapshotUserId Identity no User ID (A reference to Users)
WorkcentreId Identity yes Workcentre ID (A reference to Workcentres)
OperationTypeId Identity yes OperationType ID (A reference to OperationTypes)
Effective Date no Effective date
Cost DoubleFloat no Cost
OriginalCost DoubleFloat yes Original cost
DetailId Identity no
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
CreateRealInventoryData Replenishment
Temporary
In this table save information about calculation of incomings and outgoings of orders for creation of real inventory.
name type identity null description
SkuKey String no User id
DateFrom Date no Date from
OverallOpening Float no Opening quantity for Firm, Tentative and Consumption
Opening Float no Opening
OpeningNonForecasted Float yes Opening
OrdersIn Float no Quantity incoming firm orders
TentativeOrdersIn Float no Quantity incoming tentative orders
NonForecastedOrdersIn Float no Quantity incoming Non Forecasted orders
OrdersOut Float no Quantity outgoing firm orders
NonForecastedOrdersOut Float yes Quantity outgoing Non Forecasted orders
TentativeOrdersOut Float no Quantity outgoing tentative orders
ClosingNonForecasted Float yes Opening
Closing Float no Opening
OverallClosing Float no Closing quantity for Firm, Tentative and Consumption
FirmClosing Float no Quantity outgoing delivery orders
MinOpening Float no Quantity outgoing delivery orders
Consumption Float no Forecst consumption
IgnoredDemandValue Float no Forecst consumption
Delivered Float no Delivered movements
OnHandInventory Float no Delivered movements
OnHandMinOpening Float no Delivered movements
OperatorUserId Identity no User id
top
CTPMessagesLog Due date quoting
Logging
The table is used to maintain external messages log
name type identity null description
Id Identity no Identity
MessageReceivedTime TimeStamp no
MessageProcessStartTime TimeStamp no
MessageCompletedTime TimeStamp no
HeaderCode ShortString yes
LineCode String yes
Headers Integer no
Lines Integer no
SuccessFullLines Integer no
MessageIn Text no
MessageOut Text yes
top
Currencies Core
Core
The table stores the list of all currencies available in I-Plan
name type identity null description
Id Identity yes no Identity
CurrencyName String no Currency name
CurrencyDescription LongString no Currency description
IsInternal Integer no A flag: is this internal (Default currency in system)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
CustomerOrdersFromStock Replenishment
Replenishment
The table stores list of all the current firm customer orders sourced from a replenished warehouse.
name type identity null description
OrderCode ShortString no Order header code
LineNoCode String no External reference to the order line number
DespatchDate Date no Despatch date, i.e. when the order leaves source location
WorkCentreId Identity no Source workcentre ID
SourceMaterialId Identity no Semifinishing product ID
SourceWeight Float no Weight of SFG product consumed to produce the FG product
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
CustomerRanks Core
Core
The table stores the list of customer ranks. It describes possible service levels
name type identity null description
Id Identity yes no Identity
CustomerRankName String no Rank name
CustomerRankDesc String no Rank abbreviation
Priority Integer no Priority of the customer rank
DisplayInForecast Integer no Define will be SKU with such ranks by default displayed in Forecast screen
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
CustomerRankSnapshots Master Planning
Master Planning
The table stores the list of customer ranks. It describes possible service levels
name type identity null description
SnapshotUserId Identity no User ID (A reference to Users)
ScenarioId Identity no Scenario ID (A refernce to Scenarios)
Id Identity no Identity
CustomerRankName String no Rank name
CustomerRankDesc String no Rank abbreviation
DisplayInForecast Integer no Define will be SKU with such ranks by default displayed in Forecast screen
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
CustomersForWorkcentreData Replenishment
Temporary
Temp table for storing list destinations for selected workcentre
name type identity null description
LocationId Identity no Reference to Locations table
IsDefault Integer no 1 - is default distination; 0 - no default
JourneyId Identity yes Reference to Journeys table
OperatorUserId Identity no User identificator
top
CycleFrequencySnapshots Master Planning
Master Planning
The table contains the list of SNO issues (problems) within the specified user snapshots
name type identity null description
SnapshotUserId Identity no User ID (reference to Users )
ScenarioId Identity no Property value ID (reference to PropertyValues)
StartWeek Date no Demand date for price
CycleTypeId Identity no Property value ID (reference to PropertyValues)
CycleFixedPeriodDate Date no Demand date for price
FirstPeriodDate Date no Demand date for price
Frequency Integer no Demand date for price
WeekTolerance Integer no Demand date for price
top
CycleTypes Master Planning
Master Planning
Cycle types per property set
name type identity null description
Id Identity no Identity
DetailId Identity no Properties set
Frequency Identity no Frequency in weeks, i.e. produced every N weeks
WeekTolerance Integer no Earlier tolerance, for producing earlier
Priority String yes Priority
ProducingDay Integer no Preferred day for producing 1-7 Mon-Sun, 0 - any
GroupName String yes Group
FixedPeriodInWeeks Integer no
top
CycleTypeSnapshots Master Planning
Master Planning
SNP Cycle type snapshots
name type identity null description
ScenarioId Identity no Scenario ID (A refernce to Scenarios)
SnapshotUserId Identity no User ID (A reference to Users)
Id Identity no Identity
DetailId Identity no Properties set
Frequency Identity no Frequency in weeks, i.e. produced every N weeks
WeekTolerance Integer no Earlier tolerance, for producing earlier
Priority String yes Priority
ProducingDay Integer no Preferred day for producing 1-7 Mon-Sun, 0 - any
GroupName String yes Group
FixedPeriodInWeeks Integer no
top
CycleUtilisationSnapshots Master Planning
Master Planning
The table contains detailed information about grades/paper machines per SNP period
name type identity null description
SnapshotUserId Identity no
ScenarioId Identity no
SnoItemId Identity no
SourcePropertyValueId Identity no
WorkCentreId Identity no
WorkCentreTypeId Identity no
SourcePeriod Date no
CycleTypeId Identity yes Reference for SNP
SourceCycleTypeId Identity yes
OrdersHours Float no Is product replenished somewhere
AllocationHours Float no Is product replenished somewhere
Rate Float yes Is product replenished somewhere
top
Dashboards Core
Core
The table stores dashboards defined in the system
name type identity null description
Id Identity yes no Identity
Name String no Dashboard name
Description String no Dashboard description (title)
OrderNo Integer no Dashboard order no
UserId Identity yes User Id
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
DashboardWidgets Core
Core
Widgets placed on dashboards
name type identity null description
Id Identity yes no Identity
DashboardId Integer no Dashboard Id
WidgetId Integer no Widget Id
Top Integer no Top
Left Integer no Left
Height Integer no Height
Width Integer no Width
ZIndex Integer no Z-index
FilterId Identity yes Filter of the widget instance
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
DataSourceFields Reports
Reports
name type identity null description
Id Identity yes no Id
DataSourceId Identity no A reference to DataSource table
Name String no Column name
Description LongestString no Column description
Category LongestString yes Column category, used for analysis in summary levels
Expression LongestString yes Expression for field
DataType String no Data type: String, Number, Float, DoubleFloat, Date, Month, Week
EntityType String yes Entity type: PropertyValue, PropertyCode, HierarchyName, HierarchyCode, Regular
OrderNo Integer yes Ordinal number of the column in the report, can be non unique
DefaultFiltered Integer no 0 - this field internal, and user should be able select it. Default system setting.
Filtered Integer yes 1 - this field internal, and user should be able select it. Can be overridden in particular model. Used for hiding some fields.
Helper String yes Helper view or table
HelperColumn String yes Helper column
Partition HugeString yes Partition part
ParentField String yes Parent field for Aggregated fields
Function String yes aggregate function
UnitTypeId Identity yes Unit Type Id
UnitId Identity yes Unit Id for field
CurrencyId Identity yes Currency Id for field
IsCurrency Integer no Currency Id for field
IncludeNullCondition Integer no Currency Id for field
IsCustomField Integer no Is it a system field, or created by a user?
IsMandatory Integer no Is this field mandatory?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
DataSourceFilters Reports
Reports
Report filters
name type identity null description
Id Identity yes no Id
DataSourceId Identity no Data Source identity
ReportFilterId Identity no Filter id
Name String no Filter name
UserId Identity no Filter owner (1 - global filter, otherwise user specific)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
DataSources Reports
Reports
System and user reports
name type identity null description
Id Identity yes no Id
Name String no View name for system and helper datasources, report name for user data sources
Title LongString no Report title
Description LongestString no Report description
Query HugeString no Original query for system reports or system report name (view name - IV$XXX)
DataSourceQuery Text yes Expanded query
Type String no Report type - system, user, helper
AccessRights String yes sku, endusesku
ReportFilters HugeString yes list of filtered columns
ReportRows HugeString yes Rows
ReportColumns HugeString yes columns
ReportValues HugeString yes Values - field list
ReportFunctions HugeString yes functions for values
ReportOrderBy HugeString yes Values - field list
ReportOrderByFunc HugeString yes functions for values
ParentDataSourceId Identity yes A reference to parent (system) DataSource
IsShowTotalColumns Integer no Is show total for columns?
IsShowTotalRows Integer no Is show total for rows?
IsShowRecordCount Integer no Is show record count in report?
IsColumnsAsRows Integer no Is show total row?
IsFreezeColumns Integer no Is freeze columns?
IsMergeRows Integer no Is merge rows?
IsIncludeUnit Integer no Is include unit in column title
Materialized Integer no Is view materialized
TopX Integer no Show top x entries
TopXField String yes Top X Field
TopXFieldOrder String yes Top X Field
IsIncludeOthersToTop Integer no Is include unit in column title
ReportSubTotalRow HugeString yes Is show subtotal rows and columns?
ReportSubTotalColumn HugeString yes Is show subtotal rows and columns?
ReportType String yes Type of report - simple, pivot, grouped, master-detail (not supported now)
UsedDataSources LongString yes Used datasources
CurrencyDateField String yes Currency date field
UseAsHelper Integer no Used datasources
DefaultFilterId Identity yes Default Filter
IsPublished Integer no Is report published (actual only for user reports)
IsMandatoryFilter Integer no Is filter should be applied for any report execution
UserId Identity no Who is owner of report (userId = 1 is system wide report
IsLocked Integer no Is report locked (actual only for user reports)
AllowProductUnits Integer no Define is allowed use product units for this report. in Report should be present field MaterialId
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
DBDictionaries Core
Language
The table stores localizable words used in the database.
name type identity null description
Id Identity yes no Identity
DictionaryKey LongestString no Dictionary key
DictionaryValue LongestString yes Dictionary value
TableRowId Identity yes A reference to table ID (used for localization)
LanguageId Identity no A reference to Languages
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
DDQAmendedOrders Due date quoting
Due date quoting
DDQ amended orders (original orders or newly created orders) are stored in this table
name type identity null description
Id Identity yes no Identity
OrderLineId Identity no A reference OrderLines
HeaderCode ShortString yes Header code (It is equal to inquiry header number)
SetNum Integer yes Number of sets (1 - original orders, 2 - newly created orders)
AmendNum Identity yes Number of amends (0 - amended all lines from book, n - sequence)
CreationSetTime Date yes Set creation time
UseOrder Integer yes A flag: take this order into account when calculating RealInventory?
UseOrderPM Integer yes A flag: take this order into account when calculating free capacity of PM run?
UseOrderFL Integer yes A flag: take this order into account when calculating free capacity of FL run?
top
DDQConsignmentOrders Due date quoting
Due date quoting
DDQ Consignments orders (Consignment and calloforders) are store in this table
name type identity null description
ConsignmentOrderId Identity no Identity of consignment order
CallOfOrderId Identity no Identity of callof order
HeaderCode ShortString no Header code of this query
RequestId Identity no Identity of request
top
DDQFGInventorySourcesData Due date quoting
Temporary table
name type identity null description
ProductId Identity yes
SkuKey String no
ConsignmentLocationId Identity yes
SiteId Identity yes
WHWorkCentreId Identity yes
WHLocationId Identity yes
Priority Integer no
JourneyId Identity yes
IsMain Integer no
DespatchDate Date yes
DeliveryDate Date yes
HasTransportRoute Integer no
HasOnHandInventory Integer no
HasProjectInventory Integer no
IsValid Integer no
top
DDQInquiryMethodTypes Due date quoting
Due date quoting
The table stores the list of types of DDQ inquiry methods. This is a reference table.
name type identity null description
Id Identity yes no Identity
InquiryMethodName String no Inquiry method name
InquiryMethodCode ShortString yes Inquiry method code (JIT, JITP, ASAP)
Description String no Description
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
DDQInventoryData Due date quoting
Temporary table
name type identity null description
SkuKey String no
DateFrom Date no
Opening Float no
OnHandStock Float no
OrdersIn Float no
OrdersOut Float no
Closing Float no
MinClosing Float no
GlobalMinClosing Float no
top
DDQLog Due date quoting
Due date quoting
The table is used to store DDQ operations log
name type identity null description
Id Identity yes no Identity
RequestId Identity yes Request ID
TaskId Identity no Task ID
RequestCode ShortString yes Request code
LogTimeStamp Date no Log entry time stamp
LogSource ShortString yes Log entry source
LogText LongestString yes Log entry text
top
DDQPossibleQuantityData Due date quoting
Due date quoting
The table stores the list of DDQ result.
name type identity null description
WorkCentreCode String yes WorkCentreCode
PossibleQuantity Float yes Possible quantity
top
DDQProductionSourcesData Due date quoting
Temporary table
name type identity null description
SiteId Identity yes
StageNo Identity no
OperationTypeId Identity yes
WorkCentreId Identity no
LocationId Identity no
WHWorkCentreId Identity yes
WHLocationId Identity yes
HasRate Integer no
SPPriority Integer no
JourneyId Identity yes
TransportMethodId Identity yes
TRTime Integer no
TRCost Float no
TRPriority Integer no
TotalCapacityOfRuns Float no
LastRunFinishDate Date yes
top
DDQRequests Due date quoting
Due date quoting
The table contains DDQ requests received from External System/SAP. Some parameters are filled by the request parser on the results of incoming DDQ request analysis. Rows are not removed from this table, because requests are used to maintain the history of DDQ operations.
name type identity null description
Id Identity yes no Identity
RequestCode ShortString no Request code. It is equal to the request identifier from External System/SAP schedule request
Sender ShortString no Sender code (Client's unique identifier)
HeaderCode ShortString yes Header code. Unique symbolic code of the request.It is generated by External System
OldHeaderCode ShortString yes Old header code
AutoCreate Integer yes A flag: create firm orders automatically? (0-No, 1-Yes). If 1, Orders are created instead of inquiry reservations
LineCode String yes Inquiry line number. Always 0 for a new quote and for complete requote. If a specific line is specified for requote, the line is deleted, and new numbering is started from the last line number + 1
OldLineCode String yes Inquiry old line number.
LocationCode String yes I-Plan unique customer location code
LocationId Identity yes Unique location ID. A reference to Locations table
MultiLine Integer no A flag: is the request multiline? (0-No, 1-Yes). Reserved for future use
ProductCode String yes Inquiry product code
ProductId Identity yes Unique product ID. A reference to Materials table
EndCustomerCode String yes I-Plan unique end customer location code
EndCustomerId Identity yes Unique location ID. A reference to Locations table
EndUseCode String yes I-Plan unique end use code
EndUseId Identity yes Unique location ID. A reference to enduses table
SiteMaterialUsageId Identity yes Unique SKU ID. A reference SiteMaterialUsages
InhibitProduction Integer yes A flag: is the use of PM runs and SFG inventories inhibited? (0-No, 1-Yes). If inhibitProduction = 0 then full quantity will be searched only at FG inventories
SFGProductCode String yes SFG product code to use. Overrides specific SFG product code, hard constraint
SFGProductId Identity yes Unique SFG product ID to use. A reference to Materials table
RequestDate Date yes The date that customer requested (can be empty)
ValidRequestDate Date yes The date that customer valid requested (can be empty)
LateDays Integer yes Allowed delivery delay time. Maximal delay in days, after which the customer will still accept the order
InquiryMethodCode ShortString yes Inquiry method code (Possible values: JIT, JITP, ASAP)
InquiryMethodId Identity yes Unique inquiry method ID. A reference to DDQInquiryMethodTypes table
OriginalQuantity Float yes Required quantity the original unit of request.
Quantity Float yes The quantity converted to weight of the specified product (this value is affected by the ProductCode field). Quantity is measured in kilogramms. It must not be less or equal to 0
OriginalUnitName String yes
UnitName String yes
UnitId Identity yes
TransportMethodName String yes Transport method name (A transport code defined in IPlan)
TransportMethodId Identity yes Unique Transport method ID. A reference to TransportMethods table
TypeOfDelivery ShortString yes Type of delivery. Depending on it, the requested date can be: E - ex-mill, A - arrival
ExpiryDate Date yes Reserved for future use
CheckAllocationMethod ShortString yes Reserved for future use
TransportAreaCode ShortString yes Transport area code. Overrides destination transport location. If it is not specified in the request, then the customer location will be used
TransportAreaId Identity yes Unique Transport area ID. A reference to Locations table
SourceWarehouseCode ShortString yes Defines warehouse source. Blank or valid warehouse code
SourceWarehouseId Identity yes Unique warehouse source ID. A reference to WorkCentres table
FixSourceAssignment String yes Specific PM to be used as the material source. The order has to be sourced from a special source (PM). The field can be empty
SourceWorkcentreId Identity yes Specific PM ID. A reference to WorkCentres table
OrderSplit Integer yes A flag: is it allowed to split the order? (0-No, 1-Yes)
SingleSourcing Integer yes A flag: for a split order, is it allowed to source the order from different PMs? (0-No, 1-Yes).
FinishingLock Integer yes Reserved for future use
UseOpportunisticRuns Integer yes A flag: is it allowed to use opportunistic runs? (0-No, 1-Yes).
PartialDelivery Integer yes A flag: is it allowed to generate partial deliveries? (0-No, 1-Yes).
Quality Integer yes A flag: is a special quality required? (0-No, 1-Yes)
StartNotBefore Date yes Start date for the source search. The field can be empty
RequestType Integer yes Request type code (Possible codes: 0-New, 1-Requote, 2-Delete, 3-Resend, 4-Amend)
LoggingLevel Integer yes Logging level (0 - standart level, 255 - developer logging level)
DisregardAllocation Integer yes A flag: disregard allocation? (0-No, 1-Yes)
RequestStatus ShortString yes Status of the request after parsing (Possible values: DISCARD, READY)
SourceTypes Integer yes Allowed source types to use (Possible codes: 0-reserved; 1-FG only; 2-SFG only; 3-SFG and FG; 4-PM only; 5-PM and FG; 6-PM and SFG; 7-PM, SFG and FG)
UseFG Integer yes A flag: is it allowed to use FG inventories? (0-No, 1-Yes)
UseSFG Integer yes A flag: is it allowed to use SFG inventories? (0-No, 1-Yes)
UsePM Integer yes A flag: is it allowed to use PM runs? (0-No, 1-Yes)
InsertDate Date yes When the line was inserted?
JourneyCode String yes Code of journey
JourneyId Identity yes Unique Journey ID.
ConsignmentParameters ShortString yes Is required to indicate if consignment stock should be used, and preferences
ConsignmentLocation ShortString yes Is required to optionally specify a customer’s location code
ConsignmentLocationId Identity yes Unique Consignment Location Id. A reference to Locations table
ReplaceConsignment ShortString yes The value should be 000,100,101,102,110,111,112
ConsignmentOrder Integer no This indicates that the order will produce consignment inventory
AutoConfirm Integer no A flag: confirm orders automatically? (0-No, 1-Yes).
TimeProcessed Integer yes time processed the request
AllowLateOrders Integer no
UseInventory Integer no
UseProjectedInventory Integer no
UseConsignmenmtInventory Integer no
UseProduction Integer no
ReATPRequired Integer yes
SourcingCategories LongString yes
AlternateProducts LongString yes
AlternateProductIdList LongString yes Unique Alternate product ID. A reference to Materials table
AlternateProductSkuIdList LongString yes Unique Alternate SKU ID. A reference SiteMaterialUsages
top
DDQResponseOperations Due date quoting
Due date quoting
The table stores DDQ response operations to send to External System/SAP
name type identity null description
Id Identity yes no Identity
ResponseId Identity no A reference to Responses
OperationNumber Integer no Operation number
WorkCentreCode String yes Workcentre code
ReservationCode ShortString yes Reserved for future use
RunEndDate Date yes Run end date
BlockCode ShortString yes Block code
RunCode LongString yes Run code
SFGProductCode String yes SFG product code
Quantity Float yes Quantity
Unit String yes Unit name
InsertDate Date no When the line was inserted?
top
DDQResponseOperationsHistory Due date quoting
Due date quoting
DDQ response operations sent to External System/SAP
name type identity null description
Id Identity yes no Identity
ResponseId Identity no Response ID
OperationNumber Integer no Operation number
WorkCentreCode String yes Workcentre code
ReservationCode ShortString yes Reserved for future use
RunEndDate Date yes Run end date
BlockCode ShortString yes Block code
RunCode LongString yes Run code
SFGProductCode String yes SFG product code
Quantity Float yes Quantity
Unit String yes Unit name
InsertDate Date no When the line was inserted?
top
DDQResponses Due date quoting
Due date quoting
The table stores DDQ responses to send to External System/SAP
name type identity null description
Id Identity yes no Identity
RequestId Identity no A reference to Requests table
RequestCode ShortString no Request code
Recipient ShortString no Recipient code
HeaderCode ShortString yes Header code
LineCode String yes Line code
SolutionNumber Integer yes Solution number
Status ShortString yes Status code (Possible codes: Confirmed, Infomation, Reserved)
DeliveryDate Date yes Delivery date
DispatchDate Date yes Dispatch date
Quantity Float yes Quantity
Unit String yes Unit name
Weight Float yes Weight
ProductCode String yes Product code
WareHouseCode String yes Warehouse code
InitialPaperMachine String yes Source PM code
ReturnStatus ShortString yes Return status code (Possible values: Success, Failure)
ReturnCode ShortString yes Return code
ExpiredDate Date yes Reserved for future use
JourneyCode String yes Code of Journey
TransportMethodCode String yes Code of TransportMethod
ConsignmentLocation ShortString yes To indicate the consignment location code, if consignment stock is used by the search
OnHandStock Integer no OnHandStock
OrderType ShortString yes OrderType
InsertDate Date no When the line was inserted?
top
DDQResponsesHistory Due date quoting
Due date quoting
The table stores DDQ responses sent to External System/SAP
name type identity null description
Id Identity yes no Identity
RequestId Identity no A reference to Requests
RequestCode ShortString no Request code
Recipient ShortString no Sender code
HeaderCode ShortString yes Header code
LineCode String yes Line code
SolutionNumber Integer yes Solution number
Status ShortString yes Status (Confirmed, Infomation, Reserved)
DeliveryDate Date yes Delivery date
DispatchDate Date yes Despatch date
Quantity Float yes Quantity
Unit String yes Unit name
Weight Float yes Weight
ProductCode String yes Product code
WareHouseCode String yes Warehouse code
InitialPaperMachine String yes PM code
ReturnStatus ShortString yes Return status (Success, Failure)
ReturnCode ShortString yes Return code
ExpiredDate Date yes Reserved for future use
JourneyCode String yes Journey code
TransportMethodCode String yes Code of TransportMethod
ConsignmentLocation ShortString yes To indicate the consignment location code, if consignment stock is used by the search
OnHandStock Integer no OnHandStock
OrderType ShortString yes OrderType
InsertDate Date no When the line was inserted?
top
DDQResultCodes Due date quoting
Due date quoting
The table stores the list of codes of DDQ result. This is a reference table.
name type identity null description
Id Identity yes no Identity
Code ShortString no Result code
Name LongString no Result name
Description LongestString no Result description
SubDesc LongString yes Sub Description
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
DDQResultData Due date quoting
Temporary table
The table stores intermediate data of the the ASAP Evaluation process
name type identity null description
Id Identity no Identity
SourceWorkCentreId Identity yes A reference to the paper machine
FGQuantity Float yes Found FG quantity
FLQuantity Float yes Found FL quantity
DeliveryDate Date yes Delivery date to the destination area
WarehouseId Identity yes A reference to the warehouse
SFGWarehouseId Identity yes A reference to the SFG Warehouse
SFGMaterialId Identity yes A reference to the SFG Material
PMMaterialRunId Identity yes A reference to the PM material run
top
DDQRunsData Due date quoting
Temporary table
name type identity null description
StageNo Identity no
OperationTypeId Identity no
SiteId Identity yes
WorkCentreId Identity no
MaterialRunId Identity yes
RunCode LongString no
BlockRunCode LongString yes
Capacity Float no
Duration Float no
FreeCapacity Float no
FreeDuration Float no
RestoreCapacity Float no
RestoreDuration Float no
Rate Float yes
StartDate Date no
FinishDate Date no
Used Float no
OrderOperationId Identity yes
top
DDQSiteData Due date quoting
Temporary table
The table contains information about available sites (used for Single Stage branch)
name type identity null description
SiteId Identity no A reference to the site
DeliveryDate Date yes Delivery date to the destination area
DespatchDate Date yes Despatch date from the FG Warehouse
TransportMethodId Identity no A reference to the transport method
TransportRouteId Identity no A reference to the transport route
WarehouseId Identity no A reference to the FG warehouse
LocationId Identity no A reference to the location of the FG Warehouse
JourneyId Identity yes A reference to the Journey
top
DDQSitesData Due date quoting
Temporary table
name type identity null description
SiteId Identity yes
WHLocationId Identity no
WHWorkCentreId Identity no
IsMain Integer no
JourneyId Identity yes
DeliveryDate Date yes
DespatchDate Date yes
top
DDQSiteSourceData Due date quoting
Temporary table
The table stores the list of available sites for the DDQ Request It is filled when starting the request, and is cleared when the request finished
name type identity null description
SiteId Identity no Site ID
LastFLDate Date yes The date of the last FL run
TransportRouteId Identity yes Transport route ID
TransportPeriod Integer yes Transport time, days
FinishingWarehouseId Identity yes Finishing warehouse ID on the site
JourneyId Identity yes Journey ID for this site
TransportCost Float yes Full transport cost with consideration the journey and last transport route
LastWHLocationIdOfJourney Identity yes Last location id of FG Warehouse of Journey
top
DDQSourceData Due date quoting
Temporary table
name type identity null description
StageNo Identity no
OperationTypeId Identity no
WorkCentreTypeId Identity no
SiteId Identity yes
WorkCentreId Identity no
WCLocationId Identity no
IsFirstStage Integer no
IsLastStage Integer no
WHLocationId Identity yes
JourneyId Identity yes
TransportMethodId Identity yes
DespatchDate Date yes
DeliveryDate Date yes
IsLocked Integer no
Loss Float no
TotalCost Float no
HandlingDelay Float no
Multiplier Float no
Divider Float no
CreateOrder Integer no
OrderQuantity Float no
LastRunDate Date yes
Allocation Float no
top
DDQSourcePrioritiesData Due date quoting
Temporary table
From which workcentres SKU warehause will be replenished. It depends from Priority
name type identity null description
SiteMaterialUsageId Identity no Destination SiteMaterialUsage identity
WorkCentreId Identity no A reference to Workcentres
Priority Integer no Source priority (1, 2, empty, 0)
Portion Integer no Percent of the source use, along with other sources of the given SKU
top
DDQSplittedOrders Due date quoting
Due date quoting
DDQ splited orders (production and customers orders) are stored in this table
name type identity null description
CustomerOrderId Identity no Identity of customer order
ProductionOrderId Identity no Identity of production order
top
DDQTasks Due date quoting
Due date quoting
The table contains the list of DDQ inquiries accepted for processing. As soon as a DDQ inquiry is accepted, the corresponding task is created here
name type identity null description
Id Identity yes no Identity
Started TimeStamp no Task start timestamp
Finished TimeStamp yes Task finish timestamp
Status Identity no Status
RequestId Identity yes Request ID
RequestCode ShortString yes Request code
LogLevel Identity no Logging level
LogId Identity yes Log ID
UserId Identity no User ID
top
DDQTimeStamps Due date quoting
Temporary table
The table contains time stamps of program part runs
name type identity null description
Id Identity yes no Identity
TSValue String no Duration of the part (TimeStamp format)
TSName String no Name of the part
top
DDQUnConfirmedOrders Due date quoting
Due date quoting
DDQ unconfirmed orders are stored in this table
name type identity null description
Id Identity yes no Identity
OrderLineId Identity no A reference OrderLines
HeaderCode ShortString yes Header code (It is equal to inquiry header number)
LineCode ShortString yes Line code (It is equal to inquiry line number)
CreationSetTime Date yes Set creation time
ExpiryDate Date yes Expiry Date
top
DDQWarehouseSourcesData Due date quoting
Temporary table
name type identity null description
SiteId Identity yes
WorkCentreId Identity no
LocationId Identity no
IsMain Integer no
JourneyId Identity yes
TransportMethodId Identity yes
DespatchDate Date yes
DeliveryDate Date yes
TRTime Integer no
TRCost Float no
TRPriority Integer no
SPPriority Integer no
top
DeletedRuns Block Scheduling
Block Scheduling
The table stores information about deleted runs.
name type identity null description
Id Identity yes no Run Identity
MaterialBlockId Identity yes no Run Identity
BlockCode LongString no Run code
RunCode LongString no Run code
NominalCapacity Float no Run capacity
Quantity Float no Run capacity
WasteTime Float yes Time waste
ProcessRate Float yes Production rate of the run
StartDate Date no Run start date
FinishDate Date no Run end date
TargetStartDate Date yes Run target start date
InitialDuration Float no Initial duration and real run duration, including changeover
SwitchoverDuration Float yes Changeover duration. This duration is a part or run duration
QuantityComplete Float no Cumulative run quantity produced on the productionUpdateTimestamp
ProductionUpdateTimestamp Date yes Date of production update (timestamp)
MaterialRunStatusId Identity no A reference to MaterialRunStatuses
FPReleaseDate Date yes Last date when the run was sent to Fine Planning system. For runs which are received from External System this date is equal to MINDATE
WorkcentreId Identity no A reference to Workcentres.Id
RunType String yes Run type: production, floating shut or opportunistic run
SpecificWeight Float yes Specific weight (From production rates)
IsFixed Integer no Indicator that required recalculation for order line dates. Used during Fine Planning update
IsSent Integer no
SendTimestamp Date yes Date of send (timestamp)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Deliveries Replenishment
Replenishment
The table stores the list of delivery dates (i.e. when items will be delivered)
name type identity null description
Id Identity yes no Identity
DeliveryCode String no Delivery code
ShipDate Date no The date when the item was (or will be) shipped
DueDate Date yes The date when the item is due to get to the destination
ReceivedDate Date no The date when the item arrived to the destination
OriginalWeight Float no Delivery original weight
Weight Float no Delivery weight - can be changed by separatedDeliveries
SourceWeight Float no Delivery source weight
SourceCoef Float no Weight / Source Weight coeficient
OrderLineId Identity no Order line identification number
OrderBookDeliveryId Identity yes Order book delivery identification number
SiteMaterialUsageId Identity no SKU
SourceSiteMaterialUsageId Identity yes Source SKU
ToConsignmentLocationId Identity yes for consignment orders, this indicates the consignment location that the order will be stored for at the destination location
FromConsignmentLocationId Identity yes for call off orders, this indicates the consignment location that the stock is being sourced from
IsForecasted Integer no IsForecasted - copy from OrderLine
DeliveryStatusId Identity no Delivery status identifier
SkuKey String no Destination SKU Code - SKU-CS.
SourceSkuKey String yes FROM SKU Code - SourceSKU-CS.
StockSkuKey String yes FROM SKU Code - SourceSKU-CS. From order line stock location
AlternativeKey String yes Alternative Key
reATPOrderCode String yes reATP Order Code
reATPOrderLine String yes reATP Order Line
reATPOrderLineId Identity yes reATP Order Line Identity
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
DeliveryStatuses Replenishment
Replenishment
The table stores the list of possible statuses of delivery processes
name type identity null description
Id Identity yes no Identity
DeliveryStatusName ShortString no Delivery status name
DeliveryStatusDesc String no Delivery status description
DeliveryStatusCode String yes Delivery status code
Abbreviation ShortString yes Delivery status abbreviation
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
DerivedCharacteristicRules Core
Core
The table stores forecast method rules
name type identity null description
Id Identity yes no Identity
ReportFilterId Identity yes Filter Id
DerivedCharacteristicId Identity no Derived characteristic identity
RuleWeighting Integer no Rule Weighting
CharacteristicValue LongString no Value
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
DerivedCharacteristics Core
Core
The table stores the list of derived characteristics.
name type identity null description
Id Identity yes no Identity
CharacteristicName String no Property name
HierarchyLevelNo Integer no Property name
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Dictionaries Core
Language
The table stores the dictionary of localizable words. It is used when localizing grids, captions, filters and other interface elements
name type identity null description
Id Identity yes no Identity
DictionaryKey LongestString no Dictionary key
DictionaryValue LongestString no Dictionary value
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
EndUseProperties Core
Core
The table stores the list of properties registered in the system
name type identity null description
Id Identity yes no Identity
PropertyName String no Property name
HierarchyLevelNo Integer no Property name
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
EndUses Core
Core
The table stores the list of properties registered in the system
name type identity null description
Id Identity yes no Identity
EndUseCode String no Property name
EndUseDescription String no Property code
EndUseProperties LongestString yes EndUse properties
Property1 String yes Property
Property2 String yes Property
Property3 String yes Property
Property4 String yes Property
Property5 String yes Property
Property6 String yes Property
Property7 String yes Property
Property8 String yes Property
Property9 String yes Property
Property10 String yes Property
Property11 String yes Property
Property12 String yes Property
Property13 String yes Property
Property14 String yes Property
Property15 String yes Property
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
EntitiesForExternalSystem Replenishment
Replenishment
Store entity identifiers for sending into another external system
name type identity null description
EntityId Identity no Original entity identity
TargetSystem String no Target system
EntityType String no Entity type
TimeStamp TimeStamp no When record added
IsSent Integer no Is order line sent
top
EventLogs Core
Logging
The table stores the log of events occured in the system
name type identity null description
Id Identity yes no Identity
DateAppearence Date no The date when the event occured
Tier ShortString yes Event level code. Possible values: com+, db
DescriptionForDeveloper HugeString yes Extented event description
FormattedDescription LongestString yes Procedure or com+ method where the event detected
EventMessageId Identity no A reference to the standard message
UserId Identity no User ID
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
EventMessages Core
Logging
Event patterns for creation events in event log
name type identity null description
Id Identity yes no Identity
EventName String no Event name
EventDescription LongestString no Event description
EventTypeId Identity no Event type reference
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
EventTypes Core
Reference
The table stores the list of event types that can be registered in the event log
name type identity null description
Id Identity yes no Identity
EventTypeName String no Event type name. Possible values: FatalError, Error, Warning, Message, etc.
EventLevel Integer no Event level
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ExchangeRates Core
Core
The table stores the list of exchange rates registered in the system
name type identity null description
Id Identity yes no Identity
CurrencyId Identity no This is the currency to convert to from the system's base currency
EffectiveDate Date no Date that the exchange rate becomes effective
Multiplier DoubleFloat no The value to multiply the base currency by to convert to the specified currency. Can be used in conjunction with divider to specify the rate as a fraction
Divider DoubleFloat no Used with the multiplier to calculate the rate to convert from the base currency to the specified currency. Not usually required (hence defaults to 1), but useful if the exchange rate is a very low value to avoid rounding errors, eg the old Turkish lira was over 1,000,000 to the GBP
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ExcludedPropertiesFromSA Master Planning
Allocations
name type identity null description
PropertyId Identity no Property ID (A reference to Properties)
Value String no Property value
top
ExpandedCostRules Core
Core
The table stores costs per products
name type identity null description
CostRuleId Identity no A reference to CostRules
MaterialId Identity no A reference to the Properties table
OperationTypeId Identity yes A reference to the operation types
Priority Integer no
top
ExpandedExchangeRates Core
Core
The table stores the list of exchange rates registered in the system
name type identity null description
CurrencyId Identity no This is the currency to convert to from the system's base currency
DateFrom Date no Date that the exchange rate becomes effective
DateTo Date no Date that the exchange rate becomes effective
Multiplier DoubleFloat no The value to multiply the base currency by to convert to the specified currency. Can be used in conjunction with divider to specify the rate as a fraction
Divider DoubleFloat no Used with the multiplier to calculate the rate to convert from the base currency to the specified currency. Not usually required (hence defaults to 1), but useful if the exchange rate is a very low value to avoid rounding errors, eg the old Turkish lira was over 1,000,000 to the GBP
top
ExpandedHierarchies Core
Core
The table describes relations between other hierarchies and their locations
name type identity null description
HierarchyId Identity no Hierarchy identity
ParentHierarchyId Identity no Parent hierarchy identity
HierarchyLevelId Identity no Hierarchy level identity
top
ExpandedHierarchiesSpec Core
Core
The table stores hierarchies (specifications) in unfolded form
name type identity null description
HierarchyId Identity no hierarchy identity
HierarchyName1 String yes Hierarchy Name
HierarchyName2 String yes Hierarchy Name
HierarchyName3 String yes Hierarchy Name
HierarchyName4 String yes Hierarchy Name
HierarchyName5 String yes Hierarchy Name
HierarchyName6 String yes Hierarchy Name
HierarchyName7 String yes Hierarchy Name
HierarchyName8 String yes Hierarchy Name
HierarchyName9 String yes Hierarchy Name
HierarchyName10 String yes Hierarchy Name
HierarchyName11 String yes Hierarchy Name
HierarchyName12 String yes Hierarchy Name
HierarchyName13 String yes Hierarchy Name
HierarchyName14 String yes Hierarchy Name
HierarchyName15 String yes Hierarchy Name
HierarchyCode1 ShortString yes Hierarchy Code
HierarchyCode2 ShortString yes Hierarchy Code
HierarchyCode3 ShortString yes Hierarchy Code
HierarchyCode4 ShortString yes Hierarchy Code
HierarchyCode5 ShortString yes Hierarchy Code
HierarchyCode6 ShortString yes Hierarchy Code
HierarchyCode7 ShortString yes Hierarchy Code
HierarchyCode8 ShortString yes Hierarchy Code
HierarchyCode9 ShortString yes Hierarchy Code
HierarchyCode10 ShortString yes Hierarchy Code
HierarchyCode11 ShortString yes Hierarchy Code
HierarchyCode12 ShortString yes Hierarchy Code
HierarchyCode13 ShortString yes Hierarchy Code
HierarchyCode14 ShortString yes Hierarchy Code
HierarchyCode15 ShortString yes Hierarchy Code
top
ExpandedLocations Core
Core
The table describes relations between hierarchies and their locations
name type identity null description
HierarchyId Identity no Hierarchy node ID
LocationId Identity no Location ID
top
ExpandedLocationsSpec Core
Core
The table describes relations between locations and their hierarchies
name type identity null description
LocationId Identity no Location identity
LocationName LongString no Location name
LocationCode ShortString no Location code
HierarchyName1 String yes Hierarchy Name
HierarchyName2 String yes Hierarchy Name
HierarchyName3 String yes Hierarchy Name
HierarchyName4 String yes Hierarchy Name
HierarchyName5 String yes Hierarchy Name
HierarchyName6 String yes Hierarchy Name
HierarchyName7 String yes Hierarchy Name
HierarchyName8 String yes Hierarchy Name
HierarchyName9 String yes Hierarchy Name
HierarchyName10 String yes Hierarchy Name
HierarchyName11 String yes Hierarchy Name
HierarchyName12 String yes Hierarchy Name
HierarchyName13 String yes Hierarchy Name
HierarchyName14 String yes Hierarchy Name
HierarchyName15 String yes Hierarchy Name
HierarchyCode1 ShortString yes Hierarchy Code
HierarchyCode2 ShortString yes Hierarchy Code
HierarchyCode3 ShortString yes Hierarchy Code
HierarchyCode4 ShortString yes Hierarchy Code
HierarchyCode5 ShortString yes Hierarchy Code
HierarchyCode6 ShortString yes Hierarchy Code
HierarchyCode7 ShortString yes Hierarchy Code
HierarchyCode8 ShortString yes Hierarchy Code
HierarchyCode9 ShortString yes Hierarchy Code
HierarchyCode10 ShortString yes Hierarchy Code
HierarchyCode11 ShortString yes Hierarchy Code
HierarchyCode12 ShortString yes Hierarchy Code
HierarchyCode13 ShortString yes Hierarchy Code
HierarchyCode14 ShortString yes Hierarchy Code
HierarchyCode15 ShortString yes Hierarchy Code
top
ExpandedMasterRouteSnapshots Master Planning
Master Planning
The table contains user snapshots of master routes
name type identity null description
SnapshotUserId Identity no Snapshot user ID (A reference to Users)
ScenarioId Identity no Snapshot user ID (A reference to Users)
Id Identity yes no Identity
Cost DoubleFloat no Cost
MinCapacity Float no Min. Capacity
MaxCapacity Float no Max. Capacity
TimePeriod Integer no timeperiod in days
FromSiteId Identity no From site ID (reference to site id)
ToHierarchyId Identity no Detail Id
Type String yes Master route type
top
ExpandedMaterials Core
Core
The table describes relations between materials and their properties
name type identity null description
PropertyValueId Identity no A reference to PropertyValues
MaterialId Identity yes A reference to Materials
top
ExpandedNominalCosts Forecasting
Forecasting
The table stores monthly forecasts for SKUs
name type identity null description
DateFrom Date no Day from
DateTo Date no Day toMonth
SiteMaterialUsageId Identity no A reference to the corresponding SKU
Cost DoubleFloat no Cost for SKU
CurrencyId Identity yes A reference to the corresponding currencies
NominalCostRuleId Identity no A reference to the corresponding currencies
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
ExpandedPrices Forecasting
Forecasting
The table stores prices from price rules for each SKU
name type identity null description
DateFrom Date no Day from
DateTo Date no Day toMonth
SiteMaterialUsageId Identity no A reference to the corresponding SKU
Price Float no Price for SKU
CurrencyId Identity yes A reference to the corresponding currencies
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
ExpandedPropertyValues Core
Core
The table stores property values in unfolded form
name type identity null description
PropertyValueId Identity no A reference to PropertyValues
ParentPropertyValueId Identity no Identity of the parent property value
PropertyId Identity no A reference to Properties
top
ExpandedSKUNominalCosts Core
Core
The table store combination sku/nominalcost rules for faster nominalcost updates with system where used non-sku-based nominalcosts
name type identity null description
SiteMaterialUsageId Identity no A reference to the corresponding SKU
NominalCostRuleId Identity no NominalCost rule Id
DateFrom Date no Day from
Cost DoubleFloat no Cost for SKU
Priority Integer no Cost for SKU
CurrencyId Identity no A reference to the corresponding currencies
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
ExpandedSKUPrices Forecasting
Forecasting
The table store combination sku/price rules for faster price updates with system where used non-sku-based prices
name type identity null description
SiteMaterialUsageId Identity no A reference to the corresponding SKU
PriceRuleId Identity no Price rule Id
DateFrom Date no Day from
Price Float no Price for SKU
Priority Integer no Price for SKU
CurrencyId Identity no A reference to the corresponding currencies
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
ExternalAllocationSnapshots Master Planning
Master Planning
Allocations from external supplier
name type identity null description
ScenarioId Identity no Scenario ID (A refernce to Scenarios)
SnapshotUserId Identity no User ID (A reference to Users)
Id Identity no SNP Item Id
MaterialId Identity no SNP Item Id
SiteMaterialUsageId Identity no SKU Id
FixedSourceId Identity no fixed source Id
DeliveryDate Date no Demand date
SourceDate Date no Sourcing date
SiteId Identity no Site ID (A reference to Sites)
WorkCentreId Identity yes Workcentre ID (A reference to Workcentres)
MasterRouteId Identity yes Master route ID(A reference to MasterRoutes)
Allocation Float no Allocation value on the external source
Price Float no Revenue
Revenue Float no Revenue
ProductionCost Float no ProductionCost
TransportCost Float no TransportCost
Margin Float no Margin
top
ExternalFixedSources Core
Core
The table stores sources to external suppliers
name type identity null description
Id Identity yes no Identity
DetailId Identity no Weight of rule
WorkcentreId Identity no External supplier
DateFrom Date no Datefrom
DateTo Date yes Date to
Capacity Float no Available capacity per period type
PeriodType String no Period type: week or month
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ExternalMessageLogs Core
Logging
The table is used to maintain external messages log
name type identity null description
Id Identity no Identity
GUID String no GUID
numberOfMessages Identity no Number of received messages
processedMessages Identity no Number of processed messages
FailedMessages Identity no Number of failed messages
TimeStamp ShortString yes The moment when the record was inserted
InsertDate Date yes The date when the record was inserted
top
FailedMessages Core
Logging
The table is used to store failed external messages during processing external messages
name type identity null description
GUID String no Identity (GUID)
OriginalStamp Date no The Original time stamp
Stamp Date no The time stamp
SecurityRoleId Identity yes Role ID
QueueType String no can be MSMQ, AQ or Folder
ElementName String no The element name of failed message
Message Text no The message body
ErrorText Text no The error text
top
FavoritePages Core
Access rights
The table stores favorite pages
name type identity null description
PageId Identity no Page Id
SelectedTimes Identity no How many times page was selected
UserId Identity no UserId
top
FilterBasedRules Reference
Reference
name type identity null description
Id Identity no Rule Id
FilterType String no Rule Type
FilterColumns LongestString yes Filter fields with delimiters
FilterValues LongestString yes Filter Values with delimiter
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
FilterHistories Core
Configuration
The table contains the list select columns (Summary levels) for grids
name type identity null description
TaskName String no Grid Id
ReportFilterid Identity no Report filter
IsLast Integer no Is last created
InsertDate Date no Is last created
InsertUserId Identity no Is last created
top
FittedHistories Forecasting
Forecasting
The table stores fitted history after forecast generation
name type identity null description
SiteMaterialUsageId Identity no SKU (A reference to SiteMaterialUsages)
DateFrom Date no Date
Weight Float no Weight
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
FixedSourceSnapshots Core
Core
The table stores sources to external suppliers
name type identity null description
SnapshotUserId Identity no Id
ScenarioId Identity no Id
Id Identity yes no Identity
DetailId Identity no Weight of rule
WorkcentreId Identity no External supplier
DateFrom Date no Date from
DateTo Date yes Date to
Capacity Float no Available capacity per period type
PeriodType String no Period type: week or month
top
FLforPMData Due date quoting
Temporary table
The table stores the list of FL machines associated with paper machines. The table is filled when searching FL runs by the ddq.getPMForInquiryMethod procedure.
name type identity null description
FLId Identity no A reference to the FL machine
PMId Identity yes A reference to the paper machine
PMCode String yes Paper machine code
SiteId Identity yes Reference to the site
top
ForecastBodies Forecasting
Forecasting
name type identity null description
Id Identity yes no Identity
DateFrom Date no Month
ForecastId Identity no A reference to the corresponding forecast
SiteMaterialUsageId Identity no A reference to the corresponding SKU
OriginalSystem Float no Original forecast value generated by system (by first pass forecast generation)
System Float no Forecast value generated by system
Customer Float no Forecast value edited by customer
Final Float no Final forecast value
ForecastAllocation Float no Forecast allocation)
IsWorking Integer no A switch. Possible values: 0 - forecast state unchanged, or the forecast released; 1 - the forecast has been carried from the previous forecast, 2 - the forecast has been modified (edited) )
EditGroupId Identity yes forecast changes id
EditGroupFinalId Identity yes forecast changes id
OriginalEditGroupId Identity yes original forecast final change id
ForecastStatusId Identity no Forecast status (system, customer, final)
WeeklyEdited Integer yes A flag that value was edited on weekly level
Upper Float yes Upper percentile generated by ForecastPro
Lower Float yes Lower percentile generated by ForecastPro
OriginalUpper Float yes Upper percentile generated by ForecastPro
OriginalLower Float yes Lower percentile generated by ForecastPro
PriceCurrencyId Identity no Price Currency Id
SystemPrice Float no System Price
ForecastedPrice Float no Forecasted Price
CostCurrencyId Identity no Cost Currency Id
NominalCost DoubleFloat no Nominal Cost
NominalCostAdjustment Float no Nominal Cost adjustment
ValueAddAdjustment Float no Value Add adjustment
SafetyStock Float yes Safety Stock generated by ForecastPro
SystemWeeklyCoefId Identity yes System weekyl coef id
CustomerWeeklyCoefId Identity yes System weekyl coef id
FinalWeeklyCoefId Identity yes System weekyl coef id
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastBodySnapshots Master Planning
Master Planning
The table contains snapshots of weekly forecasts.
name type identity null description
SnapshotState Identity no State code: 0 - base line; 1- current
SnapshotUserId Identity no User ID (A reference to Users)
DateFrom Date no Week
System Float no The value of the forecast at the moment when the session was created
Customer Float no Forecast value modified by user during the SNO session
MandatoryDemand Float no Demand Increased by MinAllocation
Orders Float no Firm order weight value
Demand Float no Forecast value modified by firm order netting during the SNO session
Netted Float no Forecast value modified by firm order netting during the SNO session
PreAllocated Float no Demand after pre-alliocatiing from external sources
Aggregated Float no Forecast value after aggregation
TotalDemand Float no Aggregated cleared on orders
AfterPreNetting Float no Forecast value after prenetting
SnoDemand Float no Sno demand
Id Identity no SNO Item ID (A reference to )
SitematerialusageId Identity no SKU ID (A reference to Sitematerialusages)
MaterialId Identity no Materials Id of the SKU. Used for performance purposes.
ToHierarchyId Identity yes (Other)Hierarchy Id of the SKU location. Used for performance purposes.
IsWorking Integer yes A flag (2 - customer value has been edited, 0 - unchanged
IsOrder Integer yes A flag have this sku order or have not
Price Float yes The price of this item in base currency units
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastChangeDetails Forecasting
Forecasting
The table stores detailed set of property values for each edit action
name type identity null description
ForecastChangeId Identity no Edit action ID (A reference to ForecastChanges table)
FieldName String no Property ID (A reference to Properties)
Value String yes Property value
Operation String no Comparison operation
top
ForecastChanges Forecasting
Forecasting
The table stores the list of forecast changes and comments
name type identity null description
Id Identity yes no Identity
DateFrom Date no Date of the change (month or week)
PeriodRange String no Period range - Week or Month
ReasonId Identity yes A reference to Reasons
Operation String no A reference to ForecastOperations
ForecastId Identity yes System forecast (A reference to Forecasts)
ForecastSnapshotId Identity yes System forecast (A reference to Forecasts)
UnitId Identity yes The unit on which the edit has been made (A reference to Units)
CurrencyId Identity yes The currency for price changes
ForecastStatusId Identity no Forecast status
IsDisplayComment Identity no A flag: is this record a forecast comment?
InitValue Float no Forecast value before modification
LastValue Float no Forecast value after modification
ForecastComment HugeString yes Forecast comment
CommentLink HugeString yes Complex link to this comment from matrix or collaboration screen
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastChangeSku Forecasting
Forecasting
The table stores detailed set of property values for each edit action
name type identity null description
ForecastChangeId Identity no Forecast Change Id
SiteMaterialUsageId Identity no Sku Identity
IsActive Integer no Is active to take into consideration in carrying forecast
top
ForecastCollaborationData Forecasting
Forecasting
A temporary table for forecast collaboration
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
Id Identity no Grouped Identity
DateFrom Date yes date
System Float no
Customer Float no
Final Float no
Orders Float no
Allocations Float no Current allocations
ForecastAllocation Float no Forecast allocation
Budget Float no
Price Float yes Forecasted Price
SystemPrice Float yes System Price
Revenue Float yes Revenue
NominalCost DoubleFloat no
TotalNominalCost DoubleFloat no
NominalCostAdjustment Float no
ValueAdd Float yes
ValueAddAdjustment Float no
TotalValueAdd Float no
UnallocatedRevenue Float yes Unallocated Revenue
Unallocated Float yes
UnallocatedTotalCost Float yes
UnallocatedValueAdd Float yes
IsWorking Integer no
EditableCustomer Integer no
EditableFinal Integer no
EditableForecastAllocation Integer no
EditablePrice Integer no
ForecastStatusId Integer no
HasComment Integer no
CustomerCssClass String yes
FinalCssClass String yes
CustomerForecastComment LongestString yes
FinalForecastComment LongestString yes
OriginalCustomerComment LongestString yes
OriginalFinalComment LongestString yes
FinancialToolTip LongestString yes
CustomerForecastChangeId Identity yes
CustomerReasonId Identity yes
FinalForecastChangeId Identity yes
FinalReasonId Identity yes
PriceForecastChangeId Identity yes
PriceReasonId Identity yes
PriceComment LongestString yes
OriginalPriceComment LongestString yes
PriceHasComment Integer no
NominalCostForecastChangeId Identity yes
NominalCostReasonId Identity yes
NominalCostComment LongestString yes
OriginalNominalCostComment LongestString yes
NominalCostHasComment Integer no
ValueAddForecastChangeId Identity yes
ValueAddReasonId Identity yes
ValueAddComment LongestString yes
OriginalValueAddComment LongestString yes
ValueAddHasComment Integer no
OriginalVAAdjustment Float no
OriginalNCAdjustment Float no
OriginalPrice Float no
top
ForecastEvents Forecasting
Forecasting
A table stored forecast events per month/SKU
name type identity null description
Id Identity yes no Identity
DateFrom Date no Month
SiteMaterialUsageId Identity yes SKU ID (A reference to SiteMaterialUsages)
ForecastEventTypeId Identity no Forecast Event Type
InsertUserId Identity no The ID of the user who have inserted the line
InsertDate Date no The ID of the user who have inserted the line
top
ForecastEventTypes Forecasting
Forecasting
A table stored forecast events types
name type identity null description
Id Identity yes no Identity
ForecastEventName String no Forecast event name
InsertUserId Identity no The ID of the user who have inserted the line
InsertDate Date no The ID of the user who have inserted the line
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastHistoryData Forecasting
Forecasting
A temporary table for history calculation, including in account suppercessions. This is helper table and calculated during forecast generation.
name type identity null description
DateFrom Date no Month
SiteMaterialUsageId Identity no SKU (A reference to SitematerialUsages)
History1 Float yes history for month year ago
History2 Float yes average history for last 3 months
History3 Float yes history for 1 months ago
History4 Float yes average history for last 6 months
History5 Float yes history for 2 months ago
History6 Float yes history for 3 months ago
History7 Float yes history from begging of year to current month
SupercessionHistory1 Float yes history for month year ago including supercession
SupercessionHistory2 Float yes average history for last 3 months including supercession
SupercessionHistory3 Float yes history for 1 months ago including supercession
SupercessionHistory4 Float yes average history for last 6 months including supercession
SupercessionHistory5 Float yes history for 2 months ago including supercession
SupercessionHistory6 Float yes history for 3 months ago including supercession
SupercessionHistory7 Float yes history from begging of year to current month including supercession
top
ForecastItemsData Forecasting
Forecasting
A temporary table for forecast collaboration
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
Id Identity no Grouped Identity
Summary HugeString yes Summary fields
CommentLink HugeString yes Comment link expression
Items ForecastItemArray yes Grouped Identity
top
ForecastLaunchProfiles Forecasting
Forecasting
A table stored forecast launch profiles
name type identity null description
Id Identity yes no Identity
ProfileName String no Launch profile name
HistoryValues HugeString no Comma separated history values
HistoryStartDate Date yes History Start Date
LaunchDate Date yes Launch date
LaunchTotal Float yes Total amount per horizon
InsertUserId Identity no The ID of the user who have inserted the line
InsertDate Date no The ID of the user who have inserted the line
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastMethodRules Core
Core
The table stores forecast method rules
name type identity null description
Id Identity yes no Identity
DetailId Identity no Characteristics Id
RuleWeighting Identity no Rule weighting
ForecastMethodId Identity no Forecast method
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastMethods Forecasting
Forecasting
The table stores forecast method definitions
name type identity null description
Id Identity yes no Identity
ForecastMethodName LongString no Forecast method name
ForecastMethodDesc LongString no Description of the forecast method type
Internal Integer no An internal flag
ForecastMethodTypeId Identity no Type of the forecast method (A reference to ForecastMethodTypes)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastMethodTypeParameters Forecasting
Forecasting
The table stores definitions of forecast method type parameters
name type identity null description
Id Identity yes no Identity
ParameterId Identity no Paramater (A reference to ForecastParameters)
ForecastMethodTypeId Identity yes Forecast Method Type (A reference to ForecastMethodTypes)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastMethodTypes Forecasting
Forecasting
The table stores forecast method type definitions
name type identity null description
Id Identity yes no Identity
ForecastMethodTypeName String no Forecast method type name
ForecastMethodTypeDesc String no Description of the forecast method type
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastOperations Forecasting
Forecasting
The table stores the list of available forecast operations
name type identity null description
Id Identity yes no Identity
Name String no Operation name
Description LongString yes Operation description
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastParameters Forecasting
Forecasting
The table stores forecast parameter definitions
name type identity null description
Id Identity yes no Identity
ParameterName String no Parameter name
ParameterDescription String no Parameter description
DefaultValue String no Default value
DataType ShortString no Data type of the parameter
DataMask String yes Data mask of the parameter
BundleId Identity yes Bundle Values
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastParameterValues Forecasting
Forecasting
The table stores forecast parameter values
name type identity null description
Id Identity yes no Identity
Value String no Parameter value
ForecastMethodId Identity no Forecast method (A reference to ForecastMethods)
ForecastParameterId Identity no Forecast parameter (A reference to ForecastParameters)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastPatterns Forecasting
Forecasting
A table stored forecast patterns
name type identity null description
Id Identity yes no Identity
ForecastPatternName String no Forecast pattern name
PatternValues HugeString no Comma separated values
StartDate Date yes Start Date
InsertUserId Identity no The ID of the user who have inserted the line
InsertDate Date no The ID of the user who have inserted the line
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastRanges Forecasting
Forecasting
The ranges for daily distribution across months in weekly forecasting.
name type identity null description
Id Identity yes no Identity
RangeName String no Month
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastRangeValues Forecasting
Forecasting
The range values for daily distribution across months in weekly forecasting.
name type identity null description
Id Identity yes no Identity
RangeId Identity no Forecast distribution range
DayFrom Integer no Day from
DayTo Integer no Day to
Percentage Float no Day to
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Forecasts Forecasting
Forecasts
The table stores the list of forecasts existing in the system
name type identity null description
Id Identity yes no Identity
Horizon Identity no Length of the forecast horizon, months
Offset Integer no offset in months for forecast start date
StartDate Date no The first month where starts forecast values
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastSampleBodies Forecasting
Forecasting
name type identity null description
Id Identity yes no Identity
DateFrom Date no Month
ForecastSampleId Identity no A reference to the corresponding forecast snapshot
ForecastSampleMethodId Identity no Forecast sample method
Forecast Float no Forecast value generated by system
Upper Float no Upper percentile generated by ForecastPro
Lower Float no Lower percentile generated by ForecastPro
SafetyStock Float no Safety Stock generated by ForecastPro
top
ForecastSampleFittedHistories Forecasting
Forecasting
The table stores fitted history after forecast sample generation
name type identity null description
ForecastSampleId Identity no SKU (A reference to SiteMaterialUsages)
ForecastSampleMethodId Identity no SKU (A reference to SiteMaterialUsages)
DateFrom Date no Date
Weight Float no Weight
top
ForecastSampleHistory Forecasting
Forecasting
A temporary table for history calculation, populated during forecast generation.
name type identity null description
ForecastSampleId Identity no Forecast sample identity
DateFrom Date no Month
Weight Float no History weight
top
ForecastSampleMethods Forecasting
Forecast Sample
name type identity null description
Id Identity yes no Identity
ForecastSampleId Identity no A reference to the corresponding forecast sample
ForecastMethodId Identity no Forecast method
MethodName LongString no Forecast method name
InsertUserId Identity yes Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastSamples Forecasting
Forecasts
The table stores the list of forecasts samples
name type identity null description
Id Identity yes no Identity
HistoryStartDate Date yes The history start month (from use limited set)
StartDate Date no The start month
FinishDate Date no The end month
Name String no Forecast sample name
UserId Identity no User identity (owner)
ReportFilterId Identity yes Filter for limit SKU inside sample
SecondForecastMethods HugeString yes Second pass methods - comma separated list
InsertUserId Identity yes Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastSampleSku Forecasting
Temporary
Temporary table for selective or full forecast generation process. Table contains the list of skus
name type identity null description
ForecastSampleId Identity no Id from SecondPass properties
SiteMaterialUsageId Identity no Sku Id
HistoryStartDate Date yes History Start Date
Seasonality Identity yes Exponential smoothing No seasonality = 0 Additive seasonality=1 Multiplicative seasonality = 2
Trend Identity yes Exponential smoothing No trend = 0 Linear trend = 1 Decaying trend = 2 Exponential = 3
top
ForecastSampleStatistics Forecasting
Temporary
Temporary table for selective or full forecast generation process. Table contains the list of skus
name type identity null description
ForecastSampleId Identity no Id from SecondPass properties
ForecastSampleMethodId Identity no Sample method Id
ForecastMethodId Identity no Sample method Id
Seasonality Identity yes Exponential smoothing No seasonality = 0 Additive seasonality=1 Multiplicative seasonality = 2
Trend Identity yes Exponential smoothing No trend = 0 Linear trend = 1 Decaying trend = 2 Exponential = 3
UsedExternalTrends HugeString yes Used external trends
ymean Float yes Mean of the historic series used to fit the model
ysdev Float yes Standard deviation of the historic series used to fit the model
sigma Float yes Standard forecast error of the model over the fitted data.
rmserr Float yes Root mean square forecast error of the model over the fitted data.
adjrsq Float yes Adjusted R-square
mape Float yes Mean absolute percent error.
smape Float yes Symmetric mean absolute percent error
mad Float yes Mean absolute deviation of the actual from the fitted fore-cast.
ErrorStdDev Float yes Standard deviation of errors
MethodTextReport HugeString yes Method Text Report
top
ForecastSnapshotBodies Forecasting
Forecasting
name type identity null description
Id Identity yes no Identity
DateFrom Date no Month
ForecastSnapshotId Identity no A reference to the corresponding forecast snapshot
SiteMaterialUsageId Identity no A reference to the corresponding SKU
Final Float no Forecast value generated by system
FinalWeeklyCoefId Identity yes Final weekly coefficient id
AllocationWeeklyCoefId Identity yes Allocation weekly coefficient id
Unallocated Float no Unallocated demand
ForecastStatusId Identity no Forecast status (system, customer, final)
PriceCurrencyId Identity no Price Currency Id
SystemPrice Float no System Price
ForecastedPrice Float no Forecasted Price
CostCurrencyId Identity no Cost Currency Id
NominalCost DoubleFloat no Nominal Cost
NominalCostAdjustment Float no Nominal Cost adjustment
ValueAddAdjustment Float no Value Add adjustment
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastSnapshots Forecasting
Forecasts
The table stores the list of forecasts existing in the system
name type identity null description
Id Identity yes no Identity
StartDate Date no The first month after the forecast horizon
FinishDate Date no The first month after the forecast horizon
Name String no Forecast snapshot name
Description String no Forecast snapshot description
UserId Identity no Snapshot owner identifier
IsBudget Integer no Is this a budget
IsShowOnGraph Integer no Should this snapshot shown on the graph.
IsConstrained Integer no Is this constrained snapshot.
UnconstrainedSnapshotId Identity yes Unconstrained snapshot identifier
NewSkuMask LongString yes Mask for new products
AutoSkuStatus ShortString no Status for sku - All - turn on for forecast and replenishment, Forecast - just forecast, None - nothing
NewSkuCreated Identity no How many sku's was created in snapshot
ErrorsQuantity Identity no How many message values failed
DetailId Identity yes Filter for limit SKU inside snapshot
InsertUserId Identity yes Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastStatisticData Forecasting
Forecasting
The table stores the list of statistical parameters returned by Forecast Engine
name type identity null description
OperatorUserId Identity no Who inserted the record?
Id Identity no Identity
HistoricDataMean Float no
StandardDeviation Float no
StandardForecastError Float no
AdjustedRSquare Float no
BayesianInformationCriterion Float no
MeanAbsolutePercentError Float no
FinalTrend Float no
MAPE Float no
ZMAPE Float no
SMAPE Float no
MPE Float no
MAD Float no
RMSE Float no
Variance Float no
TotalFinalForecast Float no
Orders Float no
FinalForecast Float no
CustomerForecast Float no
OrdersVsFinalForecast Float no
MTDFF Float no
MTDCF Float no
ForecastMethod String yes
ForecastMethodTooltip HugeString yes
GroupForecastMethod String yes
GroupForecastMethodTooltip HugeString yes
Seasonality String yes Exponential smoothing No seasonality = 0 Additive seasonality=1 Multiplicative seasonality = 2
SeasonalityToolTip HugeString yes
Trend String yes Exponential smoothing No trend = 0 Linear trend = 1 Decaying trend = 2 Exponential = 3
TrendToolTip HugeString yes
WarningCssClass LongString yes
GroupSeasonality String yes Exponential smoothing No seasonality = 0 Additive seasonality=1 Multiplicative seasonality = 2
GroupSeasonalityToolTip HugeString yes
UsedExternalTrends HugeString yes
GroupTrend String yes Exponential smoothing No trend = 0 Linear trend = 1 Decaying trend = 2 Exponential = 3
GroupTrendToolTip HugeString yes
top
ForecastStatistics Forecasting
Forecasting
The table stores the list of statistical parameters returned by Forecast Engine
name type identity null description
Id Identity yes no Identity
ForecastId Identity no Forecast ID (A reference to Forecasts)
SiteMaterialUsageId Identity no SKU ID (A reference to SiteMaterialUsages)
ForecastMethodId Identity no
GroupedForecastMethodId Identity yes
Seasonality Identity yes Exponential smoothing No seasonality = 0 Additive seasonality=1 Multiplicative seasonality = 2
Trend Identity yes Exponential smoothing No trend = 0 Linear trend = 1 Decaying trend = 2 Exponential = 3
GroupedSeasonality Identity yes Exponential smoothing No seasonality = 0 Additive seasonality=1 Multiplicative seasonality = 2
GroupedTrend Identity yes Exponential smoothing No trend = 0 Linear trend = 1 Decaying trend = 2 Exponential = 3
UseTradingDays Integer no Use trading days mode?
UsedExternalTrends LongString yes Comma separated list of used external trends
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
ForecastStatuses Forecasting
Forecasting
The table stores forecast status definitions
name type identity null description
Id Identity no Identity
ForecastStatusName ShortString no Forecast status name
ForecastStatusDesc ShortString no Forecast status description
Abbreviation ShortString no Forecast status abbreviation
StatusLevel Integer no Forecast status level
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ForecastViewData Forecasting
Forecasting
A temporary table for forecast collaboration
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
GroupId Identity no Grouped Identity
DateFrom Date yes date
System Float no
Customer Float no
Final Float no
CustomerVsSystem Float no
SystemVsFinal Float no
CustomerVsFinal Float no
ForecastStatusId Integer no
Orders Float no
Budget Float no
Filtered Identity no
top
ForecastWeeklyCoefs Forecasting
Forecasting
The table stores grouped monthly forecasts
name type identity null description
Id Identity no Identity
DateFrom Date no Month
DateFromIW Date no Week
Coef DoubleDouble yes Weekly Coef
CalendarId Identity yes Initial Calendar Id
IsWorking Integer no A switch. Possible values: 0 - forecast state unchanged, or the forecast released; 1 - the forecast has been carried from the previous forecast, 2 - the forecast has been modified (edited) )
WorkingDays Integer no working days?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
FrozenEditingRules Forecasting
Forecasting
The table stores rules for freeze forecast editing
name type identity null description
CharacteristicsKey LongString no csv list of fields
CharacteristicsValue LongString no csv list of values
FrozenPeriod Integer no Forecast frozen period
InsertUserId Identity yes Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
GradeMaterials Block Scheduling
Block Scheduling
The table describes many-to-many relation between grades and materials.
name type identity null description
GradeId Identity yes A reference to GradeProperties.GradeId
OperationTypeId Identity yes yes Operation Type Identity
GradeCode String yes Grade code: concatenation of property codes of ProductionRatePicker
MaterialId Identity no A reference to Materials.Id
top
GradeProductionRates Block Scheduling
Temporary
ProductionRates for grades on PM workcentres.
name type identity null description
WorkcentreId Identity no Workcentre Id
GradeId Identity no Reference to table GradeProperties
OperationTypeId Identity no Operation type
Rate Float no Production Rate Id
top
GradeProperties Block Scheduling
Block Scheduling
The table stores properties of material grades. A grade is a set of properties. The set of properties is different for PMs and FLs and is defined by pickers (ProcutionRatePicker).
name type identity null description
GradeId Identity yes no Identity
GradeCode String no Grade code
OperationTypeId Identity yes yes Operation Type Identity
Code1 ShortString yes References to PropertyCodes
Code2 ShortString yes References to PropertyCodes
Code3 ShortString yes References to PropertyCodes
Code4 ShortString yes References to PropertyCodes
Code5 ShortString yes References to PropertyCodes
Code6 ShortString yes References to PropertyCodes
Code7 ShortString yes References to PropertyCodes
Code8 ShortString yes References to PropertyCodes
Code9 ShortString yes References to PropertyCodes
Code10 ShortString yes References to PropertyCodes
Code11 ShortString yes References to PropertyCodes
Code12 ShortString yes References to PropertyCodes
Code13 ShortString yes References to PropertyCodes
Code14 ShortString yes References to PropertyCodes
Code15 ShortString yes References to PropertyValues
Code16 ShortString yes References to PropertyCodes
Code17 ShortString yes References to PropertyCodes
Code18 ShortString yes References to PropertyCodes
Code19 ShortString yes References to PropertyCodes
Code20 ShortString yes References to PropertyCodes
Code21 ShortString yes References to PropertyCodes
Code22 ShortString yes References to PropertyCodes
Code23 ShortString yes References to PropertyCodes
Code24 ShortString yes References to PropertyCodes
Code25 ShortString yes References to PropertyCodes
Code26 ShortString yes References to PropertyCodes
Code27 ShortString yes References to PropertyCodes
Code28 ShortString yes References to PropertyCodes
Code29 ShortString yes References to PropertyCodes
Code30 ShortString yes References to PropertyCodes
top
GridColumns Core
Configuration
The table contains the list columns of grids
name type identity null description
Id Identity yes no Identity
GridId Identity no Grid Id
ActionId Identity yes Page action used for permissions
orderNo Identity no Grid Id
Caption ShortString yes Column name
FieldName ShortString no Field name
Type ShortString no Type: (Decimal, Integer, String, Date, DateTime, bool)
ControlType ShortString no Control Type (CheckBox, ComboBox, TextBox, DatePicker, MonthPicker, WeekPicker)
IsEditable Integer no Is editable (yes/no)
IsShowTotal Integer no Is show total (yes/no)
IsFinancial Integer no Is financial column
TotalFunction String yes Is show total (yes/no)
State ShortString no State = (normal, fixed, hidden)
DataForColumn String yes this column will place into column cell data object
colorColumn String yes
BackgroundColorColumn String yes
dataColumns LongestString yes
dataColumnsMapping LongestString yes
editableColumn String yes
tooltipColumn String yes
showToolTipColumn String yes
classColumn String yes
Color ShortString yes red, white (#566777)
BackgroundColor ShortString yes red, white (#566777)
IsResizable Integer no (yes/no)
IsTransformColumn Integer no (yes/no)
IsTransformable Integer no (yes/no)
TransformFormat String yes format for transformation
IsShowToolTip Integer no (yes/no)
IsConfigurable Integer no (yes/no)
IsGridFilter Integer no (yes/no)
SubRow String yes Subrow column
MaxWidth Integer no Max width for multi-line column
MinWidth Integer no Min width for multi-line column
Style String yes (string)
Format String yes (string)
Sort Integer no (yes/no)
Filter ShortString yes (text/select)
DependOnColumn ShortString yes visible depend on other column settings
SystemParameter String yes Visibility depend on parameter
SystemParameterValue String yes Visibility depend on parameter
OrderColumn ShortString yes order column for transformed grids
top
Grids Core
Configuration
The table contains the list of grids
name type identity null description
Id Identity yes no Identity
Name ShortString no Grid name
Description String no Grid description
IsColumnsAsRows Integer no Is show columns As rows
IsExtendCaptions Integer no Is extend captions before adding totals
PageId Identity yes Page
top
GroupedSKU Replenishment
Replenishment
The table contains information about inventories on every single day, by SKUs
name type identity null description
SiteMaterialUsageId Identity no SKU Id
GroupType String no Site, Company or Locatio
GroupId Identity no Location,Company,Site Id
LocationId Identity yes Location Id
MaterialId Identity no Material Id
ConsignmentLocationId Identity yes Location Id
GroupKey String no Group key included Site, Company or Location and identity key
Opening Float no Last known opening
HighQuantity Float no
LowQuantity Float no
DaysOfSupply Float no
MaxDaysOfSupply Float no
TransportTime Float no
ReplenishmentFrequency Float no
MaxReplenishmentFrequency Float no
HistoryStartDate Date yes
SafetyStockMethodId Identity no
MaxSafetyStockMethodId Identity yes
ReplenishmentHorizon Integer no
ForecastMethodId Identity no
top
GroupForecastViewData Forecasting
Forecasting
A temporary table for forecast view
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
Id Identity no Grouped Identity
SummaryFields HugeString yes SummaryFields
ForecastStatusId Integer no
WarningCssClass String yes
HistoricDataMean Float no
StandardDeviation Float no
StandardForecastError Float no
AdjustedRSquare Float no
BayesianInformationCriterion Float no
MeanAbsolutePercentError Float no
FinalTrend Float no
MAPE Float no
ZMAPE Float no
SMAPE Float no
MPE Float no
MAD Float no
RMSE Float no
Variance Float no
TotalFinalForecast Float no
FinalForecast Float no
CustomerForecast Float no
OrdersVsFinalForecast Float no
MTDFF Float no
MTDCF Float no
ForecastMethod String yes
ForecastMethodTooltip HugeString yes
GroupForecastMethod String yes
GroupForecastMethodTooltip HugeString yes
Seasonality String yes Exponential smoothing No seasonality = 0 Additive seasonality=1 Multiplicative seasonality = 2
SeasonalityToolTip HugeString yes
Trend String yes Exponential smoothing No trend = 0 Linear trend = 1 Decaying trend = 2 Exponential = 3
TrendToolTip HugeString yes
GroupSeasonality String yes Exponential smoothing No seasonality = 0 Additive seasonality=1 Multiplicative seasonality = 2
GroupSeasonalityToolTip HugeString yes
GroupTrend String yes Exponential smoothing No trend = 0 Linear trend = 1 Decaying trend = 2 Exponential = 3
GroupTrendToolTip HugeString yes
History1 Float no History1
History2 Float no History2
History3 Float no History3
History4 Float no History4
History5 Float no History5
History6 Float no History6
History7 Float no History7
MTD Float no
top
GroupRealInventoryProfiles Due date quoting
Due date quoting
The table contains information about the inventory on every day by SKUs. For each SKU and each day we have opening quantity in the beginning of the day. It is calculated as the difference of incoming and outgoing order quantities of the previous day. Closing quantity is calculated as the difference of incoming and outgoing order quantities of the current day. MinOpening value determines the minimal opening quantity at the real inventory horizon. Data in this table is updated when processing order operations. When recalculating of the real inventory for specific SKUs, appropriate rows can be deleted and inserted.
name type identity null description
SiteMaterialUsageId Identity yes A reference to SiteMaterialUsages
ConsignmentLocationId Identity yes A reference to Locations
SKUKey String no A reference to Workcentres
DateFrom Date no Date
OverallOpening Float no Opening quantity for Firm, Tentative and Consumption
Opening Float no Opening quantity
OpeningNonForecasted Float no Non forecasted opening quantity for Consignment Stock
OrdersIn Float no Incoming orders quantity
TentativeOrdersIn Float yes Incoming tentative orders quantity
OrdersOut Float no Outgoing orders quantity
TentativeOrdersOut Float yes Outgoing tentative orders quantity
ClosingNonForecasted Float no Non forecasted closing quantity for Consignment Stock
Closing Float no Closing quantity
OverallClosing Float no Closing quantity for Firm, Tentative and Consumption
FirmClosing Float yes Closing quantity only for Firm orders
MinOpening Float no Minimal opening quantity
SafetyStock Float no Safety stock
MaxSafetyStock Float yes Safety stock
Consumption Float no Forecst consumption
SupersededStockStatus Integer no Replenishment result
Delivered Float no Delivered movements
OnHandInventory Float no Delivered movements
OnHandMinOpening Float no Delivered movements
top
HiddenSharedReports Reports
Access rights
The table describes many-to-many relation between roles and system reports
name type identity null description
UserId Identity no System Role Id
DataSourceId Identity no data source id
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
Hierarchies Core
Core
The table stores the list of all hierarchies registered in I-Plan
name type identity null description
Id Identity yes no Identity
HierarchyName String no Hierarchy name
HierarchyCode ShortString no Hierarchy external code
ParentHierarchyId Identity yes Parent hierarchy identity
HierarchyLevelId Identity no Hierarchy level identity
Latitude ShortString yes Latitude
Longitude ShortString yes Longitude
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
HierarchyLevels Core
Core
The table stores the list of all levels of hierarchies registered in I-Plan
name type identity null description
Id Identity yes no Identity
HierarchyLevelName String no Hierarchy level name
HierarchyLevelNo Integer no Hierarchy level number
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
HierarchyPropertyDetails Core
Core
The table stores the list of properties and hierarchies in I-Plan
name type identity null description
Id Identity yes no Identity row
Priority Identity no Priority
HierarchyCode1 String yes Hierarchy Code1
HierarchyCode2 String yes Hierarchy Code2
HierarchyCode3 String yes Hierarchy Code3
HierarchyCode4 String yes Hierarchy Code4
HierarchyCode5 String yes Hierarchy Code5
HierarchyCode6 String yes Hierarchy Code6
HierarchyCode7 String yes Hierarchy Code7
HierarchyCode8 String yes Hierarchy Code8
HierarchyCode9 String yes Hierarchy Code9
HierarchyCode10 String yes Hierarchy Code10
HierarchyCode11 String yes Hierarchy Code11
HierarchyCode12 String yes Hierarchy Code12
HierarchyCode13 String yes Hierarchy Code13
HierarchyCode14 String yes Hierarchy Code14
HierarchyCode15 String yes Hierarchy Code15
Code1 String yes Property value Code1
Code2 String yes Property value Code2
Code3 String yes Property value Code3
Code4 String yes Property value Code4
Code5 String yes Property value Code5
Code6 String yes Property value Code6
Code7 String yes Property value Code7
Code8 String yes Property value Code8
Code9 String yes Property value Code9
Code10 String yes Property value Code10
Code11 String yes Property value Code11
Code12 String yes Property value Code12
Code13 String yes Property value Code13
Code14 String yes Property value Code14
Code15 String yes Property value Code15
Code16 String yes Property value Code16
Code17 String yes Property value Code17
Code18 String yes Property value Code18
Code19 String yes Property value Code19
Code20 String yes Property value Code20
Code21 String yes Property value Code21
Code22 String yes Property value Code22
Code23 String yes Property value Code23
Code24 String yes Property value Code24
Code25 String yes Property value Code25
Code26 String yes Property value Code26
Code27 String yes Property value Code27
Code28 String yes Property value Code28
Code29 String yes Property value Code29
Code30 String yes Property value Code30
Property1 String yes EndUse property 1
Property2 String yes EndUse property 2
Property3 String yes EndUse property 3
Property4 String yes EndUse property 4
Property5 String yes EndUse property 5
Property6 String yes EndUse property 6
Property7 String yes EndUse property 7
Property8 String yes EndUse property 8
Property9 String yes EndUse property 9
Property10 String yes EndUse property 10
Property11 String yes EndUse property 11
Property12 String yes EndUse property 12
Property13 String yes EndUse property 13
Property14 String yes EndUse property 14
Property15 String yes EndUse property 15
EndcustomerHierarchyCode1 String yes EndcustomerHierarchy Code1
EndcustomerHierarchyCode2 String yes EndcustomerHierarchy Code2
EndcustomerHierarchyCode3 String yes EndcustomerHierarchy Code3
EndcustomerHierarchyCode4 String yes EndcustomerHierarchy Code4
EndcustomerHierarchyCode5 String yes EndcustomerHierarchy Code5
EndcustomerHierarchyCode6 String yes EndcustomerHierarchy Code6
EndcustomerHierarchyCode7 String yes EndcustomerHierarchy Code7
EndcustomerHierarchyCode8 String yes EndcustomerHierarchy Code8
EndcustomerHierarchyCode9 String yes EndcustomerHierarchy Code9
EndcustomerHierarchyCode10 String yes EndcustomerHierarchy Code10
EndcustomerHierarchyCode11 String yes EndcustomerHierarchy Code11
EndcustomerHierarchyCode12 String yes EndcustomerHierarchy Code12
EndcustomerHierarchyCode13 String yes EndcustomerHierarchy Code13
EndcustomerHierarchyCode14 String yes EndcustomerHierarchy Code14
EndcustomerHierarchyCode15 String yes Hierarchy Code15
LocationCode String yes Location Code
ProductCode String yes Material Code
EndUseCode String yes End Use Code
EndCustomerCode String yes End customer code - Location Code
PropertyBits String no Notnull indicator for property columns
HierarchyBits String no Notnull indicator for hierarchy columns
EndCustomerHierarchyBits String no Notnull indicator for hierarchy columns
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was inserted?
top
HistoryComparisonData Forecasting
Temporary
Temporary table for data for Forecast comparison screen
name type identity null description
DateFrom Date no Date (month)
Weight Float yes total usage
AdjustedWeight Float yes total usage
OriginalSystem Float yes original system forecast value
System Float yes system forecast value
Customer Float yes customer forecast value
Final Float yes final forecast value
AllHistory Float yes final forecast value
FittedHistory Float yes final forecast value
Budget Float yes final forecast value
OperatorUserId Identity no user id
top
HistoryData Forecasting
Forecasting
A temporary table for history calculation, populated during forecast generation.
name type identity null description
DateFrom Date no Month
StartDate Date no Forecast start date
SiteMaterialUsageId Identity yes SKU ID (A reference to SiteMaterialUsages)
Successed Identity yes A flag: include supercessions?
TradingDays Integer no Trading days quantity (from calendars by working days)
Weight Float no History weight
OperatorUserId Identity no The ID of the user who have inserted the line
top
HistoryForOppBlocksData Block Scheduling
Temporary
History for opportunistic blocks.
name type identity null description
DateFrom Date no Date of entry
WorkcentreId Identity no Workcentre Id
StartDate Date no Current date, truncated to month
GradeId Identity no GradeId (for PM) or FinishingId (for FL)
Quantity Float yes Quantity
Upper Float yes Upper percentile
Lower Float yes Lower percentile
OperatorUserId Identity no Who inserted the line?
top
HoldingCosts Core
Core
The table stores the list of costs of storing products at warehouses
name type identity null description
Id Identity yes no Identity
SiteId Identity yes A reference to the Sites table
Effective Date no The date when the cost becomes active
HoldingCost DoubleFloat no Storing cost
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
HoldingCostSnapshots Master Planning
Master Planning
The table stores the list of costs of storing products at warehouses
name type identity null description
ScenarioId Identity no ScenarioId
SnapshotUserId Identity no User ID (A reference to Users)
SiteId Identity yes A reference to the Sites table
Effective Date no The date when the cost becomes active
HoldingCost DoubleFloat no Storing cost
OriginalCost DoubleFloat yes Original cost
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Indicatives Master Planning
Master Planning
The table stores weekly Indicatives for SKUs per demand periods
name type identity null description
Id Identity yes no Identity
DeliveryWeek Date yes Delivery Week
DeliveryMonth Date yes Delivery Month
SiteMaterialUsageId Identity no A reference to the corresponding SKU
WorkcentreId Identity yes A reference to Workcentres
Value Float no Indicative value
ConversionFactor Float no Production rate conversion factor
FGPropertyValueId Identity yes Flag
MasterRouteId Identity yes Flag
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
InitialSourceRules Core
Core
The table stores source priority rules
name type identity null description
Id Identity yes no Identity
DetailId Identity no Weight of rule
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
InitialSourceRuleSources Core
Core
The table stores about sources for SKUs
name type identity null description
Id Identity yes no Identity
InitialSourceRuleId Identity yes no Identity
OperationTypeId Identity yes A reference to operation type
WorkCentreId Identity yes A reference to Workcentres
SiteId Identity yes A reference to Sites
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
InitialSources Core
Core
The table stores about sources for SKUs
name type identity null description
Id Identity yes no Identity
SiteMaterialUsageId Identity no A reference to SiteMaterialUsages
WorkCentreId Identity yes A reference to Workcentres
OperationTypeId Identity yes A reference to Operation types on workcentres
InitialSourceRuleId Identity yes A reference to initial source rule
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
InitialSourceSnapshots Master Planning
Master Planning
The table stores initial source rules
name type identity null description
SnapshotUserId Identity no User ID (A reference to Users)
ScenarioId Identity no Scenario ID (A refernce to Scenarios)
Id Identity yes no Identity
DetailId Identity no Weight of rule
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
InitialSourceSourceSnapshots Master Planning
Master Planning
The table stores about sources for SKUs
name type identity null description
SnapshotUserId Identity no User ID (A reference to Users)
ScenarioId Identity no Scenario ID (A reference to Scenarios)
Id Identity yes no Identity
InitialSourceSnapshotId Identity yes no Identity
WorkCentreId Identity yes A reference to Workcentres
SiteId Identity yes A reference to Sites
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
InnerPointForecast Replenishment
Temporary table
The table stores a forecast, generated by forecast engine from the customer history
name type identity null description
GroupKey String no Group key included Site, Company or Location and identity key
MaterialId Identity no A reference to Materials
DateFrom Date no Date (first day of month)
Quantity Float no Forecasted weight
SafetyStock Float no Safety stock weight
top
InnerPointHistory Replenishment
Temptorary table
The table stores history data (consumption) of the customer for each warehouse. This data is used for calculation of statistical safety stock in allocation-based replenishment process using the forecast engine
name type identity null description
Id Identity yes Group key Id
DateFrom Date no Date (First day of month)
GroupKey String no Group key included Site, Company or Location and identity key
MaterialId Identity no A reference to Materials
ForecastMethodId Identity no Type of forecast method
IsWeekly Integer no Type of forecast method
Quantity Float no Consumed weight
FittedHistory Float no Fitted History Weight
top
IntraSiteTimeData Master Planning
Temporary
Temporary table with site data about transport time between site locations.
name type identity null description
SiteId Identity no Site Id
FinishingSiteId Identity no Finishing Site Id
PMWorkcentreId Identity no PM Workcentre Id of Site
PMLocationId Identity no PM Location Id of Site
SFGWorkcentreId Identity yes SFG WH Workcentre Id of Site
SFGLocationId Identity yes SFG Location Id of Site
FinishingSFGWorkcentreId Identity yes SFG WH Workcentre Id of Site
FinishingSFGLocationId Identity yes SFG Location Id of Site
FLWorkcentreId Identity yes FL Workcentre Id of Site
FLLocationId Identity yes FL Location Id of Site
FGWorkcentreId Identity yes FG WH Workcentre Id of Site
FGLocationId Identity yes FG Location Id of Site
PMtoSFGTime Identity yes Onsite PM to SFG time
PMtoFLTime Identity yes Onsite PM to FL time
SFGtoSFGTime Identity yes Intersite SFG to SFG time
SFGtoSFGCost Float yes Intersite SFG to SFG cost
SFGtoFLTime Identity yes Onsite SFG to FL time
FLtoFGTime Identity yes Onsiet FL to FG time
HasOriginalDueDate Identity yes Equals 1 if PM workcentre parameter 'ROForPMOrderDateMethod' is set to 'OriginalDueDate'
FinishingLeadTime Identity yes PM workcentre Finishing Lead Time (days, default 1)
UserId Identity no User identificator
top
Inventories Replenishment
Replenishment
The table stores in-stock balances of warehouses (this data is received from external system)
name type identity null description
Id Identity yes no Identity
DateFrom Date no Date
SiteMaterialUsageId Identity no A reference to SiteMaterialUsages
ConsignmentLocationId Identity yes A reference to Locations
SkuKey String no A reference to Sku. For performance reason and simplify conditions
StockType String no Stock type: Standard, Customer, InTransit, Quarantine
Weight Float no Opening weight
AvailableOnHandWeight Float no Available on hand weight
CalculatedOnHandWeight Float no Calculated on hand weight
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
InventoryData Replenishment
Replenishment
The table is used for storing Inventory
name type identity null description
DateFrom Date no Date from
Opening Float no Forecasted opening stocks
Incoming Float no Forecasted incoming consignment Orders
Outgoing Float no Forecasted outgoing consignment Orders
Closing Float no Forecasted closing stocks
top
InventoryLogs Inventory Planning
Inventory Planning
The table stores inventory record changes
name type identity null description
Id Identity yes no Identity
InventoryId Identity no Inventory Identity
AdjustedWeight Float yes Adjusted weight
StockType String no Stock type: Standard, Customer, InTransit, Quarantine
IsNewRecord Integer no Is new record
Comments HugeString no Comments
TimeStamp TimeStamp no Time stamp
top
InventoryProfiles Replenishment
Replenishment
The table contains information about inventories on every single day, by SKUs
name type identity null description
DateFrom Date no Date
SiteMaterialUsageId Identity yes SKU Id
CompanyId Identity yes Company Id
SiteId Identity yes Site Id
LocationId Identity yes Location Id
MaterialId Identity no Material Id
ConsignmentLocationId Identity yes Consignment customer identity
Opening Float no Opening stock
Consumption Float no Consumption (can be based on orders or forecast or netted forecast with orders
ConsumptionOrders Float no Order Consumption - outgoing orders and deliveries
ConsumptionForecast Float no Forecast consumption
FirmOrdersIn Float no Incoming orders and deliveries
TentativeOrdersIn Float no Incoming Tentative orders
TentativeOrdersOut Float no Outgoing Tentative orders
PlannedInventory Float no Inventory with taking in account tentative adn firm orders
SafetyStock Float no Safety stock
MaxSafetyStock Float yes Safety stock
OriginalSafetyStock Float no Safety stock
MinOpening Float no Original Min opening based on final Safety stock
OriginalMinOpening Float no Original Min opening based on final Safety stock
MinPlannedInventory Float no Min planned Inventory
RequestedOrdersIn Float no Requested Incoming Tentative orders
RequestedOrdersOut Float no Requested Outgoing Tentative orders
RequestedOpening Float no Requested Incoming Tentative orders
OriginalFirmIn Float no Original firm orders
OriginalConsumptionForecast Float no Original Consumption Forecast
IgnoredDemandValue Float no IgnoredDemandValue
IsRunAvailable Integer no Is run available
AvailableRunCapacity Integer no available run capacity
IsReceivingDate Integer no Is Receiving Date
GroupKey String no Group key included Site, Company or Location and identity key
top
InventoryProfilesData Replenishment
Temporary
The table contains information about inventories on every single day, by SKUs
name type identity null description
DateFrom Date no Date
Opening Float no Quantity at the begining of the DateFrom day
ForecastDemand Float no Consumption (can be based on orders, forecast, or netted forecast with orders
FirmOrdersIn Float no Total income according to incoming orders and deliveries
FirmOrdersOut Float no Total income according to incoming orders and deliveries
TentativeOrdersIn Float no Total income according to incoming orders and deliveries
TentativeOrdersOut Float no Total income according to incoming orders and deliveries
Closing Float no Inventory, taking into account tentative and firm orders
ProjectInventory Float no Inventory, taking into account firm orders only
SafetyStock Float no Safety stock
MaxSafetyStock Float yes Safety stock
Capacity Float no Capacity of warehouse
SafetyStockPercentWarning Float no Safety stock percent warning
OriginalForecastDemand Float no Original ForecastDemand
OperatorUserId Identity no User id
top
InventorySnapshots Master Planning
Master Planning
The table contains user snapshots of excess FG and SFG inventories.
name type identity null description
SnapshotUserId Identity no User ID (A reference to Users)
ScenarioId Identity no Scenario ID
DateFrom Date no
WeekT Date no Timing is based on calculated lead time in weeks T (rounded so remainder of 3 days or less adds 0 weeks, 4 days and more add 1 week) using the master route from the initial source site of the consignment customer to the customer or its MP hierarchy level
IsFinishedGoods Integer no FG/SFG inventory indicator: 0 for SFG, 1 for FG inventories.
SiteMaterialUsageId Identity no Reference to SKU Id
MaterialId Identity no material id (reference to materials)
PropertyValueId Identity yes SNP property level
LocationId Identity no location id (reference to locations)
ConsignmentLocationId Identity yes Consignmentlocation id (reference to locations)
InitialInventory Float no MinOpening minus SafetyStock on the MP Horizon Start Date plus incoming tentative orders minus outgoing tentative orders after or on current date and before MP Horizon Start. For calculating this value, incoming and outgoing tentative orders are used, which have timestamp from current date (including it) to the beginning of MP horizon (not including the date).
AvailableInventory Float no For FG Inventory: MinOpening minus SafetyStock on the MP Horizon Start Date; for SFG Inventory: Opening minus SafetyStock on the MP Horizon Start Date. Orders are not used.
InventoryAfterOrders Float no For FG Inventory: Inventory values decreased by assigning orders after FG PreNetting Orders process; for SFG Inventory: Inventory values decreased by assigning orders after SFG PreNetting Orders process. For calculating this value, incoming and outgoing tentative orders are used, which have timestamp from current date (including it) to the beginning of MP horizon (not including the date). For SFG warehouse, also movable and non-movable firm orders are used, which come from PM and SFG. Also moveable FG and SFG orders are used, which are assigned by prenetting process.
AvailableInventorySS Float no Inventory Deficit
InventoryAfterOrdersSS Float no Inventory Deficit
InventoryDeficit Float no Inventory Deficit
Opening Float no Inventory Deficit
Demand Float no Warehause demands.
Allocation Float no Used Allocation.
GroupSiteId Identity yes Site Id (A reference to Sites)
GroupCompanyId Identity yes Company Id (A reference to Companies)
IsMainWarehouse Integer yes flag
SafetyStock Float no Safety stock
OriginalSafetyStock Float no Original Safety stock
UsedSafetyStock Float no Used Safety stock
StockDeficit Float no Surplus Increase
SatisfiedFromSafetyStock Float no Surplus Increase
Replenished Integer no Replenished status
IsProductionPeriod Integer no Is Production period, 0 - no, 1 - yes, 2 - first production period
top
IPlanHooks General
General
Table where stored messages for Opt-Studio
name type identity null description
Action String no Action
Procedure String no Procedure for call
Enabled Integer no Is action enabled
top
Jobs Core
Core
name type identity null description
Id Identity yes no Identity
JobType String no JobType
FileName LongString no FileName for processing
FailedReason HugeString yes FailedReason
IsFinished Integer no Who inserted the record?
SystemProcessId Identity no System process Id
Parameters Text yes Job parameters
Identifier String no Unique identifier
FinishDate Date yes When job finished
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
JobStates Core
Core
name type identity null description
JobId Identity no Identity
Name String no JobType
Description String no JobType
CurrentState Identity no Current stage
Total Identity no Total
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
JourneyRoutes Replenishment
Replenishment
The table is used for storing many-to-many link between Journeys and Routes
name type identity null description
JourneyId Identity no A reference to the Journeys table
OrderNo Integer no Order number
TransportRouteId Identity no A reference to the TransportRoutes table
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Journeys Replenishment
Replenishment
The table is used for storing several routes, with specific transport methods. Journey is from a Site to a Location (normally this will be customer location)
name type identity null description
Id Identity no Identity
JourneyCode String no A journey code
IsDefault Integer no A parameter which to specify which journey to use if there are several between the site and the customer
IsInternal Integer no A parameter which to specify which journey to use if there are several between the site and the customer
FromSiteId Identity yes A reference to the Sites table
FromLocationId Identity yes A reference to the Locations table
ToLocationId Identity yes A reference to the Locations table
QuantityLegs Identity no QuantityLegs
Cost DoubleFloat no Tranport route cost
TimePeriod Integer no Duration, days
FirstTransportMethodId Identity yes Transport method used by the leg from the order source to the first location in the chain
LastTransportMethodId Identity yes Transport method used by the leg from the last location in the chain to the order destination
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
LanguageCategories Core
Language
The table defines the list of language categories used for localization of interface elements
name type identity null description
Id Identity yes no Identity
LanguageCategoryName String no Language category name
LanguageCategoryDesc LongString no Language category description
LanguageCategoryMask LongString no Key mask
CategoryTypeId Identity no Category type
IsTableMapping Integer no A flag: is this element stored in a separate table?
TableName String yes Table name
TableField String yes Field name in the table
TableFieldKey String yes Key field name of the table
Condition LongString yes Additional condition (optional)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
LanguageCategoryTypes Core
Language
The table defines language category types
name type identity null description
Id Identity yes no Identity
CategoryTypeName String no Language category type name
CategoryTypeDesc LongString no Language category type description
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Languages Core
Language
The table stores the list of languages used in I-Plan
name type identity null description
Id Identity yes no Identity
LanguageName String no Language name
LanguageDesc String no Language description
internal Integer no An internal column
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
LatestGeneratedInventories Replenishment
Order generation
The table is used for storing of opening stock generated when generating orders. This data is then displayed on the Inventory profile screen.
name type identity null description
SiteMaterialUsageId Identity yes A reference to the SiteMaterialUsages table
MaterialId Identity no A reference to the Materials table
LocationId Identity yes A reference to the Locations table
ConsignmentLocationId Identity yes A reference to the Locations table
SiteId Identity yes A reference to the Sites table
CompanyId Identity yes A reference to the Companies table
DateFrom Date no Date
Opening Float no Opening inventory
InventoryZero Integer no Have inventory less than zero
InventoryZeroStartDate Date no Start date when first occured zero stock
top
ListOrdersData Replenishment
Temporary
List of orders for inventory profiles. Used in replanished for show List Orders screen.
name type identity null description
MaterialId Identity yes Reference to Materials table
LocationId Identity yes Reference to Locations table
OrderLineId Identity yes Reference to OrderLines table
DeliveryId Identity yes Reference to OrderLines table
Quantity Float yes for incoming order - SupplierAdjusted, for outgoing order - SourceWeight
FinalWeight Float yes
OrderType String yes
MovementType String no Firm, Replenishment, Delivery
Direction String yes incoming, outgoing
MovementDate Date yes Movement date
DeliveryDate Date yes Delivery date
RequestedDate Date yes Delivery date
RequestedDespatchDate Date yes Requested despatch date
Phase String yes Replenishment phase
MaterialRunId Identity yes Reference to MaterialRuns table
OperatorUserId Identity no Who insert line?
WorkCentreName String yes Work centre name
SourceWorkCentreName String yes Source work centre name
Transport String yes Transport
OrderCode String yes The OrderBook code
LineNoCode String yes Externl reference to Order line number
DeliveryCode String yes Delivery Code
AlternateCode1 String yes Alternate Code 1
AlternateCode2 String yes Alternate Code 2
Status String yes Status
DispatchDate Date yes Dispatch date
CustomerRank String yes Customer rank
Source LongString yes Source
SourceMaterial String yes Source material
AllowSubstitution Integer no Allow substitution flag
DestinationMaterial String yes Destination material
ReplenishmentPoint String yes Final replenishment point
IsEditable Integer no Is row editable
top
LiveAllocationData Master Planning
Master Planning
A temporary table for live allocation
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
Id Identity no Grouped Identity
SummaryFields HugeString yes SummaryFields
DateFrom Date yes date
Forecast Float no
Orders Float no
UnallocatedOrders Float no
OriginalAllocation Float no
CurrentAllocation Float no
RemainingAllocation Float no
Unallocated Float no
IsWorking Integer no
AllocationComment LongestString yes
AllocationChangeId Identity yes
ReasonId Identity yes
ForecastTotal Float no
Indicatives Float no
IndicativesTotal Float no
MTDHistory Float no
OriginalAllocationTotal Float no
CurrentAllocationTotal Float no
OrdersTotal Float no
UnallocatedOrdersTotal Float no
RemainingAllocationTotal Float no
UnallocatedTotal Float no
MTDHistoryTotal Float no
Filtered Identity no
EditableIndicatives Integer no
top
LiveAllocationStatData Master Planning
Master Planning
A temporary table for live allocation
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
Id Identity no Grouped Identity
SummaryFields HugeString yes SummaryFields
Allocation Float no
Indicatives Float no
TotalAllocation Float no
TotalIndicatives Float no
HistoryMTD Float no
AllocationMTD Float no
AllocationOrders Float no
IndicativesMTD Float no
IndicativesOrders Float no
top
Locations Core
Core
The table stores the list of locations registered in the system
name type identity null description
Id Identity yes no Identity
LocationName LongString no Location name
LocationCode ShortString no Location external code
CompanyId Identity no Company ID
HierarchyId Identity yes Hierarchy ID
CustomerRankId Identity yes Customer rank
SafetyStockMethodId Identity yes Default safety stock method
CalendarId Identity yes Used calendar
TransportLocationId Identity yes Reference to the transport location
StockLocationId Identity yes Reference to the stock location
WarehouseLocationId Identity yes Reference to the warehouse group location
SiteId Identity yes Site
OrderAutoConfirmPeriod Integer yes Period of automatic confirmation of tentative orders
LocationProperties HugeString yes Hierarchies properties for location
CurrencyId Identity yes Currency
ForecastRangeId Identity yes forecast range for daily distribution
DefaultCustomerForecast ShortString no values - System, Budget, Zero, Budget then Zero
Capacity Float no Location capacity used for DC
AllocatedStock Float no Location capacity used for DC
UseTradingDays Integer yes Ue trading days for forecast generation
LocationStatus ShortString no Status
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
LoginInformation Core
Configuration
The table stores the information of active logins
name type identity null description
DateFrom Date no Date from
MaxLogins Identity no Count max logins
FailedLogins Identity no Count failed logins
TopPageName String yes NULL if its general failed logins
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MachineInformation Master Planning
Master Planning
The table contains detailed information about paper machines and finishing areas for each user, to pass to the SNO engine
name type identity null description
ScenarioId Identity no Scenario ID (A refernce to Scenarios)
SnapshotUserId Identity no User ID (A reference to Users)
SiteId Identity no Site ID (A reference to Sites)
WorkcentreId Identity yes Workcentre ID (A reference to Workcentres)
TimePeriod Integer no Ordinal number of the time period
DateFrom Date no Week
NominalCapacity Float no Nominal Capacity
Capacity Float no Capacity from minus shut time
Allocation Float no Allocation weight
Orders Float no Orders weight
CapacityHours Float no Available capacity in hours
NominalCapacityHours Float no Nominal Capacity in hours
ShutHours Float no Duration of shuts (in hours)
OrdersHours Float no Time in hours spent to produce nonmovable orders within the time period
AllocationHours Float no Time in hours for PM Allocation
FixedCapacityHours Float no Fixed capacity time in hours
TimeEfficiency Float no Time efficiency coefficient
MachineType String no Infortmation Type: PM, SFG (FA), WH
SNOCapacity Float no Capacity which has been passed to SNO engine - valid only for FA, i.e. its FA Capacity after prenetting
top
MandatorySettings Master Planning
Allocations
name type identity null description
Id Identity yes no Id
Value1 LongString yes Property/Hierarchy value
Value2 LongString yes Property/Hierarchy value
Value3 LongString yes Property/Hierarchy value
Value4 LongString yes Property/Hierarchy value
Value5 LongString yes Property/Hierarchy value
Value6 LongString yes Property/Hierarchy value
Value7 LongString yes Property/Hierarchy value
Value8 LongString yes Property/Hierarchy value
Value9 LongString yes Property/Hierarchy value
Value10 LongString yes Property/Hierarchy value
Value11 LongString yes Property/Hierarchy value
Value12 LongString yes Property/Hierarchy value
Value13 LongString yes Property/Hierarchy value
Value14 LongString yes Property/Hierarchy value
Value15 LongString yes Property/Hierarchy value
Value16 LongString yes Property/Hierarchy value
Value17 LongString yes Property/Hierarchy value
Value18 LongString yes Property/Hierarchy value
Value19 LongString yes Property/Hierarchy value
Value20 LongString yes Property/Hierarchy value
Value21 LongString yes Property/Hierarchy value
Value22 LongString yes Property/Hierarchy value
Value23 LongString yes Property/Hierarchy value
Value24 LongString yes Property/Hierarchy value
Value25 LongString yes Property/Hierarchy value
Value26 LongString yes Property/Hierarchy value
Value27 LongString yes Property/Hierarchy value
Value28 LongString yes Property/Hierarchy value
Value29 LongString yes Property/Hierarchy value
Value30 LongString yes Property/Hierarchy value
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MandatorySettingSnapshots Master Planning
Allocations
name type identity null description
Id Identity no Id
ScenarioId Identity no Id
SnapshotUserId Identity no Who inserted the record?
Value1 LongString yes Property/Hierarchy value
Value2 LongString yes Property/Hierarchy value
Value3 LongString yes Property/Hierarchy value
Value4 LongString yes Property/Hierarchy value
Value5 LongString yes Property/Hierarchy value
Value6 LongString yes Property/Hierarchy value
Value7 LongString yes Property/Hierarchy value
Value8 LongString yes Property/Hierarchy value
Value9 LongString yes Property/Hierarchy value
Value10 LongString yes Property/Hierarchy value
Value11 LongString yes Property/Hierarchy value
Value12 LongString yes Property/Hierarchy value
Value13 LongString yes Property/Hierarchy value
Value14 LongString yes Property/Hierarchy value
Value15 LongString yes Property/Hierarchy value
Value16 LongString yes Property/Hierarchy value
Value17 LongString yes Property/Hierarchy value
Value18 LongString yes Property/Hierarchy value
Value19 LongString yes Property/Hierarchy value
Value20 LongString yes Property/Hierarchy value
Value21 LongString yes Property/Hierarchy value
Value22 LongString yes Property/Hierarchy value
Value23 LongString yes Property/Hierarchy value
Value24 LongString yes Property/Hierarchy value
Value25 LongString yes Property/Hierarchy value
Value26 LongString yes Property/Hierarchy value
Value27 LongString yes Property/Hierarchy value
Value28 LongString yes Property/Hierarchy value
Value29 LongString yes Property/Hierarchy value
Value30 LongString yes Property/Hierarchy value
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MandatorySnpItemSnapshots Master Planning
Master Planning
The table stores Mandatory Sno Items
name type identity null description
SnapshotUserId Identity no User ID (A reference to Users)
ScenarioId Identity no Scenario ID (A reference to Scenarios)
SnpItemId Identity yes Snp Item ID
IsMandatory Integer no IsMandatory
top
MarketInfo Forecasting
Forecasting
The table stores the Market info
name type identity null description
Id Identity yes no Identity
DateFrom Date no Month
Value Float no tonnes
Market String no Market
ProductManager String yes Product Manager
Region String yes Region
Country String yes Country
BusinessArea String yes Business Area
Segment1 String yes Segment1
Segment2 String yes Segment2
Segment3 String yes Segment3
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MasterRoutes Replenishment
Replenishment
The table contains the list of transport routes (with their parameters - cost, delivery time, location, shedule) between a site and a hierarchy node (for both types of hierarchy). It is used by master planning subsystem of I-Plan.
name type identity null description
Id Identity yes no Identity
Cost DoubleFloat no Master route cost
TimePeriod Integer no Route time
FromSiteId Identity no Source site ID of the route
DetailId Identity yes A reference to the Hierarchies table
MinCapacity Float no Min. Capacity. 0 mean no limitation
MaxCapacity Float no Max. Capacity. 0 mean no limitation
IsActive Integer no Is route active?
RouteCategory String yes Route category
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MasterRouteSnapshots Master Planning
Master Planning
The table contains user snapshots of master routes
name type identity null description
SnapshotUserId Identity no Snapshot user ID (A reference to Users)
ScenarioId Identity no Snapshot user ID (A reference to Users)
Id Identity yes no Identity
Cost DoubleFloat no Cost
TimePeriod Integer no timeperiod in days
FromSiteId Identity no Fom site ID (reference to site id)
DetailId Identity no Detail Id
IsActive Integer no Detail Id
MinCapacity Float no Min. Capacity. 0 mean no limitation
MaxCapacity Float no Max. Capacity. 0 mean no limitation
RouteCategory String yes Route category
InsertUserId Identity no Who insert line?
InsertDate Date no When line is inserted?
UpdateUserId Identity yes Who update line?
UpdateDate Date yes When line is updated?
top
MaterialBlocks Block Scheduling
Block Scheduling
Runs are combines into blocks. All information about a block is applied to all runs in the block. However, start and end dates of a block are start and finish date of the first and the last run in the block, respectively. The table describes material blocks.
name type identity null description
Id Identity yes no Identity
BlockCode ShortString no Block code
WorkCentreId Identity no A reference to WorkCentre
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MaterialGroups Core
Core
Store materials which share same source priorities
name type identity null description
MaterialId Identity no Identity
Edge HugeString no Source Priorities list
GroupId Identity no Material Group Id
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
MaterialPropsSpec Core
Core
The table stores material properties (specifications) in unfolded form
name type identity null description
MaterialId Identity no Material identity
MaterialTypeId Identity no Material type
MaterialTypeName String no Material type name
MaterialName LongString no Product name
MaterialCode String no Product code
Value1 LongString yes References to PropertyValues
Value2 LongString yes References to PropertyValues
Value3 LongString yes References to PropertyValues
Value4 LongString yes References to PropertyValues
Value5 LongString yes References to PropertyValues
Value6 LongString yes References to PropertyValues
Value7 LongString yes References to PropertyValues
Value8 LongString yes References to PropertyValues
Value9 LongString yes References to PropertyValues
Value10 LongString yes References to PropertyValues
Value11 LongString yes References to PropertyValues
Value12 LongString yes References to PropertyValues
Value13 LongString yes References to PropertyValues
Value14 LongString yes References to PropertyValues
Value15 LongString yes References to PropertyValues
Value16 LongString yes References to PropertyValues
Value17 LongString yes References to PropertyValues
Value18 LongString yes References to PropertyValues
Value19 LongString yes References to PropertyValues
Value20 LongString yes References to PropertyValues
Value21 LongString yes References to PropertyValues
Value22 LongString yes References to PropertyValues
Value23 LongString yes References to PropertyValues
Value24 LongString yes References to PropertyValues
Value25 LongString yes References to PropertyValues
Value26 LongString yes References to PropertyValues
Value27 LongString yes References to PropertyValues
Value28 LongString yes References to PropertyValues
Value29 LongString yes References to PropertyValues
Value30 LongString yes References to PropertyValues
Code1 ShortString yes References to PropertyCodes
Code2 ShortString yes References to PropertyCodes
Code3 ShortString yes References to PropertyCodes
Code4 ShortString yes References to PropertyCodes
Code5 ShortString yes References to PropertyCodes
Code6 ShortString yes References to PropertyCodes
Code7 ShortString yes References to PropertyCodes
Code8 ShortString yes References to PropertyCodes
Code9 ShortString yes References to PropertyCodes
Code10 ShortString yes References to PropertyCodes
Code11 ShortString yes References to PropertyCodes
Code12 ShortString yes References to PropertyCodes
Code13 ShortString yes References to PropertyCodes
Code14 ShortString yes References to PropertyCodes
Code15 ShortString yes References to PropertyCodes
Code16 ShortString yes References to PropertyCodes
Code17 ShortString yes References to PropertyCodes
Code18 ShortString yes References to PropertyCodes
Code19 ShortString yes References to PropertyCodes
Code20 ShortString yes References to PropertyCodes
Code21 ShortString yes References to PropertyCodes
Code22 ShortString yes References to PropertyCodes
Code23 ShortString yes References to PropertyCodes
Code24 ShortString yes References to PropertyCodes
Code25 ShortString yes References to PropertyCodes
Code26 ShortString yes References to PropertyCodes
Code27 ShortString yes References to PropertyCodes
Code28 ShortString yes References to PropertyCodes
Code29 ShortString yes References to PropertyCodes
Code30 ShortString yes References to PropertyCodes
Characteristic1 ShortString yes References to Product Characteristics
Characteristic2 ShortString yes References to Product Characteristics
Characteristic3 ShortString yes References to Product Characteristics
Characteristic4 ShortString yes References to Product Characteristics
Characteristic5 ShortString yes References to Product Characteristics
Characteristic6 String yes
Characteristic7 String yes
Characteristic8 String yes
Characteristic9 String yes
Characteristic10 String yes
top
MaterialRunAttributes Block Scheduling
Block Scheduling
Except properties, FL runs also should contain attributes. Attributes are properties of PM run concerned with FL run. The table contains information about attributes of material runs.
name type identity null description
MaterialRunId Identity no A reference to MaterialRuns.Id
PropertyId Identity no A reference to Properties.Id
PropertyValueCode String no Property value code
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MaterialRunParametersData Block Scheduling
Temporary
Properties and attributes of the run being edited in the Campaign Editor.
name type identity null description
WorkcentreId Identity no Workcentre Id
MaterialRunId Identity yes Reference to MaterialRuns table
StartDate Date yes Run StartDate
FinishDate Date yes Run FinishDate
TargetStartDate Date yes Run TargetStartDate
InitialDuration Float yes Run InitialDuration
SwitchoverDuration Float yes Run SwitchoverDuration
ProductId Identity no Reference to MaterialRunProducts table
PropertyId Identity no Property Id
PropertyValueCode String no PropertyValueCode
PropertyQuantity Integer yes Quantity of properties of the run
isAttribute Integer no 0 for properties, 1 for attributes
RunCode LongString yes Run Code
Quantity Float yes Run Quantity
WasteTime Float yes Run Waste Time
ProcessRate Float yes Run Process Rate
SpecificWeight Float yes Run Specific Weight
Status ShortString yes Run Status
RunType String yes Run Type
IsPropsChanged Integer yes 1 when properties are changed in the first screen of the Campaign Editor, 0 otherwise
OperatorUserId Identity no Who inserted the line?
top
MaterialRunProducts Block Scheduling
Block Scheduling
A run can produce one or more products. Opportunistic runs and idle times don't produce any materials. The table contains information about products that are planned to produce on material runs.
name type identity null description
Id Identity yes no Unique Identifier
MaterialRunId Identity no A reference to MaterialRuns.Id
ProductName LongString yes Product name
DetailId Identity yes Number of product properties
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
MaterialRunProperties Block Scheduling
Block Scheduling
The table contains run properties. Each run (PM and FL) which contains products, should contain properties as well.
name type identity null description
RunProductId Identity no A reference to RunProducts.Id
PropertyId Identity no A reference to Properties.Id
PropertyValueCode ShortString no Property value code
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MaterialRunPropertiesData Block Scheduling
Temporary
List of properties of a run.
name type identity null description
MaterialRunPropertyId Identity no Reference to MaterialRunProperties table
MaterialRunId Identity no Reference to MaterialRuns table
PropertyId Identity no Property Id
PropertyName String no Property Name
PropertyDesc String no Property description
Value LongString no Value of the property
PropertyValueCode String no PropertyValueCode of the property
LevelNo Integer no HierarchyLevelNo of the property
OperatorUserId Identity no Who inserted the line?
top
MaterialRuns Block Scheduling
Block Scheduling
The table stores information about campaigns. A campaign consists of a few individual material runs. Currently there are 2 possible types of campaigns - template and conventional (not template). Also there are 3 types of Material runs: run, opportunistic run, and idle time.
name type identity null description
Id Identity yes no Unique identifier
RunCode LongString no Run code
BlockRunCode LongString yes Block + space + Run code
NominalCapacity Float no Run capacity
Quantity Float no Run capacity
WasteTime Float no Time waste
ProcessRate Float no Production rate of the run
StartDate Date no Run start date
FinishDate Date no Run end date
TargetStartDate Date yes Run target start date
InitialDuration Float no Initial duration and real run duration, including changeover
SwitchoverDuration Float no Changeover duration. This duration is a part or run duration
QuantityComplete Float no Cumulative run quantity produced on the productionUpdateTimestamp
ProductionUpdateTimestamp Date yes Date of production update (timestamp)
MaterialRunStatusId Identity no A reference to MaterialRunStatuses
FPReleaseDate Date yes Last date when the run was sent to Fine Planning system. For runs which are received from External System this date is equal to MINDATE
MaterialBlockId Identity no A reference to MaterialBlocks.Id
WorkcentreId Identity no A reference to Workcentres.Id
RunType String yes Run type: production, floating shut or opportunistic run
SpecificWeight Float no Specific weight (From production rates)
UpdateOrderDates Integer no Indicator that required recalculation for order line dates. Used during Fine Planning update
IsFixed Integer no Indicator that required recalculation for order line dates. Used during Fine Planning update
IsChanged Integer no Indicator that run was changed. Used for sending to external systems
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MaterialRunsForPlan Master Planning
Master Planning
The table contains copy of existing runs
name type identity null description
OperatorUserId Identity no
SnapshotState Integer no 0 - live state (copy) 1 - working state
MaterialRunId Identity yes
WorkCentreId Identity no
SourcePeriod Date no
StartDate Date no
FinishDate Date no
CycleTypeId Identity no
InitialDuration Float no
OrderDuration Float no
IsFixed Integer no
IsActive Integer no
OriginalOrderNo Integer no
AvailableDuration Float no
Rate Float no
NewMaterialRunId Identity yes
top
MaterialRunStatuses Block Scheduling
Block Scheduling
The table stores the list of possible material run statuses
name type identity null description
Id Identity yes no Identity
RunStatusCode ShortString no Run Status Code
RunStatusName String no Run Status Name
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Materials Core
Core
The table stores the list of all products registered in I-Plan
name type identity null description
Id Identity yes no Identity
MaterialName LongString no Product name
MaterialCode String no Product code
MaterialTypeId Identity no A reference to MaterialTypes table
PropertyValueId Identity yes A reference to a value in the properties tree
SourceMaterialId Identity yes A reference to Materials table
MaterialProperties LongestString no Product properties
SiteId Identity yes A reference to Sites table
ForecastStartDate Date yes Forecast start date
ForecastFinishDate Date yes Forecast end date
ReplenishmentStartDate Date yes Replenishment start date
ReplenishmentFinishDate Date yes Replenishment start date
IsActive Integer no Is active
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MaterialSupercessions Core
Core
The table stores the list of possible material supercessions
name type identity null description
Id Identity yes no Identity
Type String no Supercession type: Supercession, Substitution, Both
SiteMaterialUsageId Identity no Superceded SKU. A reference to SiteMaterialUsages
OnSiteMaterialUsageId Identity no Superceding SKU. A reference to SiteMaterialUsages
SupercessionRuleId Identity yes Supercession rule ID
StartDate Date no The date, after which the rule is effective
GeneratedFromId Identity yes id from which this rule has been generated
Percentage Float no Percentage
LevelNo Identity no depth in tree for autocreated supercessions
DisableSupersededItems Integer no Switch off supercessed sku for forecasting
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MaterialTypeProperties Core
Core
The table describes relations between material types and properties available for these types
name type identity null description
Id Identity yes no Identity
MaterialTypeId Identity no Material type ID. A reference to MaterialTypes
PropertyId Identity no An ID of a property available for the material type. A reference to Properties
DataMask String yes Data mask for property value formatting
HierarchyLevelNo Integer no Hierarchy level number
ProductionStageNo Integer no Production stage code: 1 - conventional property; 2 - dimensional property
DefaultValue String yes Default value for property
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MaterialTypes Core
Core
The table stores the list of available material types
name type identity null description
Id Identity yes no Identity
MaterialTypeName String no Material type name
MaterialCodePattern LongestString yes Pattern for material type code
MaterialNamePattern LongestString yes Pattern for material type name
IsFinishedGoods Integer no A flag: is this a finishing goods materials?
IsSingleStage Integer no A flag: is this a single stage material?
RoundingUnitId Identity yes A reference to Units
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MaterialUnits Core
Core
The table stores coefficients for units convertion
name type identity null description
Id Identity yes no Identity
MaterialId Identity no A reference to Materials
UnitId Identity no A reference to Units
Dividend DoubleFloat no Dividend
Divisor DoubleFloat no Divisor
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MessageCharacteristics Core
Configuration
The table stores allowed entity type for message
name type identity null description
Id Identity yes no Identity
MessageName LongestString no Message name
EntityType LongestString no Characteristic entity type
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MessageHierarchies Core
Core
The table stores initial source hierarchies
name type identity null description
Id Identity no Id
EntityName String no EntityName (SupercessionRule, InitialSourceRule)
HierarchyLevelId Identity yes A reference to HierarchyLevels table
HierarchyCode String no Hierarchy code
ToHierarchyCode String yes ToHierarchy code
top
MessageProperties Core
Core
The table stores intial source properties
name type identity null description
Id Identity no Id
EntityName String no EntityName (SupercessionRule, InitialSourceRule)
PropertyId Identity yes A reference to Properties table
PropertyValueCode String no Source priority value code
ToPropertyValueCode String yes Source priority value code
top
MessagesLog Core
Logging
The table is used to maintain external messages log
name type identity null description
Id Identity no Identity
Direction String no Direction: incoming or outgoing
TopElement String no Top element
Code String yes Message code
Message Text no Message text
Error Text yes Error description
ExactMessage Text yes Exact message where error is happens
TimeStamp Date no The moment when the record was inserted
StartTime Date no The moment when the record was inserted
FinishTime Date no The moment when the record was inserted
IsFailed Integer no The moment when the record was inserted
top
MinimumAllocations Master Planning
Allocations
name type identity null description
Id Identity no Property ID (A reference to Properties)
Value1 LongString yes Property/Hierarchy value
Value2 LongString yes Property/Hierarchy value
Value3 LongString yes Property/Hierarchy value
Value4 LongString yes Property/Hierarchy value
Value5 LongString yes Property/Hierarchy value
Value6 LongString yes Property/Hierarchy value
Value7 LongString yes Property/Hierarchy value
Value8 LongString yes Property/Hierarchy value
Value9 LongString yes Property/Hierarchy value
Value10 LongString yes Property/Hierarchy value
Value11 LongString yes Property/Hierarchy value
Value12 LongString yes Property/Hierarchy value
Value13 LongString yes Property/Hierarchy value
Value14 LongString yes Property/Hierarchy value
Value15 LongString yes Property/Hierarchy value
Value16 LongString yes Property/Hierarchy value
Value17 LongString yes Property/Hierarchy value
Value18 LongString yes Property/Hierarchy value
Value19 LongString yes Property/Hierarchy value
Value20 LongString yes Property/Hierarchy value
Value21 LongString yes Property/Hierarchy value
Value22 LongString yes Property/Hierarchy value
Value23 LongString yes Property/Hierarchy value
Value24 LongString yes Property/Hierarchy value
Value25 LongString yes Property/Hierarchy value
Value26 LongString yes Property/Hierarchy value
Value27 LongString yes Property/Hierarchy value
Value28 LongString yes Property/Hierarchy value
Value29 LongString yes Property/Hierarchy value
Value30 LongString yes Property/Hierarchy value
Allocation Float yes Allocation, null is mean that value not configured
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
MinimumAllocationsSnapshot Master Planning
Allocations
name type identity null description
Id Identity no Property ID (A reference to Properties)
Allocation Float no Allocation, null is mean that value not configured
SnapshotUserId Identity no Who inserted the record?
top
MonthlyExchangeRates Core
Core
The table stores the list of exchange rates registered in the system
name type identity null description
FromCurrencyId Identity no This is the currency to convert to from the system's base currency
ToCurrencyId Identity no This is the currency to convert to from the system's base currency
DateFrom Date no Date that the exchange rate becomes effective
FromMultiplier DoubleFloat no The value to multiply the base currency by to convert to the specified currency. Can be used in conjunction with divider to specify the rate as a fraction
FromDivider DoubleFloat no Used with the multiplier to calculate the rate to convert from the base currency to the specified currency. Not usually required (hence defaults to 1), but useful if the exchange rate is a very low value to avoid rounding errors, eg the old Turkish lira was over 1,000,000 to the GBP
ToMultiplier DoubleFloat no The value to multiply the base currency by to convert to the specified currency. Can be used in conjunction with divider to specify the rate as a fraction
ToDivider DoubleFloat no Used with the multiplier to calculate the rate to convert from the base currency to the specified currency. Not usually required (hence defaults to 1), but useful if the exchange rate is a very low value to avoid rounding errors, eg the old Turkish lira was over 1,000,000 to the GBP
top
MovingForecastGroupData Forecasting
Temporary
Temporary table for carrying forecast values from previous forecast generations to current. Used when selected method - by Property
name type identity null description
DateFrom Date no date (month)
GroupId Identity no Group Id
EditGroupId Identity yes Group Id
EditGroupFinalId Identity yes Group Id
SiteMaterialUsageId Identity no Site Material Usage Id
RealFinal Float yes Final previous forecast value
Final Float yes Final previous forecast value
RealFinalSum Float yes Final previous forecast value sum
FinalSum Float yes Final previous forecast value sum
CurrentSum Float yes Current forecast value sum
System Float yes system forecast value
Quantity Float yes quantity sku per edit group
WeeklyEdited Integer yes flag
ShouldBeMoved Integer yes Should be moved (mean real change)
OperatorUserId Identity no user id
top
MPBSAllocationData Block Scheduling
Temporary
A temporary table for order and allocation netting (ticket 51150)
name type identity null description
SnapshotUserId Identity no Operator User ID (A reference to Users)
DeliveryDate Date no
DateFrom Date no
HierarchyId Identity no
PropertyValueId Identity no
CustomerRankId Identity no
SourceListId Identity no
WorkcentreId Identity no
Allocation Float no
Orders Float no
Flag Identity no
top
MPBSComparisonData Block Scheduling
Temporary
A temporary table for BS / MP comparison screen (ticket 51150)
name type identity null description
OperatorUserId Identity no Operator User ID (A reference to Users)
DateFrom Date no
RunCapacity Float no
TotalAllocation Float no
Difference Float no
CumulativeTotalAllocation Float no
CumulativeRunCapacity Float no
CumulativeDifference Float no
AllocationToOrders Float no
AllocationToForecast Float no
FirmOrders Float no
TentativeOrders Float no
FreeCapacity Float no
GroupId Identity no
top
Navigations Core
Configuration
The table stores tree navigation levels, main page for each level, and pickers for hierarchies and properties.
name type identity null description
Id Identity yes no Identity
TaskName String no Task Name (Page name)
InputType ShortString no Input type column picker
LevelName String no Level Name
DisplayLabel String yes Display Label
LevelNo Identity no Level number(Ordinal numner)
Mandatory Integer yes Is the field in the dynamic filter mandatory one? i.e. value always should be selected
DefaultValue String yes Default value for returned for dynamic filter field
DefaultOperation String yes Default value for returned for dynamic filter field
OrderByField String yes Order by field for ViewBased dynamic filters
FreeEntry Integer yes Mean can user input own value into picker
Hidden Integer no Permanent hidden level for summaries
operationTypeId Identity yes OperationTypeId for specific navigations
MaterialTypeId Identity yes MaterialTypeId for specific navigations
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
NavigationTasks Core
Configuration
The table stores all used nivagation tasks in the system.
name type identity null description
Id Identity yes no Identity
TaskName String no Task Name (Page name) or Picker name
SourceType ShortString no Source for task - page or picker
Source ShortString yes Source view name
FullSource ShortString yes Full Source view name
FilterType String yes Filter Type Enumeration (filter, picker), Picker - mean only one value for each filter entry can be selected
Area String yes Pseudo Levels Flag
PageName String yes Pseudo Levels Flag
ValidateMessage LongString yes Message for confirmation (used only for MinimumAllocations)
IsUnrestricted Integer no if 1 then filter entries does not filtered by selected values, example: creating new product with properties
IsSystem Integer no Is system
SpecificType String no Specific type: usual, materialType, operationType. Define is it usual type or material type or operation type specific navigation
AllowedOperations LongString yes List of allowed operations
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
NeedRebuildProfiles Replenishment
Replenishment
name type identity null description
SiteMaterialUsageId Identity no
ConsignmentLocationId Identity yes
top
NominalCostRules Core
Core
The table stores the list of rules of Nominal Costs
name type identity null description
Id Identity yes no Identity
Effective Date no The date when the rule becomes active
Cost DoubleFloat no Cost
CurrencyId Identity yes A reference to Currencies
DetailId Identity yes A reference to HierarchyPropertyDetails
RuleWeighting Identity no Rule weighting
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Notifications Core
Reference
The table stores the list of notifications
name type identity null description
Id Identity yes no Identity
Title String no Notification title
Body HugeString no Notification body
Severity String no Notification severity
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
OldSNPUnallocatedItemDetails Master Planning
Master Planning
The table contains the list of SNO issues (problems) within the specified user snapshots
name type identity null description
SnapshotUserId Identity no User ID (reference to Users )
ScenarioId Identity yes Scenario ID (refernce to Scenarios)
SnpItemId Identity no Property value ID (reference to PropertyValues)
DateFrom Date yes delivery date (demand date)
WorkcentreId Identity no
SiteId Identity no
HasRoute Integer no
HasInitialSource Integer no
HasRate Integer no
HasAnyRate Integer no
HasRateAndCost Integer no
HasCost Integer no
HasPrice Integer no
IsMandatoryDemand Integer no
FirstDeliveryDate Date yes
IsProfitable Integer no
Price Float yes
Cost Float yes
TransportCost Float yes
FinishingCost Float yes
HoldingCost Float yes
TimePeriod Integer yes
HasCapacity Integer no
HasAvailableCapacity Integer no
Demand Float no
Allocation Float no
UnallocatedReasonId Identity no code of problem
Description LongestString no description of problem
RouteType String yes Master route type
Rate Float yes Production rate
top
OperationPredecessors Replenishment
Replenishment
The table stores information about operation predecessors
name type identity null description
Id Identity yes no Identity
OrderOperationId Identity no Order Operation ID of the operation
ParentOrderOperationId Identity no Operation number
top
OperationProperties Replenishment
Replenishment
The table stores information operation properties
name type identity null description
Id Identity yes no Identity
OrderOperationId Identity no Order operation ID
Type String no
Code String no
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
OperationTypeConversions Core
Core
The table stores source priority rules
name type identity null description
Id Identity yes no Identity
ProductionConfigurationId Identity no Weight of rule
OperationTypeId Identity no Weight of rule
InputUnitId Identity no Weight of rule
OutputUnitId Identity no Weight of rule
Multiplier Float no Site
IsLastCoProductStage Integer no Is Last Stage for coproducts
Divider Float no Who inserted the record?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
OperationTypes Core
Core
Store Product Routes
name type identity null description
Id Identity yes no Identity
OperationTypeName String no OperationType name
WorkCentreTypeId Identity no WorkCentre type Id
ApplyCyclePlan Integer no Define will be rates restricted by cycle plan frequency
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was inserted?
top
OppBlockData Due date quoting
Temporary table
The table is used for calculation of opportunistic runs duration
name type identity null description
RunId Identity no A reference to the material run
OppRunId Identity no A reference to the opportunistic run
EnabledOppDuration Float no Found opportunistic duration
top
OppBlockDurationData Block Scheduling
Temporary
Duration of opportunisitic bocks.
name type identity null description
GradeId Identity no GradeId (for PM) or FinishingId (for FL)
WorkcentreId Identity no Workcentre Id
System Float yes Quantity
Upper Float yes Upper percentile
OperatorUserId Identity no Who inserted the line?
top
OptimizedRunOrders Block Scheduling
Block Scheduling
The table describes many-to-many relation between OptimizedRuns and OrderLines.
name type identity null description
RunId Identity no A reference to OptimizedRuns.Id
OrderId Identity yes A reference to GradeOrders.Id
OrderLineId Identity yes A reference to GradeOrders.Id
DateFrom Date yes Required Date for order or allocation
Duration Float no Duration
Lateness Float no Lateness
LatenessType Float no Lateness type (-1 - early, 0 - on-time, 1 - late
SequenceNo Identity no Sequence No
top
OptimizedRunProperties Block Scheduling
Block Scheduling
The table contains properties of the optimized runs.
name type identity null description
OptimizedRunId Identity no A reference to OptimizedRuns.Id
PropertyId Identity no A reference to Properties.Id
PropertyValueCode String no Property value code
top
OptimizedRuns Block Scheduling
Block Scheduling
The table contains runs generated by Run Optimizer during the most recent calculation.
name type identity null description
Id Identity yes no Identity
CampaignType Identity no Campaign type: 0 - optimised campaign, 1 - release campaign
TemplateName String yes Program Template Name
BlockCode String yes Block Code
RunCode String yes Run Code
SequenceNo Identity no Program sequence
PositionNo Identity no Run sequence
GradeId Identity yes A reference to GradeProperties.GradeId
WorkcentreId Identity no A reference to Workcentres.Id
StartDate Date no Run start date
TargetStartDate Date yes Target start date
InitialDuration Float no Initial and real run duration. Includes changeover time
Duration Float no Run duration, including shuts
Mandatory Integer no Does it mandatory run? (Will be excluded during BSO release if have zero length)
SwitchoverDuration Float no Switchover duration
SwitchoverCost Float no Switchover cost
LatenessCost Float no Lateness cost
EarlinessCost Float no Earliness cost
OriginalAllocation Float no OriginalAllocation
Allocation Float no OriginalAllocation
OnTimeOrders Float no OriginalAllocation
EarlyOrders Float no OriginalAllocation
LateOrders Float no OriginalAllocation
Rate Float no OriginalAllocation
OppBlock Integer no A flag: is the run an opportunistic block?
FSBlock Integer no A flag: is the run an floating shut block?
IsFixed Integer no A flag: is the run an fixed?
IsShut Integer no A flag: is the run an shut?
MaterialRunId Identity yes An identity that points to the new run. This field is populated after RO results released
Properties String yes Run properties in one string
Inventory Float no Value Opening for run FinishDate from table RunInventoryProfiles
SafetyStock Float no Value SafetyStock for run FinishDate from table RunInventoryProfiles
IsReadOnly Integer no A flag: is the run an readonly?
IsLiveRun Integer no LiveRun: 1 - production run, 0 - optimized run
IsLiveBlock Integer no LiveBlock: 1 - production block, 0 - optimized template
IsFrozen Integer no A flag: is the run an FP Frozen?
IsModified Integer no A flag: is the run an modified?
top
OptStudioMessages Replenishment
Replenishment
Table where stored messages for Opt-Studio
name type identity null description
Mes_Id Identity yes no Message ID, can be set to be automatically incremented or can be set by interacting system
Mes_Origin Integer no System identifier that generates the message, provided by Greycon. Normally just ‘1’.
Mes_Status Integer no Message status, '1' on insert, (means not processed)
Mes_Type Integer no Message type identifier. Type = 41
Mes_Timout Integer yes Message timeout before Integration Manager discard processing. Leave null
Mes_IDate Date yes Message creation date.
Mes_Conts Text no Message contents, Key/Value comma separated pairs.
Mes_Error Identity yes IM error code if any.
Mes_Reply LongestString yes IM reply message if any error.
Mes_Priori Integer yes Messaage priotity in case needed
top
OrderBookDeliveries Replenishment
Replenishment
The table stores the list of delivery dates (i.e. when items will be delivered)
name type identity null description
Id Identity yes no Identity
OrderBookId Identity no A reference to the OrderBooks table
DeliveryCode String no Delivery code
SourceType String no SourceType; Indicate whether the dispatched quantity was from a production or stock source, values are Stock or Production
SourceWarehouseId Identity no SourceWarehouse; This is the site warehouse that the order is dispatched from
TargetWarehouseId Identity yes TargetWarehouse; This is the site warehouse that the order is delivered to
ShipDate Date no The date when the item was (or will be) shipped
ReceivedDate Date no The date when the item arrived to the destination
Weight Float no Delivery weight
DeliveryStatusId Identity no Delivery status identifier
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
OrderBookInventories Replenishment
Replenishment
The table stores in-stock balances of warehouses (this data is received from external system)
name type identity null description
Id Identity yes no Identity
DateFrom Date no Date
OrderLineId Identity no A reference to OrderLines
LocationId Identity no A reference to Current Warehouse
Weight Float no Opening weight
StockWeight Float no Weight reduced by Planned (Firm) deliveries from feature
DeliveryDate Date no Delivery Date calculated from current location and despatch date as today
IsLatest Integer no Is it last order line inventory for order line/location? (calculated field)
IsSameSource Integer no Is it same source (calculated field)?
IsDelivered Integer no Is it delivered (calculated field)?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
OrderBooks Replenishment
Replenishment
The table stores order books. An order book can include many orders
name type identity null description
Id Identity yes no Identity
OrderCode ShortString no Order header code
Checked Integer yes A flag; determines whether the order should be sent. it is used in GUI
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
OrderBookTypes Replenishment
Replenishment
The table stores order book types
name type identity null description
OrderBookTypeName String no OrderBook type name
ChangingDeliveryDates Integer no Is action is active for changing delivery/dispatch dates
top
OrderInformation Replenishment
Replenishment
The table stores information about Order Informations
name type identity null description
Id Identity yes no Identity
OrderLineId Identity no Order Line identity
Type String no
top
OrderInformationCategories Replenishment
Replenishment
The table stores in-stock balances of warehouses from suppliers
name type identity null description
CategoryInfo String no Category name
ItemType String no Item name
IsSelected Integer no Is selected for showing
IsEditable Integer no Is editable?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
OrderInformationItems Replenishment
Replenishment
The table stores information about Order Information Items
name type identity null description
Id Identity yes no Identity
OrderInformationId Identity no Order Information identity
Type String no
Value LongestString no
top
OrderLineProperties Replenishment
Replenishment
The table stores information order line properties
name type identity null description
Id Identity yes no Identity
OrderLineId Identity no Order line ID
Type String no
Code String no
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
OrderLines Replenishment
Replenishment
The table stores detailed data about the current order
name type identity null description
Id Identity yes no Identity
AlternateCode1 String yes Alternate code 1
AlternateCode2 String yes Alternate code 2
Phase String no Phase for tentative orders
LineNoCode String no External reference to the order line number
LocationId Identity no Customer location
SourceMaterialId Identity no Semifinishing product ID
SourceWeight Float no Weight of SFG product consumed to produce the FG product
MaterialId Identity no Product material ID
WorkCentreId Identity yes Source workcentre ID
OriginalWeight Float no Weight
WeightComplete Float no Complete weight (produced weight of SFG material)
WeightIssued Float no Issued weight (produced weight of FG material)
Quantity Float yes Quantity, in the product units
SupplierWeight Float no Weight, adujsted by supplier
FinalWeight Float no Weight, adujsted by supplier
AllocatedStock Float no Allocated stock from on-hand inventory
StockWorkCentreId Identity yes Stock workcentre Id for allocated stock
SourceCoef Float no Weight / Source Weight coeficient
OrderLineStatusId Identity no Order line status
InitialOrderLineStatusId Identity yes Initial Order line status
TransportMethodId Identity yes Transport method
DestinationLocationId Identity no Destination location
RequestedDate Date no Requested date, i.e. when the product should be delivered
ConfirmedDate Date yes Confirmed date, the order is confirmed for (ie the promised date)
DeliveryDate Date no Delivery date, i.e. when the product will actually be delivered
MakeByDate Date yes The date when the order is produced
DespatchDate Date yes Despatch date, i.e. when the order leaves source location
ConsumptionDate Date yes Consumption date, i.e. when the order should be delivered to the finishing line (it must occur before the run is started)
RequestedDespatchDate Date yes Requested despatch date , i.e. based on requested date
ExMillDate Date yes This is the date at which the order line should leave the site at latest to get to the destination in time for the requested date.
OrderBookId Identity no A reference to the OrderBooks table
FinishingLock Integer yes A flag: did the request have finishing lock on? For order lines created as a result of a DDQ request, this field should be populated with the value of FinishingLock flag of the request
ReasonId Identity yes Reason ID
CriticalDate Date yes Critical date
IsSent Integer no A flag: have the order been sent to the external system?
JourneyId Identity yes A reference to the Journey table
FinishingDate Date yes Date the order is finished on
MarkCompleted Integer yes If parameter equal 1 DeliveryDate or ConsumptionDate or DespatchDate modified equal current system date. Otherwise do not touch.
SiteMaterialUsageId Identity no SKU
EndUseId Identity yes EndUse
EndCustomerId Identity yes EndCustomer
SourceSiteMaterialUsageId Identity yes Source SKU
ToConsignmentLocationId Identity yes for consignment orders, this indicates the consignment location that the order will be stored for at the destination location
FromConsignmentLocationId Identity yes for call off orders, this indicates the consignment location that the stock is being sourced from
IsForecasted Integer yes Non Forecasted movement is order line with field IsForecasted = 0 and does not related to I-Plan Forecast subsystem
DeliveryWeight Float no Sum of weight for non-cancelled deliveries
DeliveredWeight Float no Sum of delivered deliveries
DispatchedWeight Float no Sum of dispatched deliveries
DeliverySourceWeight Float no Sum of source weight for non-cancelled deliveries
StockWeight Float no Sum of weight for last non-delivered OrderInventories and In-Transit deliveries
StockSourceWeight Float no Sum of source weight for last non-delivered OrderInventories and In-Transit deliveries
NeedRebuildProfile Integer yes If parameter equal 1 need rebuild Real Inventory Profile. Otherwise do not touch.
ReduceCSQuantity Float yes What quantity was used to reduce CS orders and/or inventory.
IsCSComplete Integer yes Whether the order is CS complete.
AllowSubstitution Integer no Flag indicate if an order can be substituted or not.
SkuKey String no Destination SKU Code - SKU-CS.
SourceSkuKey String yes FROM SKU Code - SourceSKU-CS.
StockSkuKey String yes FROM SKU Code - StockSourceSKU-CS. For Customer MTO orders with specified stockWarehouse
OrderType String no Order type: Customer or stock
ReplenishmentPointId Identity yes Replenishment point Id. For tentative orders generated by replenishment process.
ReplenishmentProcessId Identity yes Replenishment Process Id. For tentative orders generated by replenishment process.
PeriodType ShortString no Order period type: week or day
OrderGroupId Identity yes Combined order
SiteId Identity yes A reference to the Site table
Price Float yes Price
UnitId Identity yes Weight unit or any convertible to weight
Dividend DoubleFloat yes Dividend
Divisor DoubleFloat yes Divisor
CurrencyId Identity yes Currency Identity
SalesOrderLineId Identity yes A reference to the OrderLine table
AlternativeKey String yes Alternative Key
DeleteObsoleteOperations Integer yes if need Delete Obsolete Operations
IsPaymentHold Integer yes Payment hold
Priority Integer no Priority
ReATPRequired Integer yes ReATPRequired
TypeOfDelivery ShortString yes Type of delivery: Arrival or Ex-Mill
FullyAllocatedDate Date yes The date when order became fully allocated
OrderCompleteDate Date yes The date when order became completed
IsLate Integer no Is a late order
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
OrderLinesForSplit Replenishment
Replenishment
The table stores in-stock balances of warehouses from suppliers
name type identity null description
OriginalOrderLineId Identity no Original order line for split
orderCode String no Item name
lineCode String no Is selected for showing
RequestedDate Date yes Requested date
DeliveryDate Date yes Delivery date
ConfirmedDate Date yes Confirmed date
DespatchDate Date yes Despatch date
Quantity Float no Order weight (Final Weight)
UnitId Identity no Weight unit
OrderLineId Identity yes Original order line for split if provided in split part
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
OrderLineStatuses Replenishment
Replenishment
The table stores the list of possible order line statuses
name type identity null description
Id Identity yes no Identity
OrderLineStatusName ShortString no Order line status name
OrderLineStatusDesc String no Order line status description
OrderLineStatusCode String yes Order line status code
Abbreviation ShortString yes Order line status abbreviation
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
OrderMaintenanceData Replenishment
Temporary
Contains information about consignment stock orders.
name type identity null description
Key Identity no Key
OrderLineId Identity no OrderLine Identity
MaterialRunId Identity no MaterialRun Identity
SkuId Identity no SKU Identity
OrderNo String no Order Code of the order line
LineNo String no Line Number of the order line
Warehouse String no Destination warehouse code of the order line
Product String no Product code of the order line
DeliveryDate Date no Delivery Date of order
Source String yes Source
IsReadOnly Identity no Flag: is quantity and weight is read only?
OperatorUserId Identity no User which insert line
top
OrderOperationMaterials Replenishment
Replenishment
The table stores information about material run operations
name type identity null description
OrderOperationId Identity no Order operation Id
MaterialId Identity no Product
Quantity Float no Quantity
RemainingQuantity Float no Remaining Quantity
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
OrderOperations Replenishment
Replenishment
The table stores information about material run operations
name type identity null description
Id Identity yes no Identity
OrderLineId Identity no Order line ID of the operation
OperationNo Identity no Operation number
SplitNo Identity no Operation split number (for MM the production order number plus product route step plus split is unique
MaterialRunId Identity yes A reference to the MaterialRuns table
WorkCentreId Identity no The ID of the workcentre where the operation will be performed. A reference to the WorkCentres table
OrderOperationStatusId Identity no Current status of the operation. A reference to the OrderOperationStatuses table
Quantity Float no Quantity
DueDate Date yes Finish date of the run
OriginalDueDate Date yes Original due date of the order. This column is populated when the order gets into the system and an operation is assigned to a run
OriginalWorkCentreId Identity yes The ID of the workcentre where the operation is created
StartTime Date yes Date and time job starts: YYYY-MM-DD HH:MI This is the start time of the set up job, not the process job
FinishTime Date yes Date and time the job finishes: YYYY-MM-DD HH:MI Finish time of the process job
SetupDuration Float no Set up time in minutes
ProcessDuration Float yes Time in minutes. Can be not provided.
OperationDuration Float no Calculated operation duration from other columns. Time in minutes
OperationCompletedDuration Float no Calculated completed operation duration from other columns. Time in minutes
Rate Float yes Production rate
UnitId Identity yes Production Rate Unit
QuantityComplete Float no Quantity of the job already complete. Only include this and the following attributes if the job has started or is complete
QuantityCompleteTime Date yes Date the quantity complete was last updated
ActualStartTime Date yes Actual start time of the job
StageCode ShortString yes
StageNo Identity yes
PlanningStatus String yes Status needed by SHP
OperationTypeId Identity no A reference to the OperationTypes table
MaterialId Identity yes A reference to output production product, if NULL used product from order line
IsLastOperation Integer no Is it last operation?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
IsUpdated Integer no If the record was updated?
top
OrderOperationsForPlan Master Planning
Master Planning
The table contains copy of order operations
name type identity null description
OperatorUserId Identity no
WorkCentreId Identity no
OldMaterialRunId Identity yes
MaterialRunId Identity yes
CycleTypeId Identity no
OrderLineId Identity no
OrderOperationId Identity no
DueDate Date yes
top
OrderOperationSnapshots Master Planning
Master Planning
The table contains detailed information about grades/paper machines per SNP period
name type identity null description
SnapshotUserId Identity no
OldMaterialRunId Identity yes
WorkCentreId Identity no
OrderLineId Identity no
OrderOperationId Identity no
DueDate Date yes
MaterialRunId Identity yes
CycleTypeId Identity no
top
OrderOperationStatuses Replenishment
Replenishment
The table stores the list of possible order line statuses
name type identity null description
Id Identity yes no Identity
OrderOperationStatusName ShortString no Order line status name
OrderOperationStatusDesc String no Order line status description
OrderOperationStatusCode String yes Order line status code
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
OrdersForMovingData Block Scheduling
Temporary
A temporary table for storing the list of orders selected by customer for moving to a different run
name type identity null description
OrderLineId Identity no Reference to OrderLines table
OrderOperationId Identity no Reference to OrderOperations table
MaterialId Identity no Reference to Materials table
OldMaterialRunId Identity yes Reference to MaterialRuns table
IsSplitConflict Integer no Is split conflict by default will have value 0
Weight Float no Order line weight
Duration Float no Order line duration
OperatorUserId Identity no User identificator
top
OrdersForNetting Replenishment
Order generation
Temporary table which used for netting customer forecast and customer orders
name type identity null description
DateFrom Date no Devlivery Date of order
Allocation Float no Appropriate PM allocation, received from SNO engine
Orders Float no The sum of firm orders for the specified SKU for a given week
Consumption Float no Consumption for the specified SKU for one week (it is calculated from Forecast, Allocation and Orders)
top
OrdersPerRunData Replenishment
Temporary
Used for display of list of runs on Production Orders screen.
name type identity null description
MaterialRunId Identity no Reference to MaterialRuns table
FirmOrders Float yes Weight firm orders on run
TentativeOrders Float yes Weight tentative(system) orders on run
FirmOrdersDuration Float yes Duration firm orders on run
TentativeOrdersDuration Float yes Duration tentative(system) orders on run
OperatorUserId Identity no User which insert line
top
OverallStockData Due date quoting
Temporary
The table contains information about the overall inventory on every day by SKUs. For each SKU and each day we have opening quantity in the beginning of the day. It is calculated as the difference of incoming and outgoing order quantities of the previous day. Closing quantity is calculated as the difference of incoming and outgoing order quantities of the current day. MinOpening value determines the minimal opening quantity at the real inventory horizon. Data in this table is updated when processing order operations. When recalculating of the real inventory for specific SKUs, appropriate rows can be deleted and inserted.
name type identity null description
SiteMaterialUsageId Identity yes A reference to SiteMaterialUsages
DateFrom Date no Date
Opening Float no Opening quantity
OrdersIn Float yes Incoming orders quantity
OrdersOut Float yes Outgoing orders quantity
Closing Float yes Closing quantity
MinOpening Float yes Minimal opening quantity
Delivered Float no Delivered movements
OnHandInventory Float no Delivered movements
OnHandMinOpening Float no Delivered movements
OperatorUserId Identity no Operator User ID (A reference to Users)
top
PageParameters Core
Configuration
The table stores page parameter definitions
name type identity null description
Id Identity yes no Identity
PageId Identity no Page
ActionId Identity yes Action
ParameterName String no Parameter name
ParameterDescription LongString no Parameter description
ParameterHint LongString yes Parameter hint
ParameterType ShortString yes Parameter type page/session
DataType ShortString yes Parameter data type (Possible values: Boolean, Date, Enum, Number, String)
DefaultValue LongestString no Default system parameter value
Value LongestString yes Parameter value set in model
MinValue ShortString yes Parameter min value
MaxValue ShortString yes Parameter max value
DependOn String yes Name of the parameter on which depends whether the specified parameter is enabled.
DependBehaviour String yes Behaviour of depend element.
DependValues String yes Behaviour values (for comboboxes)
OrderNo ShortString yes Name of the parameter on which depends whether the specified parameter is enabled.
Separator Integer yes Name of the parameter on which depends whether the specified parameter is enabled.
GroupName String yes Group name of parameters.
BundleId Identity yes Bundle with values
IsDevMode Integer no A flag: is this a dev mode action?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Pages Core
Access rights
The table stores the list of I-Plan interface pages
name type identity null description
Id Identity yes no Identity
PageName String no Page name
PageDescription LongString no Page description
PageHint LongString yes Page hint
Icon String yes Page icon
IsBasePage Integer no A flag: is the page a base page? 1 - this is a base page, and it is shown in the tree, 0 - this is an additional page
ShowAlways Integer no Will be page shown irrespective user rights. 1- shown always, 0 - depend on user rights (via Actions)
HelpRef LongString yes Help reference ID
Cloud Integer no Will be page visible for cloud: 1 - yes, 0 - no
BlockedTasks LongestString yes Blocked tasks
CloudParentPageId Identity yes Cloud parent page
IsDevMode Integer no A flag: is this a dev mode action?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
PasteOrdersData Replenishment
Replenishment
name type identity null description
Id Identity yes no Demand identity
OperatorUserId Identity no Operator User ID (A reference to Users)
WorkCentreId Identity yes A reference to the WorkCentres table
MaterialCode String yes
MaterialId Identity yes A reference to the Materials table
MaterialCode_Status Integer no
CustomerCode String yes
CustomerId Identity yes A reference to the Locations table
CustomerCode_Status Integer no
OriginalWeight ShortString yes Order line
Weight Float no Order line
Weight_Status Integer no
OriginalQuantity ShortString yes Order line
Quantity Float no Order line
Quantity_Status Integer no
SkuId Identity yes A reference to the SiteMaterialUsages table
SkuId_Status Integer no
JourneyId Identity yes A reference to the Journeys table
IsFailed Integer no
top
PMSourceData Due date quoting
Temporary table
The table stores the list of available paper machines. The list is recreated at start of each ddq ccrequest. Only the paper machines able to produce the requested material are included into the list.
name type identity null description
PMId Identity no A reference to PaperMachines
PMCode String no Paper Machine Code
AvgLossForFL Float no Average losses on FL machines of the site
LossForPM Float no Losses on the paper machine
PMAllocation Float no Allocation quantity for the paper machine
TotalCost Float no Total cost for the paper machine
LocationPM Identity yes Location ID of the paper machine
SiteId Identity yes Site ID of the paper machine
JourneyId Identity yes Journey ID for this PM
DespatchDate Date yes Despatch date from site's FG Warehouse consideration Journey
DeliveryDate Date yes Delivery date from site's FG Warehouse consideration Journey
TransportMethodId Identity yes Transport method of the last transport route
LocationSourceWarehouseId Identity yes Location Id of site's FG Warehouse
TotalPMAllocation Float yes Total PMAllocation on the site
StageNo Identity no
WorkCentreTypeId Identity no
top
PMSourceForFGData Due date quoting
Temporary table
The table stores the list of paper machines for FG search. It is filled when running an FG search, and cleared when ddq request finished.
name type identity null description
PMId Identity no Paper machine ID
PMCode String no Paper machine code
QuantityFound Float no Found quantity on the PM
PMAllocation Float yes Allocation quantity on the PM
TotalCost Float yes Total cost
top
PreTrimSolutions Block Scheduling
Block Scheduling
Storing generated Pre-Trim solutions for each run.
name type identity null description
Id Identity yes no Unique Identifier
MaterialRunId Identity no A reference to MaterialRuns.Id
SolutionJSON Text yes Detailed solution for chart display (JSON for now as it's a demo)
TrimQty Float no Quantity of orders trimmed
TrimLossQty Float no Quantity of trim loss
MaxWidth Float no Machine's MaxWidth at the time of generation
MinTrimLoss Float no Machine's MinTrimLoss at the time of generation
MaxTrimLoss Float no Machine's MaxTrimLoss at the time of generation
OvermakeCoefficient Float no Order overmake coefficient used for generation
UndermakeCoefficient Float no Order undermake coefficient used for generation
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
PriceRules Core
Core
The table stores the list of rules of price assignment
name type identity null description
Id Identity yes no Identity
Effective Date no The date when the rule becomes active
Price Float no Price
CurrencyId Identity yes A reference to Currencies
DetailId Identity yes A reference to HierarchyPropertyDetails
RuleWeighting Identity no Rule weighting
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Processes Core
Logging
The table stores the list of all launched processes. It is used to track process statuses
name type identity null description
Id Identity yes no Identity
ProcessName String no Process name
ProcessType String no Process type
SystemProcessId String yes System process ID
Started Date no Process creation date/time
Finished Date yes Process completion date/time
Status Integer no Process status. A reference to ProcessStatusNames
UserId Identity no The ID of the user who have started the process
FailedReason LongestString yes Error text for failed processes
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
ProcessingLog Core
Logging
The table is used to maintain external messages log
name type identity null description
Stamp TimeStamp no Identity
Severity String no Severity entry
Message LongestString no Message text
SessionId String no Message text
top
ProcessLogs Core
Logging
The table is used to store process logs. It is used to trace processes execution
name type identity null description
Id Identity yes no Identity
ProcessId Identity no Process ID
Action LongString no Action
Description LongestString no Action description
Stamp TimeStamp no Action start date/time
top
ProcessParts Core
Reference
The table stores the list of process type parts. It is used to organize progress display of processes
name type identity null description
Id Identity yes no Identity
TaskId Identity no Task ID
ProcessPartName String no Process part name
ProcessPartDesc LongString no Process part description
ProcessPartType Integer no Process part type
OrderNo Integer no Ordinal number of the part on the progress screen
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ProcessResults Core
Reference
The table stores the result of process.
name type identity null description
ProcessId Identity no Task ID
Name String no Task result part name
Value LongString yes Task result part description
top
ProcessStatuses Core
Temporary table
The table stores the list of progress values for all parts of all processes launched by users and I-Plan system
name type identity null description
TaskId Identity no Task ID
TaskName String no Task name
ProcessPartId Identity yes Process part ID
ProcessPartName String no Process part name
UserId Identity no User ID
Done Identity no A flag: is the process part completed?
Total Identity no Total
OrderNo Integer no Ordinal number of the part on the progress screen
top
ProcessStatusNames Core - Processes
Reference
The table stores the list of possible process statuses
name type identity null description
Id Identity no Identity
ProcessStatusName ShortString no Process status name
ProcessStatusDesc ShortString no Status description
StatusLevel Integer no Status level
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ProductCharacteristics Core
Core
The table stores the list of product characteristicssystem
name type identity null description
Id Identity yes no Identity
CharacteristicName String no Property name
HierarchyLevelNo Integer no Property name
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ProductGradeCosts Forecasting
Forecasting
The table stores the Market info
name type identity null description
ProductGrade String no Product Grade
SetupCost Float yes Setup Cost
StockValue Float yes Stock Value
HoldingCost Float yes Holding Cost
top
ProductionConfigurations Core
Core
The table stores source priority rules
name type identity null description
Id Identity yes no Identity
MaterialId Identity no Characteristics
ProductRouteId Identity no Product route
Site String yes Site
Preferred Integer no Site
BomId Identity yes BOM
buildRoute String no build route from configuration
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ProductionInformationData Block Scheduling
Temporary
The table contains detailed information about paper machines and finishing areas for each user, to pass to the SNO engine
name type identity null description
OperatorUserId Identity no Operator User ID (A reference to Users)
WorkcentreId Identity yes Workcentre ID (A reference to Workcentres)
TimePeriod Integer no Ordinal number of the time period
DateFrom Date no Week
CapacityHours Float no Available capacity in hours
NominalCapacityHours Float no Nominal Capacity in hours
ShutHours Float no Duration of shuts (in hours)
OrdersHours Float no Time in hours spent to produce nonmovable orders within the time period
TentativeOrdersHours Float no Time in hours for Tentative Orders
FixedCapacityHours Float no Fixed capacity time in hours
UnusedRunHours Float no Unuse capacity time in hours
TimeEfficiency Float no Time efficiency coefficient
top
ProductionPlans Master Planning
Master Planning
The table contains detailed information about grades/paper machines per SNP period
name type identity null description
OperatorUserId Identity no
Id Identity no Material run id?
WorkCentreId Identity no
SourcePeriod Date no
StartDate Date no
FinishDate Date no
CycleTypeId Identity yes Can be null if cycle type is not defined
InitialDuration Float no
OrderDuration Float no
AllocationDuration Float no
Rate Float no Average Rate?
IsFixed Integer no
top
ProductionRates Core
Core
The table stores the list of rules of production rate calculation. It allows to define, how much product can be produced on each workcentre
name type identity null description
Id Identity yes no Identity
OperationTypeId Identity no A reference to the OpearationTypes table
WorkcentreId Identity no A reference to the Workcentres table
Effective Date no The date, when the rule becomes active
Rate Float yes Production rate, base weight unit/hour
TimeEfficiency Float no Coefficient of effective time, percents
MaterialEfficiency Float yes Production efficiency, taking into account production losses
SpecificWeight Float yes Specific weight, cm3/g
ConversionFactor Float no Conversion factor for getting source weight
ProductionRateCode LongString yes Production rate code (It is used for fast comparison)
DetailId Identity no Characteristic details
RuleWeighting Identity no Rule weighting
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ProductionRateSnapshots Master Planning
Master Planning
The table contains snapshots of production rate rules for SNO
name type identity null description
SnapshotUserId Identity no User ID (A reference to Users)
ScenarioId Identity no Scenario ID (A refernce to Scenarios)
OperationTypeId Identity no OperationType ID (A reference to OperationTypes)
WorkcentreId Identity no Workcentre ID (A reference to Workcentres)
Effective Date no Effective date
Rate Float yes Production rate value
OriginalRate Float yes Original Production rate value
TimeEfficiency Float no Time efficiency
MaterialEfficiency Float no Material efficiency
ConversionFactor Float no Conversion factor for getting source weight
DetailId Identity yes Characteristic details
IsGenerated Identity yes A flag: 1 - the rule was generated when creating a snapshot, 0 - the rule has been entered by a user
top
ProductionUpdates Replenishment
Replenishment
Records about what was produced and delivered to production warehouse
name type identity null description
Id Identity yes no Identity
OrderOperationId Identity no Identity
ProductionDate Date no Date
Quantity Float no Quantity
QuantityType String no type of quantity 'OrderLineTotal or DailyTotal. Not used
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ProductRoutes Core
Core
Store Product Routes
name type identity null description
Id Identity yes no Identity
ProductRouteName String no Route code
MaterialTypeId Identity yes Material type Id
DetailId Identity yes Material type Id
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was inserted?
top
ProductRouteStages Core
Core
Store Product Route stages
name type identity null description
Id Identity yes no Identity
ProductRouteId Identity no Product Route Id
OrderNo Integer no Ordinal number
StageCode ShortString no External stage core
OperationTypeId Identity no Operation type Id
StoreOutput Integer no Store Output
CreateCampaign Integer no Create runs for such operation via SNP release
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was inserted?
top
ProjectedInventory Master Planning
Master Planning
The table for projected inventory per site for reporting purpose
name type identity null description
SnapshotDate Date no Snapshot Date
DateFrom Date no Date
SiteId Identity no Site Id
Opening Float no Opening
ProductionOrders Float no Opening
Deliveries Float no Opening
Closing Float no Opening
top
ProjectedInventoryData Master Planning
Master Planning
The temporary table for projected inventory per site
name type identity null description
OperatorUserId Identity no User ID
DateFrom Date no
SiteId Identity no
Opening Float no Opening
ProductionOrders Float no Opening
Deliveries Float no Opening
top
Properties Core
Core
The table stores the list of properties registered in the system
name type identity null description
Id Identity yes no Identity
PropertyName String no Property name
PropertyDesc String no Property code
DataType ShortString yes Data type
DataMask String yes Data mask for property value formatting
DefaultValue String yes Default value of the property
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
PropertyCharacteristics Core
Core
The table stores mapping between properties and product characteristics
name type identity null description
Id Identity yes no Identity
Code1 ShortString yes References to PropertyCodes
Code2 ShortString yes References to PropertyCodes
Code3 ShortString yes References to PropertyCodes
Code4 ShortString yes References to PropertyCodes
Code5 ShortString yes References to PropertyCodes
Code6 ShortString yes References to PropertyCodes
Code7 ShortString yes References to PropertyCodes
Code8 ShortString yes References to PropertyCodes
Code9 ShortString yes References to PropertyCodes
Code10 ShortString yes References to PropertyCodes
Code11 ShortString yes References to PropertyCodes
Code12 ShortString yes References to PropertyCodes
Code13 ShortString yes References to PropertyCodes
Code14 ShortString yes References to PropertyCodes
Code15 ShortString yes References to PropertyValues
Code16 ShortString yes References to PropertyCodes
Code17 ShortString yes References to PropertyCodes
Code18 ShortString yes References to PropertyCodes
Code19 ShortString yes References to PropertyCodes
Code20 ShortString yes References to PropertyCodes
Code21 ShortString yes References to PropertyCodes
Code22 ShortString yes References to PropertyCodes
Code23 ShortString yes References to PropertyCodes
Code24 ShortString yes References to PropertyCodes
Code25 ShortString yes References to PropertyCodes
Code26 ShortString yes References to PropertyCodes
Code27 ShortString yes References to PropertyCodes
Code28 ShortString yes References to PropertyCodes
Code29 ShortString yes References to PropertyCodes
Code30 ShortString yes References to PropertyCodes
Characteristic1 String yes
Characteristic2 String yes
Characteristic3 String yes
Characteristic4 String yes
Characteristic5 String yes
Characteristic6 String yes
Characteristic7 String yes
Characteristic8 String yes
Characteristic9 String yes
Characteristic10 String yes
Key HugeString no
top
PropertyFilterData Forecasting
Temporary
Temporary table for storing filters data
name type identity null description
TaskName String no Task Name
PropertyId Identity no Property ID
PropertyValue String no Property Value
OperatorUserId Identity no User id
top
PropertyValues Core
Core
The table stores the list of property values with references to the parent properties
name type identity null description
Id Identity yes no Identity
PropertyValueCode ShortString yes Code of the property value
Value LongString no Value of the property
PropertyId Identity no A reference to Properties
ParentPropertyValueId Identity yes A reference to the parent property
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
PropertyValuesSpec Core
Core
The table stores material properties (specifications) in unfolded form
name type identity null description
PropertyValueId Identity no Material identity
Value1 LongString yes References to PropertyValues
Value2 LongString yes References to PropertyValues
Value3 LongString yes References to PropertyValues
Value4 LongString yes References to PropertyValues
Value5 LongString yes References to PropertyValues
Value6 LongString yes References to PropertyValues
Value7 LongString yes References to PropertyValues
Value8 LongString yes References to PropertyValues
Value9 LongString yes References to PropertyValues
Value10 LongString yes References to PropertyValues
Value11 LongString yes References to PropertyValues
Value12 LongString yes References to PropertyValues
Value13 LongString yes References to PropertyValues
Value14 LongString yes References to PropertyValues
Value15 LongString yes References to PropertyValues
Value16 LongString yes References to PropertyValues
Value17 LongString yes References to PropertyValues
Value18 LongString yes References to PropertyValues
Value19 LongString yes References to PropertyValues
Value20 LongString yes References to PropertyValues
Value21 LongString yes References to PropertyValues
Value22 LongString yes References to PropertyValues
Value23 LongString yes References to PropertyValues
Value24 LongString yes References to PropertyValues
Value25 LongString yes References to PropertyValues
Value26 LongString yes References to PropertyValues
Value27 LongString yes References to PropertyValues
Value28 LongString yes References to PropertyValues
Value29 LongString yes References to PropertyValues
Value30 LongString yes References to PropertyValues
Code1 ShortString yes References to PropertyCodes
Code2 ShortString yes References to PropertyCodes
Code3 ShortString yes References to PropertyCodes
Code4 ShortString yes References to PropertyCodes
Code5 ShortString yes References to PropertyCodes
Code6 ShortString yes References to PropertyCodes
Code7 ShortString yes References to PropertyCodes
Code8 ShortString yes References to PropertyCodes
Code9 ShortString yes References to PropertyCodes
Code10 ShortString yes References to PropertyCodes
Code11 ShortString yes References to PropertyCodes
Code12 ShortString yes References to PropertyCodes
Code13 ShortString yes References to PropertyCodes
Code14 ShortString yes References to PropertyCodes
Code15 ShortString yes References to PropertyValues
Code16 ShortString yes References to PropertyCodes
Code17 ShortString yes References to PropertyCodes
Code18 ShortString yes References to PropertyCodes
Code19 ShortString yes References to PropertyCodes
Code20 ShortString yes References to PropertyCodes
Code21 ShortString yes References to PropertyCodes
Code22 ShortString yes References to PropertyCodes
Code23 ShortString yes References to PropertyCodes
Code24 ShortString yes References to PropertyCodes
Code25 ShortString yes References to PropertyCodes
Code26 ShortString yes References to PropertyCodes
Code27 ShortString yes References to PropertyCodes
Code28 ShortString yes References to PropertyCodes
Code29 ShortString yes References to PropertyCodes
Code30 ShortString yes References to PropertyCodes
Properties LongestString no References to PropertyValues
top
PurgeObsoleteData Core
Configuration
The table stores parameters for Purge Obsolete Data
name type identity null description
Id Identity yes no Identity
Name String no Name
Description LongString yes Description
Help LongestString yes Help
Period Integer no Period
PeriodType String no Period type
LastAnalyzed Date yes Last date when data was analyzed
ObsoleteEntries Identity no Obsolete entries for removing
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
RealInventoryForFlRunData Due date quoting
Temporary table
The table stores intermediate data from Real Inventory Profile for an SFG search
name type identity null description
SiteMaterialUsageId Identity no A reference to SiteMaterialUsages
SourceWorkCentreId Identity yes A reference to PaperMachines
MinDateFrom Date no Start date of the interval, during which there exists constant material quantity at the inventory
MaxDateFrom Date no End date of the interval of constant material quantity at the inventory
MinOpening Float no Minimal Opening on the interval
OldMinOpening Float no Old minimal Opening. Minimal Opening value is stored here when performing calculations
top
RealInventoryProfiles Due date quoting
Due date quoting
The table contains information about the inventory on every day by SKUs. For each SKU and each day we have opening quantity in the beginning of the day. It is calculated as the difference of incoming and outgoing order quantities of the previous day. Closing quantity is calculated as the difference of incoming and outgoing order quantities of the current day. MinOpening value determines the minimal opening quantity at the real inventory horizon. Data in this table is updated when processing order operations. When recalculating of the real inventory for specific SKUs, appropriate rows can be deleted and inserted.
name type identity null description
SiteMaterialUsageId Identity yes A reference to SiteMaterialUsages
ConsignmentLocationId Identity yes A reference to Locations
SKUKey String no A reference to Workcentres
DateFrom Date no Date
OverallOpening Float no Opening quantity for Firm, Tentative and Consumption
Opening Float no Opening quantity
OpeningNonForecasted Float no Non forecasted opening quantity for Consignment Stock
OrdersIn Float no Incoming orders quantity
TentativeOrdersIn Float yes Incoming tentative orders quantity
OrdersOut Float no Outgoing orders quantity
TentativeOrdersOut Float yes Outgoing tentative orders quantity
ClosingNonForecasted Float no Non forecasted closing quantity for Consignment Stock
Closing Float no Closing quantity
OverallClosing Float no Closing quantity for Firm, Tentative and Consumption
FirmClosing Float yes Closing quantity only for Firm orders
MinOpening Float no Minimal opening quantity
SafetyStock Float no Safety stock
MaxSafetyStock Float yes Safety stock
Consumption Float no Forecst consumption
SupersededStockStatus Integer no Replenishment result
Delivered Float no Delivered movements
OnHandInventory Float no Delivered movements
OnHandMinOpening Float no Delivered movements
top
RealInventoryProfilesData Replenishment
Temporary
The table contains information about the inventory on every day by SKUs. For each SKU and each day we have opening quantity in the beginning of the day. It is calculated as the difference of incoming and outgoing order quantities of the previous day. Closing quantity is calculated as the difference of incoming and outgoing order quantities of the current day.
name type identity null description
DateFrom Date no Date
Opening Float no Quantity at the begining of the DateFrom day
Closing Float yes Quantity at the end of the DateFrom day
OrdersOut Float yes Outgoing orders quantity
OrdersIn Float yes Incoming orders quantity
TentativeIn Float yes Tentative incoming orders quantity
TentativeOut Float yes Tentative outgoing orders quantity
PrevOrdersOut Float yes Outgoing orders for previous date
PrevOrdersIn Float yes Incoming orders for previous date
PrevClosing Float yes Closing for previous date
Consumption Float yes Consumption (can be based on orders, forecast, or netted forecast with orders
SafetyStock Float yes Safety stock
MaxSafetyStock Float yes Safety stock
MinOpening Float yes Min Opening quantity for particular date
OriginalConsumption Float no Original Consumption
OperatorUserId Identity no User id
top
RealInventoryProfileSnapshot Due date quoting
Due date quoting
The table contains information about the inventory on every day by SKUs. For each SKU and each day we have opening quantity in the beginning of the day. It is calculated as the difference of incoming and outgoing order quantities of the previous day. Closing quantity is calculated as the difference of incoming and outgoing order quantities of the current day. MinOpening value determines the minimal opening quantity at the real inventory horizon. Data in this table is updated when processing order operations. When recalculating of the real inventory for specific SKUs, appropriate rows can be deleted and inserted.
name type identity null description
SnapshotUserId Identity no Operator User ID (A reference to Users)
SiteMaterialUsageId Identity yes A reference to SiteMaterialUsages
ConsignmentLocationId Identity yes A reference to Locations
DateFrom Date no Date
Opening Float no Opening quantity
OrdersIn Float no Incoming orders quantity
OrdersOut Float no Outgoing orders quantity
Closing Float no Closing quantity
MinOpening Float no Minimal opening quantity
SafetyStock Float no Safety Stock
TentativeOrdersIn Float no Incoming tentative orders quantity
TentativeOrdersOut Float no Outgoing tentative orders quantity
top
Reasons Replenishment
Replenishment
The table stores the list of available reasons for commenting forecast editing and other user actions
name type identity null description
Id Identity yes no Identity
Reason String no Reason name
ReasonType ShortString no Reason type
ReasonDescription LongString yes Reason description
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
RebalancedOrderLines Replenishment
Replenishment
The table stores in-stock balances of warehouses from suppliers
name type identity null description
ProcessId Identity yes Process Id for rebalance orders and available onhandstock
OrderLineId Identity no Original order line for rebalance
SiteMaterialUsageId Identity no
ConsignmentLocationId Identity yes
FinalWeight Float no
DispatchedWeight Float no
AllocatedStockWeight Float no
RemainingOperationWeight Float no
RemainingWeight Float no
NewAllocatedStockWeight Float yes
ReturnedAllocatedStockWeight Float yes
RequestedDate Date no Requested date
ConfirmedDate Date no Confirmed date
InsertDate Date no Confirmed date
Priority Integer no Confirmed date
OrderNo Integer no Order for balancing
Comments LongString no Comment for order
IsSent Integer no Order for balancing
TimeStamp TimeStamp no When record was addeed or updated
top
RebalancedStock Replenishment
Replenishment
The table stores in-stock balances of warehouses from suppliers
name type identity null description
ProcessId Identity no Process Id for rebalance orders and available onhandstock
SiteMaterialUsageId Identity no
ConsignmentLocationId Identity yes
PreviousStock Float no
OnHandStock Float no
top
RemainingOrdersData Replenishment
Replenishment
The table is used for storing Remaining Orders
name type identity null description
OperatorUserId Identity no A reference to the Users table
SiteMaterialUsageId Identity no A reference to SiteMaterialUsages
SiteId Identity yes Site Id of the paper machine
DateFrom Date no Date from
Weight Float no Min opening consignment stock
top
RemovedOrderLineEntities Replenishment
Replenishment
Store entity identifiers for sending into another external system
name type identity null description
TargetSystem String no Target system
EntityId Identity no Original entity identity
OrderCode String no Order book code
OrderLine String no Order line lineNoCode
TimeStamp TimeStamp no When record added
IsSent Integer no Is order line sent
top
ReplacedLocations Core
Core
The table stores the list of replaced locations
name type identity null description
FromLocationId Identity no old location Id
ToLocationId Identity no Replaced location Id
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
ReplenishedCustomerDemands Replenishment
Replenishment
The table stores information about the allocations of SKUs
name type identity null description
SiteMaterialUsageId Identity no A reference to the SiteMaterialUsages table
DateFrom Date no Date
Forecast Float no Forecast for one week for the specified SKU
Demand Float no Appropriate PM allocation, received from SNO engine
Orders Float no The sum of firm orders for the specified SKU for a given week
NettedOrders Float no Orders for netting, moved in periods
Consumption Float no Consumption for the specified SKU for one week (it is calculated from Forecast, Allocation and Orders)
IsWorkingDay integer no Is Working Day
top
ReplenishedCustomerSKU Replenishment
Order generation
The table stores data about customer SKU's which involved in the allocation based replenishment
name type identity null description
SiteMaterialUsageId Identity no A reference to SiteMaterialUsages
MaterialId Identity yes A reference to Materials
SourceMaterialId Identity yes A reference to Materials, source material
LocationId Identity yes A reference to Locations
JourneyId Identity yes A reference to Journeys
ConsignmentLocationId Identity yes A reference to Locations
WorkcentreId Identity yes PM Id where allocation exists for such SKU
Portion Float no Portion
SourceSiteMaterialUsageId Identity yes Source SKU ID
TimePeriod Integer yes Duration (days) from source to destination
MaxPeriod Integer no Max perido for demand calculation
DateFrom Date no Date
DateTo Date no Date
GroupKey String yes Group key
top
ReplenishedPoints Replenishment
Order generation
The table contains the list of primary warehouse SKUs
name type identity null description
Id Identity no Identity
GroupKey String yes A group key
GroupType String yes A group type - Company, Site, Location
GroupId Identity yes A group key
SiteMaterialUsageId Identity no Primary warehouse SKU
MaterialId Identity no Primary warehouse material
LocationId Identity no Primary warehouse location
WarehouseLocationId Identity yes Group warehouse location
ConsignmentLocationId Identity yes Primary warehouse location
GroupSiteId Identity yes Source workcentre site
GroupCompanyId Identity yes Source workcentre company
ConsumptionType String no Consumption type - can be FG or SFG
IsSingleStage Integer no A flag: is this a single stage material?
IsFinishedGoods Integer no A flag: is this a finished goods material?
Allocation Float no Allocation for replenishment point of the paper machine
IgnoreNegativeInventoryDays Integer yes 0 - ignore negative demand, positive ignore negative demands for N days, null - nothing
IgnoreNegativeInventoryMethod String yes
ChainStartDate Date no Start date for searching crash date
ReplenishmentStartDate Date yes replenishment start date
ReplenishmentFinishDate Date yes replenishment finish date
Replenished Integer no Does sku replenished?
ChainsQuantity Identity yes Quantity of chains
SelectedChain Identity yes Chain for which we will create orders
AllowSubstitution Integer no Flag indicate if an order can be substituted or not.
Possibility Integer yes Chain for which we will create orders
IsSelected Integer no Flag indicate if an sku selected for replenished.
Criteria Integer no Criteria by production rate properties
ReplenishmentHorizon Integer no Chain for which we will create orders
top
ReplenishedSKU Replenishment
Order generation
The table stores all warehouse SKUs which will be replenished in the process of allocation based replenishment
name type identity null description
PointId Identity no Replenishment point identity
ChainNo Integer no Chain no for replenishment point
LevelNo Identity no Level number
GroupKey String no Group key
Replenished Integer no Does sku replenished?
SiteMaterialUsageId Identity no A reference to SiteMaterialUsages
LocationId Identity no A reference to Locations
MaterialId Identity no A Reference to Materials
WarehouseLocationId Identity yes Group warehouse location
IsSingleStage Integer no A flag: is this a single stage material?
IsFinishedGoods Integer no A flag: is this a single stage material?
ConsignmentLocationId Identity yes Primary warehouse location
SourceSiteMaterialUsageId Identity yes Source SKU
IsConsignmentStock Integer no A flag: should we replenish from consignment stock?
FromLocationId Identity yes Source location ID
FromWorkcentreId Identity yes Destination workcentre ID
FromTransportLocationId Identity yes Source location ID
ToTransportLocationId Identity yes Destination workcentre ID
TransportWorkcentreId Identity yes TransportWorkcentreId for orders
FromSiteId Identity yes Source Site ID
SourceMaterialId Identity yes Source material
ToSiteId Identity yes Source Site ID
JourneyId Identity yes Journey ID
TotalTimePeriod Identity no Total Time Period to first warehouse in chain
CalendarId Identity yes A reference to Calendars
FATimePeriod Identity yes Duration (days) from SFG warehouse to Finishing line
FrozenPeriod Identity no Frozen period in days
FrozenPeriodStartDate Date no First day after frozen period
ReArrangeDate Date no First date where sku can be replenished
MaxCapacity Float no MaxCapacity
SourceType String yes Source type - can be : DirectWH, WH, DirectPM, SWH, SitePM , AllPm
LocationChain LongestString yes Location replenishment chain
PriorityPath LongestString yes Location priority path
AllowSubstitution Integer no Flag indicate if an order can be substituted or not.
StageNo Integer no Stage No for operations.
top
ReplenishedSubstitutedSku Replenishment
Order generation
The table stores pair of substituted SKU's
name type identity null description
SiteMaterialUsageId Identity no superseded sku
OnSiteMaterialUsageId Identity no on sku
MaterialId Identity no superseded product identity
Replenished Integer no Is superseded delisted?
top
ReplenishmentHorizonRules Core
Core
The table stores source priority rules
name type identity null description
Id Identity yes no Identity
DetailId Identity no Weight of rule
RuleWeighting Integer no Weight of rule
ReplenishmentHorizon Integer no Replenishment horizon
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ReplenishmentReports Replenishment
Replenishment
Temporary table for storing warehouse sku data for replenishment report.
name type identity null description
DateFrom Date no Report date
WarehouseSkuId Identity no Warehouse SKU Id
FinalForecast Float no
AdditiveFinalForecast Float no
DeliveriesIn Float no
OrdersOut Float no
History Float no
SafetyStock Float no
Inventory Float no
InternalInventory Float no
ExternalInventory Float no
Consumption Float no
IsWorkingDay Integer no
CalendarId Identity no
DaysOfSupply Integer no Days of supply (delivery time)
HighQuantity Float no Maximal quantity
LowQuantity Float no Minimal quantity
MaxCapacity Float no Max capacity
Replenished Integer no A flag: is the SKU replenished? (0 - not replenished, 1 - replenished)
SafetyStockMethodId Identity no ID of the SafetyStock calculation method
ReplenishmentFrequency Identity no Frequency of warehouse replenishment
UpperPercentile Float no Upper percentile
LowerPercentile Float no Lower percentile
ReplenishmentStartDate Date yes Replenishment start date
ReplenishmentFinishDate Date yes Replenishment start date
MinOrderQuantity Float no Minimal order quantity
OrderUnitId Identity no A reference to Units
top
ReplenishmentRestrictions Replenishment
The table store logs of the consignment stock edit
name type identity null description
Id Identity yes no Identity
WorkcentreId Identity no A reference to the SiteMaterialUsages table
PropertyId Identity no A reference to the Locations table
RangeFrom Float yes
RangeTo Float yes
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who inserted the record?
UpdateDate Date yes When the record was inserted?
top
ReportFilterEntries Reports
Reports
Filter entries
name type identity null description
ReportFilterId Identity no Report filter identity
FieldName String no Field name
Operation String no Operation
FilterValues Text yes list of filter values
Aggregation String yes Aggregation function
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ReportFilters Reports
Reports
Report filters
name type identity null description
Id Identity yes no Filter Id
DataSourceId Identity no Data Source identity
Code String yes Filter name
IsShared Integer no Filter shared flag
Logic String no Logic to combine criteria (AND/OR)
HashCode HugeString yes Filter hash code for comparison
ToolTip HugeString yes Filter ToolTip
SqlText Text yes Filter condition
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ReservationStockSKUData Replenishment
Temporary
A temporary table for Stock Reservation (ticket 51626)
name type identity null description
OperatorUserId Identity no Operator User ID (A reference to Users)
OrderNo Identity yes Material Id
SkuKey String no SKU Code - SKU-CS-SW.
SiteMaterialUsageId Identity no SiteMaterialUsage Id
LocationId Identity no Location Id
MaterialId Identity no Material Id
ConsignmentLocationId Identity yes Consignment Location Id
top
RestMessagesLog Due date quoting
Logging
The table is used to maintain rest messages log
name type identity null description
Id Identity no Identity
Endpoint String yes
MessageReceivedTime TimeStamp no
MessageCompletedTime TimeStamp no
MessageIn Text yes
MessageOut Text yes
top
Roles Core
Access rights
The table stores the list of all roles available in I-Plan
name type identity null description
Id Identity yes no Identity
RoleName String no Role name
RoleDescription LongString no Role description
IsAdmin Integer no If on then user who have such role have access to all locations and workcentres
IsInternal Integer no A flag: is this internal (not editable and non-removable role?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
RolesActions Core
Access rights
The table describes many-to-many relation between roles and actions
name type identity null description
Id Identity yes no Identity
ActionId Identity no Action ID
RoleId Identity no Role ID
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
RolesDataSources Reports
Access rights
The table describes many-to-many relation between roles and system reports
name type identity null description
RoleId Identity no System Role Id
DataSourceId Identity no data source id
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
RolesTasks Core
Access rights
The table describes many-to-many relation between roles and task (process) notifications
name type identity null description
Id Identity yes no Identity
TaskId Identity no Task ID
RoleId Identity no Role ID
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
RolesWidgets Core
Access rights
The table describes many-to-many relation between roles and Widgets
name type identity null description
Id Identity yes no Identity
WidgetId Identity no Widget ID
RoleId Identity no Role ID
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
RPTemporaryOrders Replenishment
Order Generation
The table stores temporary orders generated during allocation based replenishment for each replenishment chain
name type identity null description
PointId Identity yes A reference to SiteMaterialUsages
ChainNo Integer no A chain number for replenishment point
LevelNo Identity no Level number
DestinationLocationId Identity no Destination location
SiteMaterialUsageId Identity yes A reference to SiteMaterialUsages
ConsignmentLocationId Identity yes A reference to Locations
LocationId Identity no A reference to Locations
MaterialId Identity no A Reference to Materials
SourceMaterialId Identity yes A Reference to Materials
GroupKey String yes A reference to Sites
FromLocationId Identity yes Source location of the item
FromWorkcentreId Identity yes Source workcenter of the item
TransportWorkcentreId Identity yes TransportWorkcentreId for orders
OperationWorkcentreId Identity yes OrderOperation workcentre Id
FromSiteId Identity yes Source site of the item
ToSiteId Identity yes Source site of the item
SourceSiteMaterialUsageId Identity yes Source SKU ID
FATimePeriod Identity yes Duration (days) from SFG warehouse to the finishing line
DespatchDate Date yes Despatch date from the warehouse
DeliveryDate Date yes Delivery date to the destination area
RequestedDate Date yes Requested date to the destination area
ConsumptionDate Date yes Delivery date to the destination area
FinishingDate Date yes Delivery date to the destination area
JourneyId Identity yes Journey ID
MaterialRunId Identity yes A reference to MaterialRuns
Weight Float Weight
DueDate Date yes Weight
SourceWeight Float no Weight
AvailableInventory Float no Weight
IsCreateOrder Integer no Order is create
AllowSubstitution Integer no Flag indicate if an order can be substituted or not.
MaxCapacity Float no Max Capacity.
SourceConsignmentLocationId Identity yes Order is create
SourceType String no Order is create
FrozenPeriod Identity no Frozen period in days
FrozenPeriodStartDate Date no First day after frozen period
ToTransportLocationId Identity yes Destination workcentre ID
FromTransportLocationId Identity yes TransportWorkcentreId for orders
MaxLevelNo Identity no Quantity of levels in the chain
Rate Float no Rate
Stageno Integer no StageNo for last operation
top
RPTemporarySTOOrders Replenishment
Replenishment
The table is used for storing stock transfer orders
name type identity null description
LevelNo Integer no Replenished SKU Level No
OrderNo Integer no OrderNo from the JourneyRoutes table
DespatchDate Date no A despatch date
DeliveryDate Date no A delivery date
top
RsoDemands Replenishment
Replenishment
Store demands for RSO property sets
name type identity null description
Id Identity yes no Demand identity
RsoPropertySetId Identity no Property Set Id
RsoScenarioId Identity no Scenario Id
Width Integer yes Demand width
Weight Float no Demand weight
PatternQty Integer yes Demand pattern qty (output from RSO, for selected stock size)
RsoStockSizeId Identity yes Stock Size Id (assigned by RSO)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
RsoPropertySets Replenishment
Replenishment
Store RSO property sets (individual RSO problems)
name type identity null description
Id Identity no Property set identity
RsoScenarioId Identity no Scenario Id
RequestedStockSizes Integer yes Nuber of requested stock sizes
DetailId Identity no HierarchyProperty DetailId
Properties HugeString yes comma separated properties
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
RsoScenarios Replenishment
Replenishment
Store RSO scenarios
name type identity null description
Id Identity yes no Scenario identity (-1 to use the current scenario)
Name String yes Scenario name
UserId Identity no User ID of the scenario owner
WorkcentreId Identity no ID of the workcentre the scenario is for
DateFrom Date no The start date of scenario
DateTo Date no The end date of scenario
DemandGenerationDate Date no Date of the demand snapshot creation
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
RsoStockSizes Replenishment
Replenishment
Stock sizes created manually and by the RSO process
name type identity null description
Id Identity yes no Stock size identity
RsoPropertySetId Identity no Property Set Id
RsoScenarioId Identity no Scenario Id
Width Integer yes Demand width
IsRequired Identity yes A flag (1 means that the stock size should be kept by RSO process)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
RunInventoryProfiles Block Scheduling
Block Scheduling
The table stores allocations as inputfor BSO engine
name type identity null description
DateFrom Date no Date
SiteId Identity no Site Identity
GradeId Identity no Grade Identity
Opening Float no Calculate Opening for current date by using opening from RealInventoryProfile for all SKU which match selected GradeId
Demand Float no Passed Allocations and Orders to BSO from table BSOInputData + orders assigned to runs before BSOHorizon based on OrderOperations.DueDate (between CurrentDate and BSOStartDate)
Capacity Float no Calculate daily run capacity for BSO generated runs plus runs with StartDate before BSOStartDate and Finishdate after CurrentDate, proparting run daily capacities take from getMPBSComparison
Closing Float no Opening - Demand + Capacity
SafetyStock Float no Calculate SafetyStock for each Grade/Date - take sum of safety stocks from InventoryProfiles which match GradeId
OperatorUserId Identity no User identity
top
RunsForAdjustingData Block Scheduling
Block Scheduling
name type identity null description
Guid String no Unique identifier per batch
MaterialRunId Identity no Unique identifier
PositionNo Identity no Position No
StartDate Date no Run start date
FinishDate Date no Run end date
TargetStartDate Date yes Run target start date
InitialDuration Float no Initial duration and real run duration, including changeover
SwitchoverDuration Float no Changeover duration. This duration is a part or run duration
WorkcentreId Identity no A reference to Workcentres.Id
RunType String yes Run type: production, floating shut or opportunistic run
top
SafetyStockMethods Core
Configuration
The table stores the list of available methods of safety stock calculation
name type identity null description
Id Identity yes no Identity
SafetyStockMethodName String no Method name
SafetyStockMethodDesc LongString no Method description
IsMaxMethod Integer no Can be used method as Max safety stock method
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SafetyStockSnapshots Master Planning
Master Planning
The table contains snapshots of production cost rules for SNO.
name type identity null description
ScenarioId Identity no ScenarioId
SnapshotUserId Identity no User ID (A reference to Users)
SiteId Identity yes Workcentre ID (A reference to Workcentres)
Effective Date no Effective date
Percentage Float no Cost
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SAInventorySourcingData Master Planning
Temporary
A temporary table for SA Sourcing View screen
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
Id Identity no Group Id
SummaryFields HugeString yes Group fields
DateFrom Date no date
Capacity Float no
InitialInventory Float no
TotalInventory Float no
AvailableInventory Float no
Allocation Float no
SafetyStock Float no
OriginalSafetyStock Float no
InventoryDeficit Float no
RestoredAllocation Float no
IsProductionPeriod Integer no
Orders Float no
Revenue Float no
Cost Float no ProductionCost
Margin Float no
top
SASiteInventoryData Master Planning
Temporary
A temporary table for SA Site Inventory screen
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
Id Identity no Group Id
SummaryFields HugeString yes Summary fields
DateFrom Date no date
Opening Float no
Incoming Float no
Outgoing Float no
Produced Float no
Dispatched Float no
UnallocatedRunCapacity Float no
RemainingAllocation Float no
AllocatedProduction Float no
CustomerAllocation Float no
top
SASourcingData Master Planning
Temporary
A temporary table for SA Sourcing View screen
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
Id Identity no Group Id
DateFrom Date no date
Capacity Float no
NominalCapacity Float no
Allocation Float no
Orders Float no
Utilisation Float no
CycleInventory Float no
Revenue Float no
ProductionCost Float no ProductionCost
TransportCost Float no TransportCost
InventoryCost Float no InventoryCost
TotalCost Float no TotalCost
UtilisationTime Float no
Margin Float no
Profitability Float no Margin per hour
CapacityHours Float no
AllocationHours Float no
OrdersHours Float no
ShutHours Float no
UnallocatedHours Float no
Losses Float no Losses
top
SATransportationData Master Planning
Temporary
A temporary table for SA Sourcing View screen
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
Id Identity no Group Id
SummaryFields HugeString yes Group fields
DateFrom Date no date
MinCapacity Float no
MaxCapacity Float no
Allocation Float no
Orders Float no
Revenue Float no
ProductionCost Float no ProductionCost
TransportCost Float no TransportCost
InventoryCost Float no InventoryCost
TotalCost Float no TotalCost
Margin Float no
Filtered Integer no
top
ScenarioActionParameters Master Planning
Master Planning
The table contains saved history of user actions for SNO scenarios.
name type identity null description
ActionId Identity no Ordinal number of the action
ParameterName LongestString no SQl statement text
ParameterType LongestString no A comment to show in GUI
ParameterValue LongestString yes Snaptshot owner user ID
InsertDate Date yes Date and time when the action was inserted
top
ScenarioActions Master Planning
Master Planning
The table contains saved history of user actions for SNO scenarios.
name type identity null description
Id Identity no Ordinal number of the action
ScenarioId Identity no Scenario ID (a reference to Scenarios)
ActionName String yes System mnemonic of the user's action
SqlText LongestString yes SQl statement text
ActionComment LongestString yes A comment to show in GUI
SnapshotUserId Identity yes Snaptshot owner user ID
InsertDate Date no Date and time when the action was inserted
top
ScenarioAnalysisSnapshots Master Planning
Master Planning
The table contains user snapshots of SKU coefficients for prorating
name type identity null description
SnapshotUserId Identity no User ID who have created the snapshot (A reference to Users)
ScenarioId Identity no ScenarioId
SnpItemId Identity no Snp item Id
DeliveryDate Date no
ChainNo Identity no
SourceDate Date no
SeqNo Integer no
WorkcentreId Identity no
OperationTypeId Identity no
Cost DoubleFloat yes
Rate Float yes
top
ScenarioComparisonData Master Planning
Temporary
Temporary table for comparing scenarios in SA
name type identity null description
ScenarioId Identity yes Scenario Id
UserId Identity yes User Id
ScenarioName String yes Scenario Name
Forecast Float no Forecast
RemainingForecast Float no Forecast after pretenning and aggregation
IgnoredSmallDemands Float no SNO Demand
SNODemand Float no SNO Demand
FirmOrders Float no Non-moveable orders weight
NonMoveableOrdersWithLoss Float no Non-moveable orders with losses
Allocation Float no Allocation
UnAllocatedDemand Float no Unallocated demand
UnAllocatedPMCapacity Float no Unallocation PM capacity
Revenue Float no Revenue
Cost Float no Cost
Margin Float no Margin
OperatorUserId Identity no Who update line?
DateFrom Date yes Date (week start date)
top
ScenarioPeriodSnapshots Master Planning
Master Planning
An internal table used in SNO when creating or removing a snapshot.
name type identity null description
SnapshotUserId Identity no User Id (a reference to Users)
StartPeriod Date no Start Period date
EndPeriod Date no End Period End
PeriodNumber Integer no Ordinal number of period
PeriodLength Integer no Period length in days
top
ScenarioRates Core
Temporary
Temporary table for calculated production rates in SNO
name type identity null description
SnapshotUserId Identity no USer Id
ScenarioId Identity no Scenario Id
WorkcentreId Identity no Workcentre Id
SiteId Identity no Site Id
OperationTypeId Identity no OperationType Id
PropertyValueId Identity no Property Value Id
CycleTypeId Identity yes Property Value Id
IsActive Integer no Is rate can be used in this period
HasOrder Integer no Indication what order is exists
HasRun Integer no Indication what run with fixed capacity is exists
Rate Float no Production Rate
Cost Float yes Production Rate
ConversionFactor Float no Conversion factor
MaterialEfficiency Float no Material efficiency
TimeEfficiency Float no Time efficiency
DateFrom Date yes Effective date
top
Scenarios Master Planning
Master Planning
Uses SNO scenarios created during the user SNO Session
name type identity null description
Id Identity yes no Scenario identity (-1 to use the current scenario)
ScenarioName String yes Scenario name
IsCurrentBase Identity yes A flag (1 means that the current scenario is selected as the parent scenario)
OptimizationMode Integer no Optimization mode selected for the SNO engine
Released Integer no A flag (1 means that the scenario was released, 0 - non-released scenario
SnapshotUserId Identity no User ID of the snaptshot owner
State String no State: None, Stored, Optimized, ReferenceChanged
HasReferenceChanges Integer no A flag: does the scenario have any changes in reference data which not taking in optimisation process? 1- yes, 0 - no
IsProblem Integer yes A flag: does the scenario have any problems in data? 1 - yes, 0 - no
IsAllDemandsMandatories Integer yes A flag: does the all demands are mandatory in this scenario
PenaliseDowntime HugeString yes Workcentres/workcentreTypes to penalise downtime for
IgnoreSourceLists Integer no A flag: Ignore source lists
UseOnlyPrimarySources Integer no A flag: Use only primary sources
UseMinAllocation Integer no A flag: Apply minimum allocation settings
IsCrossSite Integer no A flag: Whether to allow cross-site (cross-mill) allocations
DifferenceFG Integer yes Max weeks to produce early
DifferenceFGReplenished Integer yes Max weeks to produce early (replenished)
DifferenceSFG Integer yes Number of weeks between PM and SFG Warehause
Ranks HugeString yes Comma-separated customer ranks taken in account
UseUnlimitedPMCapacity Integer no A flag: does the use unlimited production capacity in this scenario
LatenessPeriods Integer no Max lateness weeks
IsFullLog Integer no A flag: Whether to generate full log
InsertDate Date no When scenario was created
top
ScenarioSessions Master Planning
Master Planning
The table contains definitions of user snapshots for SNO.
name type identity null description
SnapshotUserId Identity no User ID
SnapshotPeriodType String no Which snapshot period type used: Day, Week, Month, WeekMonth, Quarter
FixedPeriod Integer no Duration of Fixed period (days,weeks, months, Quarter)
UseFixedPeriod Integer no Actually use frozen period.
Horizon Integer no SNO session horizon (number of weeks to plan to)
SourceHorizon Integer no SNO session source horizon (number of weeks to plan to)
ReadOnly Integer no A flag (1 means that the session is read-only, so user can only view screens and cannot change anything)
IsValid Integer no Is session created properly
UsedPriceSettings String no Which prices used: Reference, Forecast or ForecastAndReference
CreationDate Date no The date when session was created.
StartDate Date no The internal start of session
SourceStartWeek Date no The first week of the sourcing SNO horizon
StartWeek Date no The first week of the SNO horizon
FixedPeriodDate Date no The fixed period **end** period date. Check that
FinishWeek Date no The last week of the SNO horizon
ForecastSnapshotId Identity yes Forecast snapshot identifier. If null session created from system forecast, otherwise from snapshot
top
ScheduleRules Core
Schedules
The table stores schedule rules
name type identity null description
Id Identity yes no Identity
ScheduleId Identity no A reference to schedule
ScheduleRuleNo String no Schedule number
Day Integer yes Day of month
DayOfWeek Integer yes Day of week
NumOfWeek Integer yes Number of week
Month Integer yes Month
Year Integer yes Year
Description LongString no Description
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Schedules Core
Schedules
In this table schedules are stored. A schedule defines when a product can be despatched from a warehouse.
name type identity null description
Id Identity yes no Identity
ScheduleName String no Schedule name
GeneralScheduleId Identity yes Parent schedule ID
DefaultAvailable Integer no A flag: 0 - all rules of this schedule define possible shipping dates, 1 - impossible shipping dates
IsReceivingDays Integer yes A flag; defines, if this schedule is used for defining possible leave dates or for possible receiving dates
LastGeneratedDate Date yes When schedule was last time regenerated.
LastExistingDate Date yes Schedule last existing date.
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ScheduleSources Core
Schedules
The table stores detailed information on each day of schedules. Schedule rules are expanded into this table.
name type identity null description
ScheduleId Identity no Schedule ID (A reference to Schedules)
DateFrom Date no Date
IsLeaveDay Integer yes A flag: is this a shipping day? Meaning of this flag depends on Schedules.DefaultAvailable value for the schedule
Description LongString yes Description (copied from the rule)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
SecondPassRules Core
Core
The table stores forecast method rules
name type identity null description
Id Identity yes no Identity
ReportFilterId Identity yes Filter Id
CharacteristicsList HugeString no List of characteristics for grouping
RuleWeighting Integer no Rule Weighting
ForecastMethodId Identity no Forecast method
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SelectiveData Forecasting
Temporary
Temporary table for selective or full forecast generation process. Table contains the list of skus
name type identity null description
FirstPassId Identity no Id from SecondPass properties
SecondPassId Identity yes Id from SecondPass properties
SecondPassRuleId Identity yes Id from SecondPassRules
SiteMaterialUsageId Identity no SMU Id
ForecastMethodId Identity yes Forecast Method Id
SecondForecastMethodId Identity yes Forecast Method Id
HistoryStartDate Date yes History Start Date
Successed Integer no Does SKU have supercessions in the future
StartDate Date yes Start Date for forecast (used for future supercessions
CurrencyId Identity no Currency
UseTradingDays Integer no Use Trading Days for forecast generation
CalendarId Identity no Use Trading Days for forecast generation
LowerPercentile Float no Lower percentile
UpperPercentile Float no Upper percentile
HistoryExists Integer no Does SKU have history
Patterns LongString yes list of sku Forecast patterns
SecondPatterns LongString yes list of sku Forecast patterns for second pass
CharacteristicsList LongString yes list of characteristics for second pass
Characteristics HugeString yes Characteristics values
OperatorUserId Identity no user id
top
SelfLog Core
Logging
The table is used to maintain external messages log
name type identity null description
Stamp TimeStamp no Identity
Message Text no Message text
ProcedureName String no Message text
OperatorUserId Identity no Message text
top
SiteInventorySnapshots Master Planning
Master Planning
A table for SA Site Inventory screen for Fixed period.
name type identity null description
SnapshotUserId Identity no User ID (reference to Users )
SiteId Identity no Group Id
DateFrom Date no date
Opening Float no
Incoming Float no
Outgoing Float no
Produced Float no
Dispatched Float no
UnallocatedRunCapacity Float no
RemainingAllocation Float no
AllocatedProduction Float no
CustomerAllocation Float no
top
SiteMaterialUsages Core
Core
The table stores the list of SKU parameters
name type identity null description
Id Identity yes no Identity
MaterialId Identity no SKU material ID
LocationId Identity no SKU location ID
EndUseId Identity yes Identity
EndCustomerId Identity yes Identity
DaysOfSupply Integer no Days of supply (delivery time)
MaxDaysOfSupply Integer no Max Days of supply (delivery time)
HighQuantity Float no Maximal quantity
LowQuantity Float no Minimal quantity
MinOrderQuantity Float yes Minimal order quantity
OrderUnitId Identity yes A reference to Units
MaxCapacity Float yes Capacity of the warehouse
Status Integer yes A flag: is the SKU forecasted? (0 - not forecasted, 1 - forecasted)
HistoryStartDate Date yes History start date. The earliest month of history, which need to be taken into account when generating forecast
Replenished Integer no A flag: is the SKU replenished? (0 - not replenished, 1 - replenished)
ReplenishmentFlag Integer no A flag: does SKU replenished or have non-zero source priority to replenished SKU? (0 - not replenished, 1 - replenished)
ForecastMethodId Identity yes ID of the forecast calculation method
SafetyStockMethodId Identity yes ID of the SafetyStock calculation method
MaxSafetyStockMethodId Identity yes ID of the SafetyStock calculation method
CustomerRankId Identity yes A reference to CustomerRanks
UpperPercentile Float yes Upper percentile
LowerPercentile Float yes Lower percentile
ReplenishmentFrequency Identity no Frequency of warehouse replenishment
MaxReplenishmentFrequency Identity no Frequency of warehouse replenishment
ForecastStartDate Date yes Forecast start date
ForecastFinishDate Date yes Forecast end date
ReplenishmentStartDate Date yes Replenishment start date
ReplenishmentFinishDate Date yes Replenishment start date
SourceListId Identity yes A reference to SourceLists
inhibitProduction Integer no A flag: disable further production of the SKU?
inhibitSFGSearch Integer no A flag: disable further search of SFG materials for the SKU
DDQContingency Float yes The quantity of units for keep on the warehouse
TurnOffForecastId Identity yes A reference to forecast header which has turn off this sku (by supersessions)
TurnOnForecastId Identity yes A reference to forecast header which has turn on this sku (by supersessions)
NeedCheckForecastId Identity yes A reference to forecast header ....
LastInventoryDate Date yes Last known inventory date
GroupKey String yes Group key for grouping in replenishment
DefaultCustomerForecast ShortString no values - NotSet, System, Budget, Zero, Budget then Zero
NettingAlgorithm String yes Netting algorithm for replenishment. Values from Bundle NettedAlgorithm
AlternateProduct String yes Alternate Product
ExistingAlternateProduct String yes Alternate Product
SkuKey String no Destination SKU Code - SKU-CS-SW
SkuProperty1 String yes Sku Property 1
SkuProperty2 String yes Sku Property 2
SkuProperty3 String yes Sku Property 3
SkuProperty4 String yes Sku Property 4
SkuProperty5 String yes Sku Property 5
SkuProperties HugeString yes All sku properties
DerivedCharacteristic1 String yes Derived Characteristic 1
DerivedCharacteristic2 String yes Derived Characteristic 2
DerivedCharacteristic3 String yes Derived Characteristic 3
DerivedCharacteristic4 String yes Derived Characteristic 4
DerivedCharacteristic5 String yes Derived Characteristic 5
SafetyStockPercentWarning Float yes Safety stock percent warning
UpperPercentileMethod String no Method for upper percentile
ReplenishmentHorizon Float yes ReplenishmentHorizon
UpperPercentileMonths Integer no Method for upper percentile
ForecastFrozenEditingPeriod Integer yes Hidden columns managed by rules
ConsumptionType String yes What will be used as replenishment demand - forecast or allocation, null - mean use value from system parameter ReplenishmentDemandType
IsActiveSku Integer no Is suck sku have inventory or movements. Valid only for WH skus
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SiteProperties Core
Core
The table stores the list of properties registered in the system
name type identity null description
Id Identity yes no Identity
PropertyName String no Property name
HierarchyLevelNo Integer no Property name
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Sites Core
Core
The table stores the list of all sites registered in I-Plan
name type identity null description
Id Identity yes no Identity
SiteName String no Site name
SiteCode ShortString no Site external code
Ownership Float no percent of profit
TaxRate Float no Tax Rate
BSLocked Identity no 0 - BS process not locked site; 1 -0 - BS process locked site
ProcessId Identity yes BS process identity that locked site
SafetyStockMethodId Identity yes Default safety stock method
GroupReplenishedLocations Integer no Group Replenished locations
Latitude ShortString yes Latitude
Longitude ShortString yes Longitude
StandardTransportCost DoubleFloat no Standard transport cost
SiteProperty1 String yes Site Property 1
SiteProperty2 String yes Site Property 2
SiteProperty3 String yes Site Property 3
SiteProperty4 String yes Site Property 4
SiteProperty5 String yes Site Property 5
SiteProperties HugeString yes All site properties
UserId Identity yes The ID of the user who have locked the site
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SkuComments Reference
Reference
The table stores the list of commmented for replenished (warehouse sku)
name type identity null description
Id Identity yes no Identity
ReasonId Identity no A reference to Reasons
SiteMaterialUsageId Identity no A reference to Reasons
ConsignmentLocationId Identity yes A reference to Reasons
CommentText HugeString yes Allocation comment
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SkuDetails Core
Core
The table stores characteristics
name type identity null description
DetailId Identity no Characteristic ID from HierarchyPropertyDetails
SiteMaterialUsageId Identity no Sku Id
top
SkuForecastPatterns Forecasting
Forecasting
The table stores forecast patterns/trends for second pass rule for particular SKU
name type identity null description
Id Identity yes no Identity
SecondPassRuleId Identity yes A reference to second pass rule
SiteMaterialUsageId Identity yes SKU (A reference to SiteMaterialUsages)
ForecastSampleMethodId Identity yes Forecast sample method
ForecastPatternId Identity no Forecast pattern Identity
ForecastPatternDate Date yes Forecast pattern start date
PatternPositionNo Identity yes Pattern position
InsertUserId Identity yes Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SkuLaunchProfiles Forecasting
Forecasting
The table stores forecast patterns/trends for second pass rule for particular SKU
name type identity null description
Id Identity yes no Identity
SecondPassRuleId Identity yes A reference to second pass rule
SiteMaterialUsageId Identity yes SKU (A reference to SiteMaterialUsages)
ForecastSampleMethodId Identity yes Forecast sample method
LaunchProfileId Identity no Forecast pattern Identity
LaunchDate Date yes Forecast pattern start date
LaunchTotal Float yes Pattern position
InsertUserId Identity yes Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SKULeadTimes Replenishment
Replenishment
The table store average non-production periods of finishing lines and paper machines, depending on the material
name type identity null description
SiteMaterialUsageId Identity no A reference to the SiteMaterialUsages table
MTSLeadTime Integer no Timeperiod from MTS Warehouse to customer, in case of MTO decision should be use FG WH of Mill as source point
DirectLeadTime Integer no Timeperiod from route from FG WH of site (depend on Site) to customer
MTSMillLeadTime Integer no Transport time from Mill FG WH to MTS warehouse, in case if for SKU/PM pair not defined MTS warehouse (i.e. MTO SKU) this value should zero
TotalLeadTime Integer no TimePeriod + ProductionCycleTime + FinishingCycleTime + FinishingLeadTime
top
SkuProperties Core
Core
The table stores the list of properties registered in the system
name type identity null description
Id Identity yes no Identity
PropertyName String no Property name
HierarchyLevelNo Integer no Property name
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SkuValuesLogs Core
Core
The table stores about sources for SKUs
name type identity null description
SiteMaterialUsageId Identity no A reference to SiteMaterialUsages
ConsignmentLocationId Identity yes A reference to SiteMaterialUsages
FieldName String no A reference to Workcentres
Value String yes A reference to initial source rule
Description String yes A reference to initial source rule
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
TimeStamp TimeStamp no When the record was inserted?
top
SMIForecastData Forecasting
Forecasting
A temporary table for forecast collaboration
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
Id Identity no Grouped Identity
Summary HugeString yes
DateFromMonth Date yes date
DateFromWeek Date yes date
Forecast Float no
WeeklyForecast Float no
TotalForecast Float no
IsWorking Integer no
ForecastStatusId Integer no
Editable Integer no
ForecastComment LongestString yes
ForecastChangeId Identity yes
ReasonId Identity yes
WeeklyForecastComment LongestString yes
WeeklyForecastChangeId Identity yes
WeeklyReasonId Identity yes
top
SMIInventoryData Replenishment
Temporary
The table contains information about inventories on every single day, by SKUs
name type identity null description
DateFrom Date no Date
Opening Float no Quantity at the begining of the DateFrom day
Forecast Float yes Consumption used in replenishment calculations
PlannedFirm Float yes Consumption (can be based on orders, forecast, or netted forecast with orders
PlannedTentative Float yes Consumption (can be based on orders, forecast, or netted forecast with orders
ProducedFirm Float yes Total income according to incoming orders and deliveries
ProducedTentative Float yes Total income according to incoming orders and deliveries
InTransit Float yes Incoming tentatave orders
Closing Float yes Inventory, taking into account tentative and firm orders
SafetyStock Float yes Safety stock
PlannedForProduction Float yes Inventory, taking into account firm orders only
OperatorUserId Identity no User id
top
SnapshotAllocationData Master Planning
Master Planning
A temporary table for snapshot allocation
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
Id Identity no Grouped Identity
SummaryFields HugeString yes SummaryFields
DateFrom Date yes date
Allocation Float no
IsWorking Integer no
Filtered Identity no
top
SnapshotTableInfos Master Planning
Master Planning
An internal table used in SNO when creating or removing a snapshot.
name type identity null description
SnapshotUserId Identity no User Id (a reference to Users)
TableName String no Table name
OrderNo Integer no Ordinal number
HaveStateFieldFlag Integer no A flag (1 - the table has the SnapshotState field, 0 - doesn't have it)
IsDeleteFlag Integer no A flag (1 - the table can be safely cleared with delete command)
IsPartitionedTableFlag Integer no A flag (1 means that the table has partitions)
NoStaticticsFlag Integer yes A flag (1 means that the statictics for this table will not be gathered)
top
SNOAllOrderSnapshots Master Planning
Master Planning
The table contains snapshot of all orders relevant to Master Planning)
name type identity null description
SnapshotUserId Identity no User ID (A reference to Users)
OrderLineId Identity no Reference to OrderLines.Id
OrderOperationId Identity yes Reference to OrderOperations.Id
SiteId Identity no Site Id where the order is sourced from
WorkcentreId Identity yes Workcentre Id where the order is sourced from
LocationId Identity no Location Id where the order is to be delivered to
MaterialId Identity no Material Id of the order's SKU
SourceMaterialId Identity no SorceMaterial Id of the order
SiteMaterialUsageId Identity no Order's SKU ID
IsFirm Integer no Is current order the Firm one?
SourceType String no Type of order's source: PM for paper machine, SFGWH for semifinidhing warehouse, FGWH for finishing warehouse, FL for finishing line, UNKNOWN otherwise.
DestinationType String no Type of order's destination: SFGWH for semifinishing warehouse, FGWH for finishing warehouse, CUST for customer, UNKNOWN otherwise
MethodCode String yes Used for debug purposes: internal code.
FinishingMethodCode String yes Used for debug purposes: internal code.
SourceWeight Float no Order source weight
Weight Float no Order weight (SFG for SFGWH-targeted orders and FG otherwise)
RemainingWeight Float no Order remaining weight
RemainingSourceWeight Float no Order remaining weight
ProductionDate Date yes Calculated for relevant firm non-moveable orders only.
RequestedDate Date yes Requested date of the order
DespatchDate Date yes Despatch date of the order
SourcePeriod Date yes Source Period - truncated to snapshot period type
DeliveryPeriod Date yes Delivery Period - truncated to snapshot period type
PropertyValueId Identity yes Property value ID (A reference to PropertyValues)
SourcePropertyValueId Identity yes Property value ID (A reference to PropertyValues)
HierarchyId Identity yes Hierarchy ID (A reference to Hierarchies)
CustomerRankId Identity yes Customer rank ID (A reference to CustomerRanks)
ProductionCost Float no Production cost
InventoryCost Float no Inventory cost
TransportCost Float no Transport cost
TotalCost Float no Total cost
Price Float no Price
Revenue Float no Revenue
Margin Float no Margin
SnoItemId Identity yes Sno Item ID
CoProductId Identity yes CoProduct Id
Rate Float no PM Production Rate
ConversionFactor Float no Production Rate Conversion Factor
MasterRouteId Identity yes Master Route Id
MRTimePeriod Integer yes Master Route time period
MRCost Float yes Master route cost
JourneyId Identity yes Reference to Journeys table
OperationTypeId Identity yes Reference to Journeys table
ToConsignmentLocationId Identity yes for consignment orders, this indicates the consignment location that the order will be stored for at the destination location
FromConsignmentLocationId Identity yes for call off orders, this indicates the consignment location that the stock is being sourced from
StageNo Integer no Stage No
IsLastStage Integer no Is Last Stage
Duration Float no Order duration
RemainingDuration Float no Order duration
MaterialEfficiency Float no Material efficiency
TimeEfficiency Float no Time efficiency coefficient
top
SNOCustomersData Master Planning
Master Planning
A table for storing of temporary snapshots
name type identity null description
SnapshotUserid Identity no Snapshot User ID (A reference to Users)
Id Identity no Unique identifier of the record
HierarchyId Identity no
CustomerName LongString no
CustomerRankId Identity no
Optional Integer no
top
SNODemands Master Planning
Master Planning
The table contains user snapshots of demands for SNO
name type identity null description
ScenarioId Identity no Scenario ID (A refernce to Scenarios)
SnapshotUserId Identity no User ID (A reference to Users)
DateFrom Date no The date of demand (Delivery date)
Id Identity no SNP Item Id
CoProductId Identity yes CoProduct Id
Forecast Float no Forecast value for the SNO item
NonMoveableFirm Float no Non-movable firm orders of the SNO item
Inventory Float no inventory as demand (excess on warehouses)
InventoryDeficit Float no inventory deficit (not a demand)
Demand Float no demand
MandatoryDemand Float no Netted demand
OptionalDemand Float no Netted demand
Netted Float no demand
Aggregated Float no Aggregated demand
TotalDemand Float no Aggregated cleared on orders
AfterPreNetting Float no Forecast value after prenetting
SNODemand Float no sno Demand
ToHierarchyId Identity yes master route Hierarchy ID (A reference to Hierarchies)
Price Float no Price
CoProductPrice Float no CoProduct Price
Cost Float no Cost
Revenue Float no Revenue
Margin Float no Margin
Allocation Float no Allocation value received from SNO engine for the demand
IsDemand Integer no An internal column. 1 means that the SNO item has non-zero demand on a week within horizon
UnallocatedReasonId Identity no Unallocated Reason
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
SNOForecastData Master Planning
Master Planning
A temporary table for creating forecast snapshots
name type identity null description
SnapshotUserId Identity no User ID who have created the snapshot (A reference to Users)
SitematerialUsageId Identity no SMU ID (A reference to SiteMaterialUsages)
DateFrom Date no Scenario snapshot period
Final Float no Final forecast
Price Float no Price
IsOrder Integer yes 1 - this sku has orders ,0 - this sku has not orders
Status Integer yes Forecast Status
top
SNOInventoryCostData Master Planning
Master Planning
A temporary table for calculating of inventory costs before transferring them to the SNO bridge
name type identity null description
SiteId Identity no Site ID (A reference to Sites)
TimePeriod Identity no Ordinal number of the time period
DateFrom Date no Week
Cost Float no Cost
SnapshotUserId Identity no User ID (A reference to Users)
top
SNOItemCoefs Master Planning
Master Planning
The table contains user snapshots of SKU coefficients for prorating
name type identity null description
SnapshotUserId Identity no User ID who have created the snapshot (A reference to Users)
Id Identity no SNP item Identity
SiteMaterialUsageId Identity no SMU ID (A reference to SiteMaterialUsages)
MaterialId Identity no Material ID (A reference to Materials)
DateFrom Date no Start date (week)
Coef DoubleFloat no Coefficient
SkuSum Float no Forecast sum by the first SKU
AllSum Float no Forecast sum by all SKUs included into the specified SNO item
Forecast Float no Forecast sum by SKU
Demand Float no Demand sum by SKU
Forecast2 Float no Forecast sum by SKU
Demand2 Float no Demand sum by SKU
top
SNOItems Master Planning
Master Planning
The table contains information about grouping SMU into SNO items
name type identity null description
HierarchyId Identity yes Hierarchy ID (A reference to Hierarchies)
PropertyValueId Identity no Property value ID (A reference to PropertyValues)
CustomerRankId Identity no Customer rank ID (A reference to CustomerRanks)
SiteMaterialUsageId Identity no SMU ID (A reference to SiteMaterialUsages)
LocationId Identity no Location ID (A reference to Locations)
MaterialId Identity yes Reference to SKU Material Id
Status Integer no A flag: Forecasted? 1 - forecasted ,0 - not forecasted
IsWarehouse Integer no Is warehouse
HasInventory Integer no Has inventory Deficit
Id Identity yes SNO item ID
ConfigurationSet String yes Production configuration set
IncludedInPrenetting Integer no Is sku included in pre-netting
CoverPeriod Integer no Cover period from SafetyStock methods
MinimumAllocationId Identity yes User ID who have created the snapshot (A reference to Users)
EndUseId Identity yes Reference to SKU EndUSe ID, used for performance
EndUseProperty1 String yes EndUseProperty1
EndUseProperty2 String yes EndUseProperty2
EndUseProperty3 String yes EndUseProperty3
EndUseProperty4 String yes EndUseProperty4
EndUseProperty5 String yes EndUseProperty5
Characteristic1 String yes Characteristic1
Characteristic2 String yes Characteristic2
Characteristic3 String yes Characteristic3
Characteristic4 String yes Characteristic4
Characteristic5 String yes Characteristic5
Characteristic6 String yes
Characteristic7 String yes
Characteristic8 String yes
Characteristic9 String yes
Characteristic10 String yes
CoProductList HugeString yes semicolon separated list in format: CoProductId:Percentage
CoProductPercentage Float no sum of percentage of coproducts
SnapshotUserId Identity no User ID who have created the snapshot (A reference to Users)
ReplenishmentFlag Integer no A flag: does SKU replenished or have non-zero source priority to replenished SKU? (0 - not replenished, 1 - replenished)
CycleTypeId Identity yes Cycle type (set of properties) for fixed capacities
top
SNOItemsShort Master Planning
Master Planning
The table contains information about grouping into SNO items
name type identity null description
Id Identity no SNO item ID
NettingGroupId Identity yes Id For netting
HierarchyId Identity yes Hierarchy ID (A reference to Hierarchies)
PropertyValueId Identity no Property value ID (A reference to PropertyValues)
MaterialId Identity yes Product Id for replenshed sku items
CoProductId Identity yes CoProduct Id
CustomerRankId Identity no Customer rank ID (A reference to CustomerRanks)
ConfigurationSet String yes Production routes configuration set (list of production configurations
CoverPeriod Integer no Cover period from SafetyStock methods
IsDemandRecord Integer no Demand stage flag
IsOptional Integer no Optional flag
IsForecast Integer no Forecasted flag
IsWarehouse Integer no Warehouse flag
SplitItemId Integer yes Demand split to optional and mandatory
MinimumAllocationId Identity yes User ID who have created the snapshot (A reference to Users)
Description LongestString no SNP Item description
EndUseProperty1 String yes EndUseProperty1
EndUseProperty2 String yes EndUseProperty2
EndUseProperty3 String yes EndUseProperty3
EndUseProperty4 String yes EndUseProperty4
EndUseProperty5 String yes EndUseProperty5
Characteristic1 String yes Characteristic1
Characteristic2 String yes Characteristic2
Characteristic3 String yes Characteristic3
Characteristic4 String yes Characteristic4
Characteristic5 String yes Characteristic5
Characteristic6 String yes
Characteristic7 String yes
Characteristic8 String yes
Characteristic9 String yes
Characteristic10 String yes
CoProductList HugeString yes semicolon separated list in format: CoProductId:Percentage
CoProductPercentage Float no sum of percentage of coproducts
ReplenishmentFlag Integer no A flag: does SKU replenished or have non-zero source priority to replenished SKU? (0 - not replenished, 1 - replenished)
CycleTypeId Identity yes Cycle type (set of properties) for fixed capacities
ProductRouteId Identity yes Product Route
SnapshotUserId Identity no User ID who have created the snapshot (A reference to Users)
top
SNOMaterialCoefs Master Planning
Master Planning
The table contains user snapshots of SKU coefficients for prorating
name type identity null description
SnapshotUserId Identity no User ID who have created the snapshot (A reference to Users)
MaterialId Identity no SMU ID (A reference to SiteMaterialUsages)
Id Identity no SNP item Identity
DateFrom Date no Start date (week)
Coef DoubleFloat no Coefficient
top
SNOPreNettingAllocations Master Planning
Master Planning
The table contains user FG and SFG pre-netting allocations.
name type identity null description
SnapshotUserId Identity no User ID (A reference to Users)
ScenarioId Identity no Scenario Id
SnoItemId Identity no SNO Item unique identifier
IsFinishedGoods Integer no FG/SFG inventory indicator: 0 for SFG, 1 for FG inventories.
WHWorkcentreId Identity no Workcentre Id - reference to Warehouse of the source SKU
SiteMaterialUsageId Identity yes Reference to Customer SKU Id
SourceSiteMaterialUsageId Identity no Reference to Warehouse SKU Id
ConsignmentLocationId Identity yes Consignment location Id
StockDate Date no Original available stock week (date)
SourceDate Date no Consumption date.
DeliveryDate Date no Delivery date.
FLWorkcentreId Identity yes Reference to Finishing line Id where inventory is allocated at.
Allocation Float no amount of inventory
SFGAllocation Float no amount of inventory
MasterRouteId Identity yes reference to Master Route Id
TransportCost Float no transport cost
InventoryCost Float no inventory cost
top
SNOSFGInventoryData Master Planning
Master Planning
A temporary table for calculating of an inventory snapshot of semifinishing warehauses
name type identity null description
SnapshotUserId Identity no User ID (reference to Users )
MaterialId Identity no material id(reference to materials)
LocationId Identity no location id (reference to locations)
SitematerialUsageId Identity no SMU ID (reference to SiteMaterialUsages)
SiteId Identity no Site ID (reference to Sites)
CustomerRankId Identity no Customer rank ID (reference to CustomerRanks)
LastInventoryDate Date yes last known inventory date for this sku
SafetyStock Float yes Safety Stock
InOrders Float yes total ammount of inbound orders
OutOrders Float yes total ammound of outbound orders
Inventory Float yes inventory
top
SNOSFGtoFGMapData Master Planning
Temporary
mapping between fg materials and sfg materials
name type identity null description
SnapshotUserId Identity no User Id
FGmaterialId Identity no Finishing material Id
SFGMaterialId Identity no Semifinishing material Id
top
SNOSKUWeeklyData Master Planning
Temporary
temporary table for resolve perfomance problem weeklyforecastbody snapshot creation
name type identity null description
SnapshotUserId Identity no User Id
Id Identity no SiteMaterialUsage Id
Status Integer no forecasted flag
IsOrder Integer no is order flag
top
SNOSolutionTempData Master Planning
Master Planning
A temporary table for storing sno solution data received from SNO engine
name type identity null description
SnapshotUserId Identity no User ID (A reference to Users)
DeliveryPeriod Integer no Delivery Date (Demand date)
SourcePeriod Integer no Production date
SnoItemId Identity no SNO item id
AllocationId Identity no Allocation Id (links stages)
MasterRouteId Identity yes Master route ID
WorkcentreId Identity yes Workcentre ID (A reference to Workcentres)
Allocation Float yes Allocation
TransportCost Float yes Transport cost
InventoryCost Float yes Inventory cost
ProductionCost Float yes Production cost
ConfigurationId Identity yes Production configuration
OperationTypeId Identity yes Operation Type
NextOperationTypeId Identity yes Operation Type
SeqNo Identity yes Operation Type
StageNo Integer StageNo
IsLastStage Integer Is Last Stage
SourcePropertyValueId Identity yes Operation Type
BomMaterialId Identity yes BOM Material Id
SourceMaterialId Identity yes SFG Source material
IsSafetyStock Integer no Is used ss or it's recovery
WarehouseSnpItemId Identity yes WH SNO Item Id (for restoring SS)
top
SNPEdges Master Planning
Master Planning
The table contains the list of SNO issues (problems) within the specified user snapshots
name type identity null description
SnapshotUserId Identity no User ID (reference to Users )
FromSiteId Identity no Property value ID (reference to PropertyValues)
ToSiteId Identity no delivery date (demand date)
ToHierarchyId Identity no delivery date (demand date)
TimePeriod Integer no delivery date (demand date)
DelayDays Float no
top
SNPInventorySnapshots Master Planning
Master Planning
The table contains user snapshots of consolidated SNP Inventory.
name type identity null description
SnapshotUserId Identity no User ID (A reference to Users)
ScenarioId Identity no Scenario Id
DateFrom Date no Date for available inventory
IsFinishedGoods Integer no FG/SFG inventory indicator: 0 for SFG, 1 for FG inventories.
GradeId Identity yes Grade Id based on production rates
SiteId Identity no Main Site Warehouse
Inventory Float no Initial Inventory
Opening Float no Initial Inventory
Capacity Float no Initial Inventory
Orders Float no Initial Inventory
Indicatives Float no Initial Inventory
Allocation Float no Used Allocation.
top
SNPMaterialRunSnapshots Master Planning
Master Planning
The table contains detailed information about grades/paper machines per SNP period
name type identity null description
SnapshotUserId Identity no
ScenarioId Identity no
MaterialRunId Identity yes
WorkCentreId Identity no
SourcePeriod Date no
StartDate Date no
FinishDate Date no
CycleTypeId Identity no
InitialDuration Float no
OrderDuration Float no
IsFixed Integer no
IsActive Integer no
OriginalOrderNo Integer no
AvailableDuration Float no
Rate Float no
NewMaterialRunId Identity yes
top
SNPProductionPlanSnapshots Master Planning
Master Planning
The table contains detailed information about grades/paper machines per SNP period
name type identity null description
SnapshotUserId Identity no
ScenarioId Identity no
Id Identity no
WorkCentreId Identity no
SourcePeriod Date no
StartDate Date no
FinishDate Date no
CycleTypeId Identity no
InitialDuration Float no
OrderDuration Float no
AllocationDuration Float no
Rate Float no
IsFixed Integer no
top
SNPUnallocatedData Master Planning
Master Planning
The table contains the list of SNO issues (problems) within the specified user snapshots
name type identity null description
SnapshotUserId Identity no User ID (reference to Users )
SnpItemId Identity no Property value ID (reference to PropertyValues)
DeliveryPeriod Integer no delivery date (demand date)
SourcePeriod Integer no delivery date (demand date)
WorkcentreId Identity no
Reason LongestString no
top
SNPUnallocatedItemDetails Master Planning
Master Planning
The table contains the list of SNO issues (problems) within the specified user snapshots
name type identity null description
SnapshotUserId Identity no User ID (reference to Users )
ScenarioId Identity yes Scenario ID (refernce to Scenarios)
SnpItemId Identity no Property value ID (reference to PropertyValues)
CycleTypeId Identity yes Cycle type
ProductionConfigurationId Identity no Property value ID (reference to PropertyValues)
ProductRouteId Identity no Property value ID (reference to PropertyValues)
OperationTypeId Identity no Property value ID (reference to PropertyValues)
StageNo Integer no Stage of operation
PropertyValueId Identity no Property value ID (reference to PropertyValues)
WorkcentreId Identity yes
WorkcentreTypeId Identity yes
SiteId Identity yes
HasSite Integer no
HasRoute Integer no
HasValidSource Integer no
HasRate Integer no
HasCost Integer no
Rate Float yes Production rate
Cost Float yes
TransportCost Float yes
HoldingCost Float yes
HasCapacity Integer no
UnallocatedReasonId Identity no code of problem
top
SNPUnallocatedItems Master Planning
Master Planning
The table contains the list of SNO issues (problems) within the specified user snapshots
name type identity null description
SnapshotUserId Identity no User ID (reference to Users )
ScenarioId Identity yes Scenario ID (refernce to Scenarios)
SnpItemId Identity no Property value ID (reference to PropertyValues)
CycleTypeId Identity yes Cycle type
DateFrom Date yes delivery date (demand date)
Demand Float no
Allocation Float no
ProductionConfigurationId Identity yes Property value ID (reference to PropertyValues)
ProductRouteId Identity yes Property value ID (reference to PropertyValues)
FirstDeliveryPeriod Date yes
LeadTime Integer yes
CycleFrequency Integer yes
HasRates Integer no
HasCosts Integer no
HasPrice Integer no
HasRoute Integer no
HasSite Integer no
IsMandatory Integer no
IsProfitable Integer no
HasCapacity Integer no
Price Float yes
Cost Float yes
Rate Float yes
TransportCost Float yes
MarginPerHour Float yes
UnallocatedReasonId Identity no
top
SNPUnallocatedItems2 Master Planning
Master Planning
The table contains the list of SNO issues (problems) within the specified user snapshots
name type identity null description
SnapshotUserId Identity no User ID (reference to Users )
ScenarioId Identity yes Scenario ID (refernce to Scenarios)
SnpItemId Identity no Property value ID (reference to PropertyValues)
DateFrom Date yes delivery date (demand date)
Demand Float no
Allocation Float no
IsMandatory Integer no Is Mandatory Demand
FirstDeliveryDate Date yes First Possible delivery period
Price Float yes Price
TotalCost Float yes Min total cost
TransportCost Float yes min transport cost
TransportTime Integer yes min duration days
UnallocatedReasonId Identity no
top
SNPWorkCentreFixedGrades Master Planning
Master Planning
Should be exposed for PropertyValueId (as rates)
name type identity null description
ScenarioId Identity no Scenario ID (A refernce to Scenarios)
SnapshotUserId Identity no User ID (A reference to Users)
WorkCentreId Identity yes Workcentre ID (A reference to Workcentres)
CycleTypeId Identity no SNP Grade Id
DateFrom Date no Week
CapacityHours Float no Available capacity in hours
top
SourceLists Core
Core
The table stores source list descriptions. A source list is a set of workcetres
name type identity null description
Id Identity yes no Identity
SourceList HugeString no List of source workcentres
IsFull Integer no A flag: is the source list complete?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SourceListSources Core
Core
The table describes many-to-many relation between source lists and sources
name type identity null description
SourceListId Identity no A reference to SourceLists
WorkcentreId Identity no A reference to Workcentres
InsertUserId Identity no Who inserted the line?
InsertDate Date no When the line was inserted?
top
SourcePriorities Core
Core
From which workcentres SKU warehause will be replenished. It depends from Priority
name type identity null description
Id Identity yes no Identity
SiteMaterialUsageId Identity no Destination SiteMaterialUsage identity
DestinationLocationId Identity no Destination location identity
DestinationMaterialId Identity no Destination material identity
SourceSiteMaterialUsageId Identity yes Source SiteMaterialUsage identity
SourceLocationId Identity yes Source location identity
SourceMaterialId Identity yes Source material identity
ConsignmentLocationId Identity yes A reference to Locations
WorkCentreId Identity no A reference to Workcentres
Priority Integer no Source priority (1, 2, empty, 0)
Portion Integer no Percent of the source use, along with other sources of the given SKU
SourcePriorityRuleId Identity yes A reference to SourcePriorityRules
JourneyId Identity yes JourneyId for use with this SKU
MaterialTypeId Identity yes Define from which material type we will source
IsConsignmentStock Integer no Indicate that sourcing will be from consignment stock (ued in replenishment)
RPJourneyId Identity yes Journey selected for replenishment
DateFrom Date yes Effective start date
DateTo Date yes Effective finish date
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SourcePriorityRules Core
Core
The table stores source priority rules
name type identity null description
Id Identity yes no Identity
DetailId Identity yes A reference to Hierarchies table
WorkCentreId Identity no A reference to the destination workcentre
Priority Integer no Source priority (1, 2, empty, 0)
Percentage Integer no Percentage
Rebuild Integer no Rebuild
RuleWeighting Integer no Rule Weighting
JourneyId Identity yes JourneyId for use with this SKU
MaterialTypeId Identity yes Define from which material type we will source
IsConsignmentStock Integer no Indicate that sourcing will be from consignment stock (used in replenishment)
DateFrom Date yes Effective start date
DateTo Date yes Effective finish date
GroupName String yes Group name
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SourceRunMaterials Replenishment
Order generation
The table stores data about available runs and material which when can produce for allocation based replenishment process
name type identity null description
MaterialRunId Identity no A reference to MaterialRuns
MaterialId Identity no Material identity
Cost Float yes Calculate production cost for combination Material/Paper Machine
Rate Float yes Production Rate for Material/Paper Machine
top
SourceRuns Replenishment
Order generation
The table stores data about available runs for allocation based replenishment process
name type identity null description
SiteWHLocationId Identity yes A reference to Locations
WorkcentreId Identity no A reference to Workcentres
SiteId Identity yes A reference to Sites
MaterialRunId Identity no A reference to MaterialRuns
OriginalDuration Float no Run Duration
Duration Float no Run Duration
OriginalCapacity Float no Run original capacity
Capacity Float no Run capacity
StartDate Date no The date when run will be started
FinishDate Date no The date when run will be finished
CalculatedFinishDate Date no The date when run will be finished
MaxTrimLoss Float no Maximal trim loss
MinTrimLoss Float no Minimal trim loss
MaxSheetOut Float no Maximal sheet out
ConsumptionType String yes Consumption type - can be FG or SFG
HandlingDelay Float no Handling delay (minutes) before of shipping
IsUnlimitedCapacity Integer no Is unlimited capacity
Cost Float no Calculate production cost for combination Material/Paper Machine
Rate Float no Run process rate
ConversionFactor Float no Conversion factor for getting source weight
IsLastStage Integer no 1 = used for last stage, 0 - used for all stages
PointId Identity yes Virtual run for specific replenishment point
top
SourceWorkcentresData Block Scheduling
Temporary
A temporary table for storing the list of source workcentres for selected orders
name type identity null description
OrderLineId Identity no Reference to OrderLines table
WorkCentreId Identity no Reference to WorkCentres table
IsValid Integer no 0 - no valid; 1 - is valid
OperatorUserId Identity no User identificator
top
SourcingAllocation Master Planning
Master Planning
The table contains user snapshot info about splitting demand allocation on paper machines, finishing and semifinishing warehouses
name type identity null description
ScenarioId Identity no Scenario ID (A refernce to Scenarios)
Id Identity no SNP Item Id
CoProductId Identity yes CoProduct Id
SnapshotUserId Identity no User ID (A reference to Users)
DeliveryDate Date no Demand date (Despatch date)
SourceDate Date no Sourcing date
SiteId Identity no Site ID (A reference to Sites)
WorkCentreId Identity yes Workcentre ID (A reference to Workcentres)
AllocationId Identity no Allocation Id (links stages)
StageNo Integer no Stage No
IsLastStage Integer no Is Last Stage
Allocation Float no Allocation value on the paper machine
CycleInventory Float no Cycle inventory
Price Float no Revenue
Revenue Float no Revenue
ProductionCost Float no ProductionCost
TransportCost Float no TransportCost
InventoryCost Float no InventoryCost
Margin Float no Margin
MasterRouteId Identity yes Master route ID(A reference to MasterRoutes)
Rate Float yes production rate
ConversionFactor Float no production rate conversion factor
MaterialEfficiency Float no material efficiency
TimeEfficiency Float no time efficiency
ConfigurationId Identity yes Production Configuration Id
ProductRouteId Identity yes Production Route Id
OperationTypeId Identity yes Operation Type
NextOperationTypeId Identity yes Next Operation Type
SourcePropertyValueId Identity yes Source SNP grade
SourceMaterialId Identity yes Source material
BomSourceMaterialId Identity yes Source material
SeqNo Identity yes Operation Type
IsSafetyStock Integer no Is used ss or it's recovery
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
SplitRunsData Block Scheduling
Block Scheduling
Temp table for split runs by Started status
name type identity null description
OperatorUserId Identity no User Identity
PositionNo Integer no
WorkcentreId Identity no
MaterialRunId Identity no
StartDate Date no
FinishDate Date no
TargetStartDate Date yes
Duration Integer no
RunStatusCode String yes
MinStartedDate Date yes
SystemDuration Float no
FirmDuration Float no
SystemWeight Float no
FirmWeight Float no
HaveLateOrders Integer no
top
SPValuesData Core
Temporary
The temporary table for storing of list of system parameters values.
name type identity null description
ParameterId Identity no System parameter Id (A reference to SystemPparameters).
Key String yes Key
Value LongString yes Value
OrderNo Integer yes OrderNo
Description LongString yes Description of value.
OperatorUserId Identity no Operator User ID (A reference to Users)
top
StageAllocations Master Planning
Master Planning
The table contains detailed information about grades/paper machines per SNP period
name type identity null description
AllocationId Identity no Allocation Id
CharacteristicsId Identity no Characteristics
DeliveryWeek Date yes Delivery week
DeliveryMonth Date yes Delivery Month
top
StageAllocationSources Master Planning
Master Planning
The table contains detailed information about grades/paper machines per SNP period
name type identity null description
AllocationId Identity no Allocation Id
WorkcentreId Identity no Workcentre Id
OperationTypeId Identity no Operation Type Id
SourceWeek Date yes Source week
SourceMonth Date yes Source Month
UnitId Identity no WorkcentreId
AllocationValue Float no WorkcentreId
isLastStage Integer no Is last stage
top
StagedInventoryProfiles Replenishment
Replenishment
The table contains information about inventories on every single day, by SKUs
name type identity null description
DateFrom Date no Date
Phase String no Phase
SiteMaterialUsageId Identity yes SKU Id
LocationId Identity yes Location Id
MaterialId Identity no Material Id
ConsignmentLocationId Identity yes Consignment customer identity
Opening Float no Opening stock
Consumption Float no Consumption (can be based on orders or forecast or netted forecast with orders
ConsumptionOrders Float no Order Consumption - outgoing orders and deliveries
ConsumptionForecast Float no Forecst consumption
FirmOrdersIn Float no Incoming orders and deliveries
TentativeOrdersIn Float no Incoming Tentative orders
TentativeOrdersOut Float no Outgoing Tentative orders
PlannedInventory Float no Inventory with taking in account tentative adn firm orders
SafetyStock Float no Safety stock
MaxSafetyStock Float yes Safety stock
OriginalSafetyStock Float no Safety stock
MinOpening Float no Min opening
MinPlannedInventory Float no Min planned Inventory
OriginalConsumptionForecast Float no Original Consumption Forecast
IgnoredDemandValue Float no Ignored Demand Value
IsRunAvailable Integer no Is run available
IsReceivingDate Integer no Is Receiving Date
InsertDate Date no When record was created
GroupKey String no Group key included Site, Company or Location and identity key
top
StockMonitoringData Replenishment
Temporary
A temporary table for Stock Monitoring (ticket 52254)
name type identity null description
OperatorUserId Identity no Operator User ID (A reference to Users)
OrderNo Identity no Order No
SiteMaterialUsageId Identity yes SiteMaterailUsage Id
ConsignmentLocationId Identity yes Consignment Customer Id
UnitId Identity yes Unit Id for default unit per product
Dividend Float no Unit Id for default unit per product
Divisor Float no Unit Id for default unit per product
LocationId Identity yes Warehouse location id
Replenished Integer no Is replenished
PrevMonthDespatches Float no Previous month's despatches
MaxCapacity Float no MaxCapacity
ShowMaxCapacityWarning Integer no Max Capacity Behaviour
SafetyStock Float no Safety Stock
SafetyStockPercentWarning Float no Safety stock percent warning
StockDate Date yes Stock Date
LastPeriodDate Date yes Last period Stock Date
InternalStock Float no Internal Stock from internal suppliers
ExternalStock Float no External Stock from external suppliers
Opening Float no Opening Stock Value
Closing Float no Closing Stock Value
DaysOfStock Float no Days Of Stock
Orders Float no Orders
AvailableCapacity Float no Available Capacity
FirmOrders Float no Firm Orders
Consumption Float no Consumption
StockStatus Integer yes Stock Status
QuarantineStock Float yes Daily Demand
OpeningToolTip HugeString yes Stock Status
WarningColor integer yes Warning Color
DailyDemand Float no Daily Demand
MonthlyDemand Float no Monthly Demand
DayOfStockCssClass String yes DayOfStock CssClass
GroupId Identity yes Group for subtotals
GroupProperties HugeString yes Group properties
IsSubTotal Integer no Group properties
Delisted HugeString yes Delisted sku and value of product which superseding thi SKU
IsOrdersEditable Integer no Id allow edit tentative orders
top
StockReservationData Replenishment
Temporary
A temporary table for Stock Reservation (ticket 51626)
name type identity null description
OperatorUserId Identity no Operator User ID (A reference to Users)
OrderNo Identity yes Order no
SkuKey String no SKU Code - SKU-CS-SW.
SkuID Identity no sku ID
MaterialID Identity no Material ID
WorkCentreID Identity no WorkCentre ID
LocationID Identity yes Location ID
StockDate Date no
StockValue Float yes
CompletedStock Float yes Weight completed orders and deliveries today
WarningColor String yes
LowestAvailableStock Float yes The lowest inventory level is the lowest available stock level between today and the end of the real in-ventory profile
LowestAvailableStockComment LongestString yes The lowest inventory level is the lowest available stock level between today and the end of the real in-ventory profile
top
STODatesData Due date quoting
Temporary table
The table contains information about STO despatch and delivery dates
name type identity null description
SiteId Identity no A reference to the site
DateFrom Date yes Date of end of FL-run (truncate)
OrderNo Identity no A reference to the routes of journey
DespatchDate Date no Despatch date from the source STO Warehouse
DeliveryDate Date no Delivery date to the destination STO Warehouse
top
StorageEntries Core
Language
The table stores various data
name type identity null description
Name LongestString no Dictionary key
Value LongestString no Dictionary value
StorageId Identity no A reference to table ID (used for localization)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Storages Core
Language
The table stores various data
name type identity null description
Id Identity yes no Identity
StorageType String no Dictionary key
Name String no Dictionary value
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SummaryHistories Core
Configuration
The table contains the list select columns (Summary levels) for grids
name type identity null description
TaskName String no Grid Id
Summary HugeString no Column name
Title LongestString yes Column name
IsLast Integer no Is last created
InsertDate Date no Is last created
InsertUserId Identity no Is last created
top
SupercessionConflictsData Forecasting
Temporary
Temporary table for showing conflicts in Supercession rules
name type identity null description
SupercessionRuleId Identity no Supercession Rule Id
CountProps Identity yes number of properties in this rule
OperatorUserId Identity no User Id
top
SupercessionRules Core
Core
The table stores the list of supercession rules
name type identity null description
Id Identity yes no Identity
TestCode String no Test code for reference
Type String no Supercession type: Supercession, Substitution, Both
StartDate Date no The date when the rule becomes effective
Percentage Float no Percentage
AutoCreateSku Integer no Create or not new sku's
DisableSupersededItems Integer no Switch off supercessed sku for forecasting
HierarchyLevels String yes
HierarchyCodes HugeString yes
Properties HugeString yes
FromPropertyCodes HugeString yes
ToPropertyCodes HugeString yes
FromCharacteristicId Identity yes
ToCharacteristicId Identity yes
FromLocationId Identity yes
ToLocationId Identity yes
FromMaterialId Identity yes
ToMaterialId Identity yes
FromEndCustomerId Identity yes
ToEndCustomerId Identity yes
FromEndUseId Identity yes
ToEndUseId Identity yes
DeleteOnNextRebuild Integer no Delete On Next Rebuild
RequiresRebuild Integer no Requires Rebuild
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SupplierInventories Replenishment
Replenishment
The table stores in-stock balances of warehouses from suppliers
name type identity null description
Id Identity yes no Identity
DateFrom Date no Date
SupplierId Identity no A reference to Suppliers
LocationId Identity no A reference to Location Warehouses
MaterialId Identity no A reference to Materials
SiteMaterialUsageId Identity no A reference to SiteMaterialUsages
Quantity Float no Opening weight
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Suppliers Core
Core
The table store stock suppliers
name type identity null description
Id Identity yes no Identity
SupplierName ShortString no Supplier name
SupplierCode ShortString no Supplier code
SupplierType ShortString no Supplier type: internal or external
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SystemParameterLogs Core
Logging
The table is used to store audit log for system parameters
name type identity null description
ParameterName String no System parameter name
OldValue LongString no Old value
NewValue LongString no New value
UserId Identity no Who inserted the record?
Stamp Date no When the record was inserted?
top
SystemParameters Core
Configuration
The table stores system parameter definitions
name type identity null description
Id Identity yes no Identity
ParameterName String no Parameter name
ParameterDescription LongString no Parameter description
ParameterHelp HugeString yes Parameter help
ParameterType String no Parameter type (Possible values: system, admin, user)
ParameterArea String no Parameter area (Possible values: admin, display, forecast, invisible, personal, reference, warnings)
DataType ShortString yes Parameter data type (Possible values: Boolean, Date, Enum, Number, String)
Value LongestString no Parameter value
MinValue ShortString yes Parameter min value
MaxValue ShortString yes Parameter max value
ReadOnly Integer no A flag: is the parameter read-only?
Cloud Integer no A flag: is it for cloud version?
Category LongString yes Parameter category. Used on parameter pages.
DependOn String yes Name of the parameter on which depends whether the specified parameter is enabled.
BundleId Identity yes Bundle id
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
SystemParameterValues Core
Configuration
The table stores system parameter values
name type identity null description
Id Identity yes no Identity
ParameterId Identity no Identity
Key String yes Key
Value String yes Parameter value
TableName String yes Source table
Condition String yes Condition
FieldKeyName String yes Key source field
FieldValueName String yes Value source field
OrderNo Integer no Ordinal number in the list of parameter values.
Description LongString no Description
top
TargetSystems Replenishment
Replenishment
The table stores in-stock balances of warehouses from suppliers
name type identity null description
TargetSystem String no Target system
ViewName String no View name used for selecting entities
Condition String yes Condition applied to view
EntityType String yes Reserved for future use
IsActive Integer no Is target system active
UseForRemoving Integer no Should be also use for removed entities
top
TaskResults Core
Reference
The table stores the result of process.
name type identity null description
Id Identity yes no Task ID
TaskId Identity yes Task ID
OrderNo Integer no Ordinal number of the part on the progress screen
Name String no Task result part name
Description LongString no Task result part description
IsForActiveTask Integer no Is active task
DataType String no Data type of value
top
Tasks Core - Processes
Reference
The table stores the list of process types, that can be started in I-Plan
name type identity null description
Id Identity yes no Identity
TaskName String no Task name
Executable String no Task name
Description String yes Task description
IsSystemTask Integer no A flag: is this a system task?
DaysToKeepLogs Identity no How many days should be stored logs?
IsActive Integer no A flag: is the column visible in the user report?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
TempConsignmentOrdersData Replenishment
Replenishment
name type identity null description
OperatorUserId Identity no Operator User ID (A reference to Users)
OrderLineId Identity yes Order line
OrderBookId String yes Line no
SkuId Identity yes Order line
MaterialId Identity no Order line
CustomerId Identity no Order line
MaterialRunId Identity no Order line
IsForecasted Integer no Order line
IsExisting Integer no Order line
IsEditable Integer no Order line
ForDelete Integer no Order line
Modified Integer no Order line
Weight Float no Order line
Quantity Float no Order line
Capacity Float no Order line
AvailableCapacity Float no Order line
TotalOrderWeight Float no Order line
FreeCapacity Float no Order line
LineNo String no Line no
top
TimeEfficiencySnapshots Master Planning
Master Planning
The table stores the time efficiency for workcentres
name type identity null description
ScenarioId Identity no ScenarioId
SnapshotUserId Identity no User ID (A reference to Users)
WorkcentreId Identity yes A reference to the Sites table
Effective Date no The date when the cost becomes active
RoughTimeEfficiency Float no Storing cost
OriginalTimeEfficiency Float no Storing cost
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
TransportationAllocationsData Master Planning
Temporary
A temporary table for Live allocation transportation View screen
name type identity null description
OperatorUserId Identity no User ID (reference to Users )
Id Identity no Group Id
SummaryFields HugeString yes Group fields
DateFrom Date no date
MinCapacity Float no
MaxCapacity Float no
Allocation Float no
Orders Float no
Revenue Float no
ProductionCost Float no ProductionCost
TransportCost Float no TransportCost
InventoryCost Float no InventoryCost
TotalCost Float no TotalCost
Margin Float no
Filtered Integer no
top
TransportMethods Replenishment
Replenishment
The table stores the list of possible transportation methods
name type identity null description
Id Identity yes no Identity
TransportMethodName String no Transport method name
TransportMethodCode String no Transport method code (external reference)
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
TransportRouteChains Replenishment
Replenishment
For each transport route, the table describes a set of points (locations) of the path,
name type identity null description
TransportPathId Identity no A reference to the TransportRoutePaths table
LevelNo Identity no Transport route chain level number
TimePeriod Integer yes Total transportation time from source to destination
LocationId Identity no A reference to the Locations table
top
TransportRoutePaths Replenishment
Replenishment
The table stores detailed description of transport routes
name type identity null description
Id Identity no Identity
FromLocationId Identity no Source location (FG warehouse site)
ToLocationId Identity no Destination location (external customer)
SiteId Identity no A reference to the Sites table
TimePeriod Identity no Total transportation time from source to destination
WarehouseTimePeriod Identity no Time of transportation to a warehouse (to a primary replenishment point)
WarehouseLocationId Identity yes Warehouse location ID (to a primary replenishment point)
MainRouteId Identity no Main route ID
LevelNo Integer no Transport route level number
top
TransportRoutes Replenishment
Replenishment
The table contains the list of transport routes (with their parameters - cost, delivery time, location, shedule) between two locations. It is used by replenishment subsystem of I-Plan.
name type identity null description
Id Identity yes no Identity
CalendarId Identity yes Calendar for the route
Cost DoubleFloat no Tranport route cost
TimePeriod Integer no Duration, days
Priority Integer no Priority of the transport route
TransportMethodId Identity no Reference to transport method
FromLocationId Identity no Source location
ToLocationId Identity no Destination location
ScheduleId Identity yes Schedule for the route
LoadingTime Integer no Number of days the goods must be available at starting point prior to dispatch
UnLoadingTime Integer no Number of days after transportation before goods available at destination Will not be used by interface from TIPS, 0 should be sent
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
TransportRouteSnapshots Master Planning
Master Planning
The table contains user snapshots of transport routes
name type identity null description
SnapshotUserId Identity no Snapshot user ID (A reference to Users)
ScenarioId Identity no Snapshot user ID (A reference to Users)
Id Identity yes no Identity
Cost DoubleFloat no Cost
TimePeriod Integer no timeperiod in days
FromSiteId Identity no Fom site ID (reference to site id)
ToSiteId Identity no Detail Id
TransportMethodId Identity no Detail Id
IsActive Integer no Detail Id
InsertUserId Identity no Who insert line?
InsertDate Date no When line is inserted?
UpdateUserId Identity yes Who update line?
UpdateDate Date yes When line is updated?
top
TransportTimeTable Replenishment
Replenishment
name type identity null description
FromLocationId Identity no
ToLocationId Identity no
JourneyId Identity no
Priority Integer no
DespatchDate Date no
DeliveryDate Date no
top
UnallocatedReasons Master Planning
name type identity null description
Id Identity yes no Id
ReasonCode String no
Name String no
Description String no
Message LongString no
Severity String no
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Units Core
Units
The table lists units of measure registered in the system
name type identity null description
Id Identity yes no Identity
UnitName ShortString no Unit name
UnitDescription String no Unit description
UnitTypeId Identity no Unit type (A reference to UnitTypes)
IsBaseUnit Integer no A flag: is this a base unit? (0, 1)
Dividend DoubleFloat no Dividend
Divisor DoubleFloat no Divisor
MaterialTypeId Identity yes A reference to MaterialTypes
DividendProductPart LongString yes A Reference to Unit Formula
DivisorProductPart LongString yes A Reference to Unit Formula
FromBaseUnit Integer no A flag: should we used material units for conversion and create such entries
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
UnitTypeConverts Core
Units
The table stores the list of mutually convertible unit types
name type identity null description
Id Identity yes no Identity
FromUnitTypeId Identity no Initial unit type ID
ToUnitTypeId Identity no Final unit type ID
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
UnitTypes Core
Units
The table stores the list of unit types
name type identity null description
Id Identity yes no Identity
UnitTypeName String no Unit type name (such as length, weight, quantity)
UnitTypeDesc String no Unit type description
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
UploadedConsignmentOrders Replenishment
Replenishment
name type identity null description
OperatorUserId Identity no Operator User ID (A reference to Users)
OrderNo Identity no Row number
WorkCentreCode String yes
BlockCode String yes
RunCode String yes
CustomerCode String yes
ProductCode String yes
Quantity Float yes
UnitName String yes
UnitId Identity yes
MaterialId Identity yes Order line
CustomerId Identity yes Order line
MaterialRunId Identity yes Order line
Weight Float yes Order line
RunCapacity Float no Order line
AvailableRunCapacity Float no Order line
TotalOrderWeight Float no Order line
FreeRunCapacity Float no Order line
top
UsageHistories Forecasting
Forecasting
The table stores usage history by SKUs
name type identity null description
Id Identity yes no identity
DateFrom Date no Date
Weight Float no Weight
AdjustedWeight Float yes Adjusted Weight
SiteMaterialUsageId Identity no SKU (A reference to SiteMaterialUsages)
WorkCentreId Identity yes Workcentre Id
Price Float yes Price
PriceQuantityUnitId Identity yes Weight unit or any convertible to weight
CurrencyId Identity yes Currency Identity
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
UsedOppQuantityData Due date quoting
Temporary table
The table stores temporary data for calculation of the initial quantity
name type identity null description
MaterialRunId Identity no A reference to the material run
Quantity Float no Used quantity, or used duration
IsOppBlock Identity no A flag: is this an opportunistic run? (0, 1)
top
UseOppRuns Due date quoting
Temporary table
The table is used for calculation of the quantity on opportunistic runs
name type identity null description
MaterialRunId Identity no A reference to the material run
Quantity Float no Found quantity
WCType ShortString no Workcentre type (FL or PM)
top
UserAudit Core
Configuration
The table stores the information about changes to User settings (password, MFA method etc)
name type identity null description
UserId Identity yes Affected User Id
UserName String yes Affected User Name (at the time of recording)
UserGroupId Identity yes Affected User Group Id
UserGroupName String yes Affected User Group Name (at the time of recording)
Description HugeString yes Change description
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
UserGroupFilters Core
Core
The table stores infomation about locations assignment to users
name type identity null description
UserGroupId Identity no Identity
ReportFilterid Identity no User ID
FilterType Integer no 0-inclusive, 1 - exclusive filter
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
UserGroupGroups Core
Core
The table stores infomation about locations assignment to users
name type identity null description
UserGroupId Identity no Identity
AccessGroupId Identity no User ID
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
UserGroupLocations Core
Core
The table stores infomation about locations assignment to users
name type identity null description
UserGroupId Identity no Identity
LocationId Identity no User ID
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
UserGroups Core
Core
The table stores infomation about locations assignment to users
name type identity null description
Id Identity yes no Identity
GroupName String no Group name
GroupType String no Group type
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
UserIPLogging Core
Logging
Users IP address log
name type identity null description
Id Identity yes no Identity
UserId Identity yes User ID
LoginTime Date no When the user logged in to the system
LogoutTime Date yes When the user logged off the system
IPAdress String no IP Address of the user
IPAdress2 String yes Second IP Address of the user
SessionKey String yes Session key
ExtraClientInfo LongestString yes Additional information about the client used
top
UserNavigations Core
Configuration
The table stores user configured navigation levels for summary and filters.
name type identity null description
Id Identity yes no Identity
TaskName String no Task Name (Page name)
LevelName String no Level Name
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
UserNotifications Core
Reference
The table connects notifications to users
name type identity null description
Id Identity yes no Identity
NotificationId Identity no Notification Id
UserId Identity no User Id
IsRead Integer no 0 if unread, 1 if read
DeliveryMethod String no Method of delivery, values: iplan, email, iplanandemail
IsSent Integer no Used for delivery methods email/iplanandemail, 0 if not sent yet (or not needed), 1 if sent
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
UserPageParameters Core
Configuration
The table contains the list of parameters and values, that were changed by users
name type identity null description
PageParameterId Identity no Parameter ID
UserId Identity no User ID
Value LongestString no Value of the parameter
IsSession Integer no 0 - default user settings for Page 1 - session user settings for Page
StorageName String yes Storage name
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
UserParameters Core
Configuration
The table contains the list of parameters and values, that were changed by users
name type identity null description
Id Identity yes no Identity
SystemParameterId Identity no Parameter ID
UserId Identity no User ID
Value LongString no Value of the parameter
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
UserPasswordsHistory Core
Logging
The table stores the list of recent passwords for each of the users. It serves to disable the use of the same passwords
name type identity null description
UserId Identity no User ID
Num Identity no Ordinal number
UserPassword String yes Password
InsertDate Date no The date when the line was inserted
top
Users Core
Configuration
The table contains the list of users of I-Plan
name type identity null description
Id Identity yes no Identity
UserLogin ShortString no Login name
DomainLogin ShortString yes Domain login name
UserName String no Full name
UserPassword String yes Password
Disabled Integer no A flag: is the user disabled?
Email LongString yes Email of the user
UserCode ShortString no External reference
CompanyId Identity yes Company ID that the user belongs to
UserGroupId Identity yes User group that the user belongs to
PasswordHistory Identity no Number of previous passwords to store
PasswordAge Identity no Maximal allowed password age, days. After this number of days passed since last password change, the user will be forced to change password again
PasswordUpdateTime Date yes The date when the password was changed last time
LockInvalidPasswordFlag Integer yes An internal column
LockInvalidPasswordTime Date yes An internal column
IsPasswordExpired Integer no Is password expired
MFARequired Integer no A flag: is MFA required for this user to login?
MFAMethod ShortString yes Multi-factor authentication method
MFAConfirmed Integer no A flag: is MFA method confirmed?
MFASecret LongString yes Multi-factor authentication method secret
MFASecretDate Date yes When the MFA secret was created?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
UserSessionParameters Core
Configuration
The table stores the list of parameters changed during sessions of each user
name type identity null description
Id Identity yes no Identity
UserId Identity no User ID
SystemParameterId Identity no Parameter
Value LongestString no Parameter value
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
UserSessions Core
Logging
The table stores additional information about user sessions
name type identity null description
Id Identity yes no Identity
FromAddress LongString yes User IP address
SessionKey LongString no Unique session key
StartedAt Date no Session start time
LatestActionAt Date no The moment of the latest action
UserId Identity yes User ID
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
top
UsersRoles Core
Access rights
The table is used to maintain the list of roles assigned to each of the users
name type identity null description
Id Identity yes no Identity
RoleId Identity no Role ID
UserId Identity no User ID
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
ValidSources Core
Core
The table stores source priority rules
name type identity null description
Id Identity yes no Identity
ProductionConfigurationId Identity no Weight of rule
OperationTypeId Identity no Weight of rule
WorkCentreId Identity no Weight of rule
Preferred Integer no Site
SourceRank String no Is primary source
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WarehouseConsumption Replenishment
Replenishment
The table stores in-stock balances of warehouses from suppliers
name type identity null description
WarehouseSkuId Identity no Warehouse Sku Id
ConsignmentLocationId Identity yes Consignment Location Id
DateFrom Date no Date
EditableWarehouseConsumption Identity no A reference to Suppliers
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WidgetGraphData Widgest
Temporary
Write description here.
name type identity null description
WidgetName String no
Key String no
Value1 Float yes
Value2 Float yes
OperatorUserId Identity no
top
WidgetParameters Core
Core
The table stores WidgetParameters defined in the system
name type identity null description
Id Identity yes no Identity
WidgetId Identity no Widget identity
Name String no Widget template parameter name
Value HugeString yes Value
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Widgets Core
Core
The table stores widgets defined in the system
name type identity null description
Id Identity yes no Identity
WidgetName String no Widget name
WidgetDescription String no widget description (title)
WidgetCategory LongString yes Widget category (functional area)
WidgetTemplateId Identity no Widget Template Id
IsEditable Integer no A flag: is the widget editable by user
UserId Identity no Widget owner Id
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WidgetTemplateParameters Core
Core
The table stores WidgetTemplateParameters defined in the system
name type identity null description
Id Identity yes no Identity
WidgetTemplateId Identity no Widget Template identity
Name String no Widget template parameter name
Description String no Widget template parameter description
Help HugeString yes Widget template parameter help (optional)
Value HugeString yes Value
ControlType String no Parameter visual control
IsMandatory Integer no Parameter visual control
Category String yes Parameter visual control
Options HugeString yes Additional options for different controls
BundleId Identity yes Bundle with values
OrderNo Integer no Sequence of UI control inside category
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WidgetTemplates Core
Core
The table stores WidgetTemplate defined in the system
name type identity null description
Id Identity yes no Identity
Name String no Widget template name
Description String no Widget template name
Category String no Widget template category
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WorkCentreAttributes Block Scheduling
Block Scheduling
The table contains PM run properties which should be present in FL run attributes (MaterialRunAttributes table) and which are not defined in PM run Properties (MaterialRunProperties table). They are defined per workcentre. Currently, only paper machine property are used.
name type identity null description
Id Identity yes no Unique identifier
WorkCentreId Identity no A reference to Workcentres.Id
PropertyId Identity no A reference to Properties.Id
PropertyValueCode ShortString no Property value code
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WorkcentreCampaignRunData Source Selection
Temporary table
The table used in source selection process for storing paper machine production periods for each paper machine. It is used for calculation of production cycles
name type identity null description
Id Identity no Identity
MaterialRunId Identity no A reference to MaterialRuns
StartDate Date no Start date of campaign run
FinishDate Date no End date of campaign run
Valid Identity no Valid
OperatorUserId Identity no Operator user ID
top
WorkCentreCapacities Core
Core
The table stores the list of capacities of workcentres
name type identity null description
Id Identity yes no Identity
WorkcentreId Identity no Workcentre ID
Capacity Float no Capacity
EffectiveDate Date yes Effective date
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WorkCentreChangeOvers Block Scheduling
Block Scheduling
The table contains detailed information about Workcentre changeovers. Changeover matrix, described by this table, contains all grades registered in the system, both in rows and columns, and specifies switchover time and cost necessary to switch between any two grades.
name type identity null description
Id Identity yes no Identity
WorkcentreId Identity no A reference to Workcentres.Id
DateFrom Date no Date
Time Float no Changeover time
Cost Float no Changeover cost
FromGradeId Identity yes Source grade ID
ToGradeId Identity yes Product grade ID
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WorkCentreParameters Core
Core
The table stores the list of parameters for workcentres
name type identity null description
Id Identity yes no Identity
WorkcentreId Identity no Workcentre ID
ParameterTypeId Identity no Parameter type
Value String yes Value
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WorkCentreParametersData Core
Temporary
Keeps the most used parameters of workcentres from the table WorkcentreParameters.
name type identity null description
SiteId Identity no Site Id
WorkCentreId Identity no Workcentre Id
MinWidth Float no MinWidth parameter Value
MaxWidth Float no MaxWidth parameter Value
MaxNumberOfSheetsOut Float no MaxNumberOfSheetsOut parameter Value
MinTrimLoss Float no MinTrimLoss parameter Value
MaxTrimLoss Float no MaxTrimLoss parameter Value
top
WorkCentreParameterSnapshots Master Planning
Master Planning
The table contains workcentre parameter snapshots for SNO
name type identity null description
SnapshotUserId Identity no User ID (A reference to Users)
ScenarioId Identity no Scenario ID (A refernce to Scenarios)
WorkCentreId Identity no Workcentre ID (A reference to Workcentres)
IdleCost Float no Idle time cost, base currency unit per hour (A reference to Workcentres)
ExcludeFromSA Float no Exclude from SA Scenarios ParameterType (A reference to WorkCentreParameters)
top
WorkCentreParameterTypes Core
Core
The table stores the list of all type of parameters for workcentres registered in I-Plan
name type identity null description
Id Identity yes no Identity
ParameterName String no Parameter name
ParameterDescription String no Parameter description
ParameterHelp HugeString yes Parameter help
DataType String no Type of data
UnitDescription String no Description of unit
MinValue Float yes Min value of data
MaxValue Float yes Max value of data
DefaultValue String no Default value of data
WorkcentreTypeId Identity no Workcentre type identity
ParameterGroup String no Column which will be indicate parameter group - possible values: Common, Master Planning, BSO
Undefined Integer no possible values 0 and 1, indicate that parameter can be undefined
BundleId Identity yes possible values 0 and 1, indicate that parameter can be undefined
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WorkcentreROData Block Scheduling
Temporary
The list of workcentres to be processed in RO per user.
name type identity null description
WorkcentreId Identity no Workcentre Id
OrdersQuantity Integer yes Quantity of orders passed to RO engine
GradesQuantity Integer yes Quantity of grades
ChangeOversQuantity Integer yes Quantity of changeovers
ShutsQuantity Integer yes Quantity of shuts per workcentre
OperatorUserId Identity no Who inserted the line?
top
WorkCentreROParameters Block Scheduling
Block Scheduling
The table stores global parameters for RO. The data should be passed to the Run Optimiser engine.
name type identity null description
WorkcentreId Identity no A Reference to Workcentres.Id
EarlyTolerance Float no Earliness Tolerance, hrs – non-negative floating-point numeric value, default value – 0. This value is used in template assignment logic, if the demand’s projected finish date is not before its due date minus the earliness tolerance – then the order has no earliness penalty
LateTolerance Float no Lateness Tolerance, hrs – non-negative floating-point numeric value, default value – 0. This value is used in template assignment logic, if the demand’s projected finish date is not after its due date plus the lateness tolerance – then the order has no lateness penalty
OrderLP Float no Order penalty of lateness
OrderFLP Float no Order fixed penalty of lateness
OrderEP Float no Order penalty of earliness
OrderFEP Float no Order fixed penalty of earliness
AllocationLP Float no Allocation penalty of lateness
AllocationFLP Float no Allocation fixed penalty of lateness
AllocationEP Float no Allocation penalty of earliness
AllocationFEP Float no Allocation fixed penalty of earliness
PropOrderLP Integer yes A flag: 1 - calculate order lateness costs proportionally to the run lentgth
PropOrderFLP Integer yes A flag: 1 - calculate order fixed lateness costs proportionally to the run lentgth
PropOrderEP Integer yes A flag: 1 - calculate order earliness costs proportionally to the run lentgth
PropOrderFEP Integer yes A flag: 1 - calculate order fixed earliness costs proportionally to the run lentgth
PropAllocationLP Integer yes A flag: 1 - calculate allocation lateness costs proportionally to the run lentgth
PropAllocationFLP Integer yes A flag: 1 - calculate allocation fixed lateness costs proportionally to the run lentgth
PropAllocationEP Integer yes A flag: 1 - calculate allocation earliness costs proportionally to the run lentgth
PropAllocationFEP Integer yes A flag: 1 - calculate allocation fixed earliness costs proportionally to the run lentgth
OpportunisticBlocks Identity yes Opportunistic blocks
GenericChangeoverCost Float no Generic changeover cost
GenericChangeoverDuration Float no Generic changeover duration
FrozenPeriodEnd Date yes Moment of the frozen period end
Saved Integer no A flag: 1 indicates that RO Results were saved (i.e. campaign saving should be disabled)
Released Integer no A flag: 1 indicates that RO results were released
AllowIdleTime Integer no A flag: 1 indicates that idle time between generated runs is allowed
AllowIdleTimeFS Integer no A flag: 1 indicates that idle time around generated floating shuts is allowed and for runs not used
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WorkCentreROResults Block Scheduling
Block Scheduling
The table stores results of the most recent run optomization. The table is populated after completion of the the RO process, and is used to display statistics of campaigns generated for corresponding workcentres.
name type identity null description
WorkcentreId Identity no Reference to Workcentres.Id
LatenessCost Float no Total lateness cost
EarlinessCost Float no Total earliness cost
SwitchoverCost Float no Total switchover sost
OpportunisticBlocks Identity yes Average duration of an opportunistic block
GeneratedDate Date yes Date and time when displayed results were generated
AllowIdleTime Integer no A flag: indicates that idle time was allowed when optimizing runs
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WorkCentres Core
Core
The table stores the list of all workcentres registered in I-Plan
name type identity null description
Id Identity yes no Identity
WorkCentreName String no Workcentre name
WorkCentreCode String no Workcentre code
WorkCentreTypeId Identity no A reference to WorkCentreTypes
LocationId Identity no A reference to Location (only supplier can contain workcentres)
FrozenPeriod Identity no Period in days from current date to set frozen status on runs, orders and operations before sending them to fine planning system
ReleasePeriod Identity no Period in days from current date for sending runs, orders and operations to fine planning system
FinePlanningRelease Date yes The date of the latest release to fine planning system
FinePlanningUpdate Date yes The date of the latest update from fine planning system
CampaignReleaseDate Date yes The date of the latest RO release on the workcentre
NewLiveAllocations Integer yes Flags that RO results were not released yet on the workcentre after latest MP calculation
DDQLocked Identity no 0 - workcentre is not locked for DDQ process; 1 - workcentre is locked for DDQ process
BSLocked Identity no 0 - BS process not locked workcentre; 1 -0 - BS process locked workcentre
ProcessId Identity yes BS process identity that locked site
AutoConfirmationPeriod Integer yes Replenishment orders auto-confirmation period
UserId Identity yes The ID of the user who have locked the workcentre
DefaultRate Float no Default Production rate, base weight unit/hour
NumberOfWorkcentres Integer no Number of physical workcentres
IdleCost Float no Idle time cost, base currency unit/hour
LineOfAuthority Date yes The date of the LineOfAuthority
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WorkCentreShuts Core
Core
The table stores infomation about shuts for workcentres
name type identity null description
Id Identity yes no Identity
WorkCentreId Identity no WorkCentre identity
ShutCode String no WorkCentre shut code
StartDate Date no Start date
FinishDate Date no Finish date
Description String yes Description
UseShutInMPOnly Integer no Use shut only in MP
UseOnlyInBSOGantt Integer no Use shut only In BSOGantt
WorkCentreShutTypeId Identity no WorkCentre shut type Identity
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WorkCentreShutSnapshots Master Planning
Master Planning
The table contains workcentre shut snapshots for SNO
name type identity null description
SnapshotUserId Identity no User ID (A reference to Users)
ScenarioId Identity no Scenario ID (A refernce to Scenarios)
Id Identity yes no Identity
ShutCode String no WorkCentre shut code
WorkcentreId Identity no Workcentre ID (A reference to Workcentres)
StartDate Date no Start date and time of the snapshot
FinishDate Date no End date and time of the snapshot
Description String yes User description of the shut
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WorkCentreShutTypes Core
Core
The table stores infomation about type shuts for workcentres
name type identity null description
Id Identity yes no Identity
Name String no Shut type name
Description String yes Shut type description
IsDefault Integer no A flag: is this a default action?
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WorkCentreTimeEfficiencies Core
Core
The table stores the time efficiency for workcentres
name type identity null description
Id Identity yes no Identity
WorkcentreId Identity no Workcentre ID
RoughTimeEfficiency Float no Capacity
EffectiveDate Date yes Effective date
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
WorkCentreTypes Core
Core
The table stores the list of workcentre types
name type identity null description
Id Identity yes no Identity
WorkCentreTypeName String no Workcentre type name
WorkCentreTypeDesc String no Description of the workcentre type
IsValidInitialSource Integer no A flag: is this a valid initial source workcentre type?
HasInventory Integer no A flag: is this warehouse
IsProductionSource Integer no A flag: is this a valid initial source workcentre type?
IsExternalSource Integer no A flag: is this a external source workcentre type?
StageDelayHours Integer no Fixed (min) delay after this stage in SNP, in hours
MaxStageDelayHours Integer no Max delay after this stage in SNP, in hours
OrderNo Integer no Order number for sequencing by wkcType on screens
BSOptimisation Integer no Such workcentre type can be optimized in BSO
BSONextCampaign Integer no Should generate runs for next workcentre type in the production chain
InsertUserId Identity no Who inserted the record?
InsertDate Date no When the record was inserted?
UpdateUserId Identity yes Who updated the record?
UpdateDate Date yes When the record was updated?
top
Views
ActiveProcessStatusesView

SELECT ps.TaskName, ps.ProcessPartName AS ProcessPartDesc,
       ps.Done,
       ps.Total,
       DECODE(ps.Total, 0, 0, ROUND(ps.Done / ps.Total * 100, 0)) AS Percentage,
       ps.UserId,
       u.UserLogin,
       ps.OrderNo
  FROM ProcessStatuses ps, Users u, Processes p
 WHERE ps.UserId = u.Id
   AND ps.TaskName = p.ProcessType
   AND p.Status = 0
   AND p.UserId = ps.UserId

top
AlternateMaterialsIplanView
SELECT smu.Id, l.LocationCode, m.MaterialCode ProductCode,
smu.LocationId, smu.MaterialId, NULL ConsignmentLocationId,
COALESCE(lam.MaterialName, am.MaterialName) ExistingAlternateName,
COALESCE(lam.MaterialName, am.MaterialName, m.MaterialName) MaterialName,
'Normal sku (customer and free stock)' Annotation
FROM SiteMaterialUsages smu
JOIN Materials m ON (m.Id = smu.MaterialId)
JOIN Locations l ON (l.Id = smu.LocationId)
LEFT JOIN AlternateMaterials am ON (smu.MaterialId = am.MaterialId AND am.LocationId IS NULL)
LEFT JOIN AlternateMaterials lam ON (smu.MaterialId = lam.MaterialId AND lam.LocationId = smu.LocationId)
UNION ALL
SELECT t.ID, LocationCode, ProductCode,
t.Locationid, t.MaterialId, ConsignmentLocationId,
COALESCE(lam.MaterialName, am.MaterialName) ExistingAlternateName,
COALESCE(lam.MaterialName, am.MaterialName, t.MaterialName) MaterialName,
'Consignment Sku' Annotation
FROM
(
SELECT smu.Id, l.LocationCode, m.MaterialCode ProductCode,
cm.MaterialName,
smu.LocationId, smu.MaterialId, cp.CustomerId ConsignmentLocationId,
cp.SiteMaterialUsageId, cp.CustomerId, cm.Id CustomerMaterialId,
cl.LocationCode CustomerCode, cm.MaterialCode CustomerProductCode,
ROW_NUMBER() OVER (PARTITION BY cp.SiteMaterialUsageId, cp.CustomerId ORDER BY csmu.Status DESC) r
FROM Consignmentparameters cp
JOIN SiteMaterialUsages smu ON (smu.Id = cp.SiteMaterialUsageID)
JOIN Materials m ON (m.Id = smu.MaterialId)
JOIN Locations l ON (l.Id = smu.LocationId)
JOIN Materials cm ON (NVL(cm.SourceMaterialId, cm.Id) = smu.MaterialId)
JOIN Locations cl ON (cp.Customerid = cl.Id)
JOIN SiteMaterialUsages csmu ON (csmu.LocationId = cp.CustomerId AND csmu.MaterialId = cm.Id)
) t
LEFT JOIN AlternateMaterials am ON (am.MaterialId = t.CustomerMaterialId AND am.LocationId IS NULL)
LEFT JOIN AlternateMaterials lam ON (t.CustomerMaterialId = lam.MaterialId AND lam.LocationId = t.ConsignmentLocationId)
WHERE  t.R = 1

top
AvailableWidgetsIPlanView
-- Own user widgets (for UserId=1 categorized as System)
SELECT 0 IsTemplate, w.Id, w.WidgetName Name,
    w.WidgetDescription Description, 
    DECODE(w.UserId, 1, 'system-widgets', 'my-widgets') CATEGORY,
    wt.Name TemplateName, w.IsEditable, wt.id AS WidgetTemplateId, w.UserId,
    0 IsShared
  FROM Widgets w, WidgetTemplates wt
    WHERE wt.Id = w.WidgetTemplateId
UNION
-- UserId = 1: "System" Widgets (match role, various categories, non-editable)
-- UserId != 1: Shared widgets (match role, category 'Shared Widgets', editable)
  SELECT DISTINCT 0 IsTemplate, w.Id, w.WidgetName Name,
    w.WidgetDescription Description, 
    DECODE(w.UserId, 1, 'system-widgets', 'shared-widgets') Category, -- ignore category for pre-created ones
    wt.Name TemplateName, w.IsEditable, wt.id AS WidgetTemplateId, ur.UserId,
    DECODE(w.UserId, 1, 0, 1) IsShared
  FROM Widgets w, UsersRoles ur, RolesWidgets rw, WidgetTemplates wt
  WHERE wt.Id = w.WidgetTemplateId
    AND ur.RoleId = rw.RoleId
    AND rw.WidgetId = w.Id
UNION
-- Widget Templates
  SELECT 1 IsTemplate,  0 Id, wt.Name, wt.Description WidgetDescription, wt.Category,
       wt.Name TemplateName, 1 AS IsEditable, wt.Id AS WidgetTemplateId, 0 UserId, 0 IsShared
  FROM   WidgetTemplates wt
  WHERE  EXISTS (SELECT 1
        FROM   WidgetTemplateParameters p
        WHERE  p.WidgetTemplateId = wt.Id
        AND    p.controltype != 'Hidden')
top
AverageGradePricesIPlanView
SELECT ep.DateFrom,
NVL(LEAD(ep.DateFrom, 1) over( PARTITION BY GradeId order by DateFrom), to_date('01-01-2050', 'DD-MM-YYYY')) - 1 DateTo,
gm.GradeId, gm.Gradecode, Avg(Price) Price
FROM IH#ExpandedPrices ep, GradeMaterials gm, SiteMaterialUsages smu
WHERE smu.MaterialId = gm.MaterialId
AND ep.SiteMaterialUsageId = smu.Id
GROUP BY ep.DateFrom, gm.GradeId, gm.Gradecode
top
CurrenciesIPlanView

SELECT c.Id, c.CurrencyName, t.CurrencyDescription, c.Isinternal, LanguageId
  FROM Currencies c
  LEFT JOIN IT#Currencies t ON t.CurrencyId = c.Id

top
CustomerRanksIPlanView

SELECT cr.Id, cr.CustomerRankName, t.CustomerRankDesc, cr.Priority, LanguageId
  FROM CustomerRanks cr
  LEFT JOIN IT#CustomerRanks t ON t.CustomerRankId = cr.Id
 ORDER BY cr.Priority
top
DataSourcesIPlanView
SELECT ds.Name DataSourceName, ds.DEscription DataSourceDescription, ds.Query, DF.*
FROM DataSources ds, DataSourcefields DF
WHERE ds.Id = df.DataSourceId
top
DemandBalanceIPlanView
      SELECT pm.WorkcentreName, pr.GradeId, SourceMonth,
             (Customer) / pr.Rate * 60 AllocationDuration,
             (Revised) / pr.Rate * 60 RevisedAllocationDuration
      FROM   AllocationBodies ab, GradeProductionRates pr, SiteMaterialUsages smu, GradeMaterials gm,
             IH#WorkCentres pm
      WHERE  ab.SiteMaterialUsageId = smu.Id
      AND    Customer != Revised
      AND    gm.MaterialId = smu.MaterialId
      AND    gm.Gradeid = pr.GradeId
      AND    pr.WorkcentreId = ab.WorkcentreId
      AND    ab.WorkcentreId = pm.WorkcentreId
top
EndCustomerLevelsIPlanView

SELECT Id, 
       'EndCustomer'||HierarchyLevelName AS HierarchyLevelName,
       'EndCustomer '||REGEXP_REPLACE(HierarchyLevelName, '[^[:alnum:]_]', '') AS HierarchyName,
       UPPER('H_EH_' || REGEXP_REPLACE(HierarchyLevelName, '[^[:alnum:]_]', '')) AS HierarchyViewName,
       UPPER('H_EH_' || REGEXP_REPLACE(HierarchyLevelName, '[^[:alnum:]_]', '') || 'CODE') AS HierarchyViewCode,
       'End Customer '||HierarchyLevelName as HierarchyDesc,
       'EndCustomerHierarchyCode' || ROW_NUMBER() Over(ORDER BY Id) FieldHierarchyCode,
       'EndCustomerHierarchyName' || ROW_NUMBER() Over(ORDER BY Id) FieldHierarchyValue,
       ROW_NUMBER() Over(ORDER BY Id) OrderNo,
       HierarchyLevelNo
  FROM HierarchyLevels

top
EndUsePropertiesIPlanView
SELECT Id,
       REGEXP_REPLACE(PropertyName, '[^[:alnum:]_]', '') AS PropertyName,
       PropertyName AS PropertyDesc,
       UPPER('EU_' || REGEXP_REPLACE(PropertyName, '[^[:alnum:]_]', '')) PropertyViewName,
       'Property' || ROW_NUMBER() Over(ORDER BY Id) FieldProperty,
       HierarchyLevelNo OrderNo
  FROM EndUseProperties
top
EV#AllocationBodies
SELECT smu.LocationName, smu.LocationCode, smu.MAterialName, smu.MaterialCode,
wc.WorkcentreName, wc.WorkcentreCode, wc.SiteName, wc.SiteCode,
ab.SourceWeek, ab.SourceMonth, ab.DeliveryWeek, ab.DeliveryMonth,
ab.System, ab.Customer, smu.id as SiteMaterialUsageId, wc.WorkcentreId, wc.SiteId
FROM AllocationBodies ab
JOIN EV#Sitematerialusages smu
ON smu.Id = ab.SiteMaterialUSageId
JOIN IH#Workcentres wc
ON wc.WorkcentreId = ab.WorkcentreId

top
EV#AllSiteMaterialUSages
SELECT smu.Id, NULL ConsignmentLocationId, l.LocationName, l.LocationCode, MaterialName, MaterialCode,
eu.endusecode, eu.EndUseDescription, ec.Locationcode EndCustomerCode,
ec.LocationName EndCustomerName, NULL ConsignmentCustomerName, NULL ConsignmentCustomerCode,
Replenished, smu.Status, ReplenishmentFlag,
smu.MaterialId, smu.LocationId
FROM   SiteMaterialUsages smu
JOIN   Locations l
ON     (smu.LocationId = l.Id)
JOIN   Materials m
ON     smu.MaterialId = m.Id
LEFT JOIN EndUses eu
ON eu.Id = smu.EndUseId
LEFT JOIN Locations ec
ON ec.Id = smu.EndCustomerId
union ALL
SELECT smu.Id, cp.CustomerId ConsignmentLocationId, l.LocationName, l.LocationCode, MaterialName, MaterialCode,
NULL endusecode, NULL EndUseDescription, NULL EndCustomerCode,
NULL EndCustomerName, cc.LocationName ConsignmentCustomerName, cc.LocationCode ConsignmentCustomerCode,
cp.Replenished, 0 Status, 0 ReplenishmentFlag,
smu.MaterialId, smu.LocationId
FROM   SiteMaterialUsages smu
JOIN ConsignmentParameters cp
ON cp.SiteMaterialUsageId = smu.Id
JOIN   Locations l
ON     (smu.LocationId = l.Id)
JOIN   Materials m
ON     smu.MaterialId = m.Id
JOIN Locations cc
ON cc.Id = cp.CustomerId
top
EV#ArchivedForecastBodies

SELECT afb.SiteMaterialUSageId, f.StartDate, LocationName, LocationCode, MaterialName, MaterialCode, EndUseCode,
       EndUseDescription, EndCustomerCode, EndCustomerName, DateFrom, OriginalSystem, System, Customer, FINAL,
       EditGroupId, EditGroupFinalId
FROM   ArchivedForecastBodies afb
JOIN   EV#SiteMaterialUSages smu
ON     smu.Id = afb.SiteMaterialUsageID
JOIN   Forecasts f
ON     afb.ForecastId = f.Id
top
EV#BSOInput
WITH s AS (
SELECT u.UserName, WorkcentreCode, ab.DateFrom SourcePeriod, gp.Gradecode, OriginalWeight DemandControlWeight,
OperatorUserId, WorkcentreId, ab.GradeId, ab.OperationTypeId, ab.Finishingid
FROM BSOAllocationData ab
JOIN GradeProperties gp ON ab.GradeId = gp.GradeId AND ab.OperationTypeId = gp.Operationtypeid
JOIN USERS u ON ab.OperatorUserId = u.Id
JOIN Workcentres wc ON wc.Id = ab.WorkcentreId
),
i AS (

SELECT WorkcentreCode, TRUNC(DateFrom, p.AllocationPeriod) SourcePeriod, gp.Gradecode, SUM(Weight) InputWeight,
WorkcentreId, ab.GradeId, ab.OperationTypeId, ab.FinishingId
FROM Bsoinputdata ab
JOIN GradeProperties gp ON ab.GradeId = gp.GradeId AND gp.Operationtypeid = ab.Operationtypeid
JOIN Workcentres wc ON wc.Id = ab.WorkcentreId
CROSS JOIN (SELECt CASE WHEN VALUE IN ('Week', 'WeekMonth') THEN 'IW' ELSE 'month' END AllocationPeriod FROM SystemParameters WHERE ParameterName = 'LiveAllocationPeriod') p
GROUP BY WorkcentreCode, TRUNC(DateFrom, p.AllocationPeriod), gp.Gradecode, ab.WorkcentreId, ab.GradeId, ab.OperationTypeId, ab.FinishingId
)
SELECT s.UserName, s.SourcePeriod, s.WorkcentreCode, s.GradeCode, ot.OperationTypeName, s.FinishingId, s.GradeId, s.DemandControlWeight, InputWeight FROM s
LEFT JOIN i ON
s.GradeId = i.GradeId
AND s.WorkcentreId = i.WorkcentreId
AND s.SourcePeriod = i.SourcePeriod
AND s.OperationTypeId = i.OperationTypeId
AND NVL(s.FinishingId,0) = NVL(i.FinishingId,0)
JOIN OperationTypes ot ON ot.Id = s.OperationTypeId
top
EV#CarriedForecast
SELECT fb.SiteMaterialUSageId, LocationName, LocationCode, MaterialName, MaterialCode,
EndUseCode, EndUseDescription, EndCustomerCode, EndCustomerName,
DateFrom,
GroupId, EditGroupId, EditGroupFinalId,
RealFinal, Final, RealFinalSum, FinalSum, CurrentSum, System, Quantity
FROM MovingForecastGroupData fb
JOIN EV#SiteMaterialUSages smu ON smu.Id = fb.SiteMaterialUsageID
top
EV#CarriedForecastNoSuper
SELECT *
FROM   EV#CarriedForecast fb
WHERE  NOT EXISTS
(SELECT 1
FROM   MovingForecastGroupData md
JOIN   IH#MaterialSupercessions ms
ON     (ms.OnSiteMaterialUsageId = md.SiteMaterialUsageId OR ms.SiteMaterialUsageId = md.SiteMaterialUsageId)
WHERE  NVL(fb.EditGroupId,0) = NVL(md.EditGroupId,0)
AND    NVL(fb.EditGroupFinalId,0) = NVL(md.EditGroupFinalId,0)
)
top
EV#ConsignmentSku
SELECT v.LocationName, v.LocationCode, v.MAterialName, v.MaterialCode, l.LocationName CustomerName, l.LocationCode CustomerCode
FROM Consignmentparameters cp
JOIN  EV#SITEMATERIALUSAGES v ON v.Id = cp.SiteMaterialUSageID
JOIN Locations l ON l.Id = cp.CustomerId
top
EV#CustomerReplenishedDemand
SELECT a.SiteMaterialUsageId, s.LocationCode, s.MaterialCode, s.LocationName, s.MaterialName, EndUseCode, EndCustomer,
Demand, Forecast, Orders, Consumption, NettedOrders,
DateFrom
FROM ReplenishedCustomerDemands a
JOIN IH#sku s
ON s.Id = a.Sitematerialusageid
WHERE EXISTS (SELECT 1 from ReplenishedCustomerSku rs WHERE rs.SiteMaterialUsageId = a.SiteMaterialUsageId)
top
EV#DailyForecastDistribution
SELECT smu.*, d.*
FROM IH#DailyForecastDistribution d
JOIN EV#SiteMaterialUsages smu
ON smu.Id = d.SiteMaterialUsageId
top
EV#ExpandedPrices
SELECT
LocationName, LocationCode, MaterialName, MaterialCode,
EndUseCode, EndUseDescription, EndCustomerCode, EndCustomerName,
DateFrom, DateTo, CurrencyId, Price, CurrencyName
FROM IH#ExpandedPrices p
JOIN EV#SiteMaterialUsages smu
ON smu.Id = p.SiteMaterialUsageId
JOIN Currencies c
ON c.Id = p.CurrencyId

top
EV#FixedSourceSnapshots
      select d.Description, wc.WorkcentreName, s.ScenarioName, s.UserName,
        fs.* from FixedSourceSnapshots fs
        JOIN IH#HierarchyPropertyDetails d
        ON d.ID = fs.DetailId
        JOIN Workcentres wc
        ON wc.Id = fs.WorkcentreId
        JOIN IH#Scenarios s
       ON s.USerId = fs.SnapshotUserId
       AND s.Id = fs.ScenarioId
top
EV#ForecastBodies
SELECT fb.SiteMaterialUSageId, LocationName, LocationCode, MaterialName, MaterialCode,
EndUseCode, EndUseDescription, EndCustomerCode, EndCustomerName,
DateFrom, OriginalSystem, System, Customer, FINAL, ForecastStatusId,
EditGroupId, EditGroupFinalId, OriginalEditGroupId, IsWorking, SystemPrice, ForecastedPrice
FROM ForecastBodies fb
JOIN EV#SiteMaterialUSages smu ON smu.Id = fb.SiteMaterialUsageID
WHERE fb.ForecastId = forecasting.getLatestForecast()
top
EV#ForecastBodiesNoSuper
SELECT *
FROM EV#ForecastBodies fb
WHERE NOT EXISTS(SELECT 1 from IH#MaterialSupercessions ms
where ms.OnSiteMaterialUsageId = fb.SiteMaterialUsageId
OR ms.SiteMaterialUsageId = fb.SiteMaterialUsageId)
top
EV#ForecastHistory
SELECT smu.Id SiteMaterialUsageId, LocationName, LocationCode, MaterialName, MaterialCode,
EndUseCode, EndUseDescription, EndCustomerCode, EndCustomerName,
DateFrom,
History1, History2, History3, History4, History5, History6, History7,
SupercessionHistory1, SupercessionHistory2, SupercessionHistory3, SupercessionHistory4, SupercessionHistory5, SupercessionHistory6, SupercessionHistory7
FROM ForecastHistoryData fh
JOIN EV#SiteMaterialUSages smu ON smu.Id = fh.SiteMaterialUsageID
top
EV#ForecastHistoryNoSuper
SELECT *
FROM EV#ForecastHistory uh
WHERE NOT EXISTS(SELECT 1 from IH#MaterialSupercessions ms
where ms.OnSiteMaterialUsageId = uh.SiteMaterialUsageId
OR ms.SiteMaterialUsageId = uh.SiteMaterialUsageId)
top
EV#ForecastUsedHistory
SELECT smu.Id SiteMaterialUsageId, LocationName, LocationCode, MaterialName, MaterialCode,
EndUseCode, EndUseDescription, EndCustomerCode, EndCustomerName,
DateFrom, StartDate, Successed, Weight, Weight Quantity, TradingDays
FROM HistoryData fh
JOIN EV#SiteMaterialUSages smu ON smu.Id = fh.SiteMaterialUsageID
top
EV#ForecastUsedHistoryNoSuper
SELECT *
FROM EV#ForecastUsedHistory uh
WHERE NOT EXISTS(SELECT 1 from IH#MaterialSupercessions ms
where ms.OnSiteMaterialUsageId = uh.SiteMaterialUsageId
OR ms.SiteMaterialUsageId = uh.SiteMaterialUsageId)
top
EV#InnerPointForecast
SELECT s.LocationCode, s.MaterialCode, s.LocationName, s.MaterialName, EndUseCode, EndCustomer, a.*
FROM InnerpointForecast a
JOIN (SELECT DISTINCT GroupKey,MaterialId, SiteMaterialUSageId FROM ReplenishedSku) r ON r.GroupKey = a.GroupKey
AND r.MaterialId = a.MaterialId
JOIN IH#sku s
ON s.Id = r.Sitematerialusageid
ORDER BY 1,2,DateFrom
top
EV#InnerPointHistory
SELECT s.LocationCode, s.MaterialCode, s.LocationName, s.MaterialName, EndUseCode, EndCustomer, a.*
FROM Innerpointhistory a
JOIN (SELECT DISTINCT GroupKey,MaterialId, SiteMaterialUSageId FROM ReplenishedSku) r ON r.GroupKey = a.GroupKey
AND r.MaterialId = a.MaterialId
JOIN IH#sku s
ON s.Id = r.Sitematerialusageid
ORDER BY 1,2,DateFrom
top
EV#Inventories
SELECT smu.*, i.StockType, i.Weight, i.DateFrom, i.InsertDate, i.UpdateDate
FROM Inventories i
JOIN EV#AllSiteMaterialUsages smu ON smu.Id = i.Sitematerialusageid
AND NVL(smu.ConsignmentLocationId,0) = NVL(i.ConsignmentLocationId,0)
top
EV#InventoryProfiles
SELECT s.LocationCode, s.MaterialCode, s.LocationName, s.MaterialName,
cs.LocationName ConsignmentCustomerName, cs.LocationCode ConsignmentCustomerCode,
WorkcentreCode, WorkcentreName, SiteName, SiteCode,
ip.*
FROM InventoryProfiles ip
JOIN IH#sku s
ON s.Id = ip.Sitematerialusageid
LEFT JOIN Locations cs
on cs.Id = ip.ConsignmentLocationId
JOIN IH#Workcentres wc
ON wc.LocationId = s.LocationId
top
EV#InventorySnapshots
SELECT smu.*,
ScenarioName, UserName,
i.DateFrom, Weekt, PropertyValueId,
InitialInventory, AvailableInventory, InventoryAfterOrders,
InventoryDeficit, DEMAND, Allocation, SafetyStock,
OriginalSafetyStock
FROM Inventorysnapshots i
JOIN IH#Scenarios s
ON s.USerId = i.SnapshotUserId
AND s.Id = i.ScenarioId
JOIN EV#AllSiteMaterialUsages smu ON smu.Id = i.Sitematerialusageid
AND NVL(smu.ConsignmentLocationId,0) = NVL(i.ConsignmentLocationId,0)
top
EV#MaterialProperties
SELECT MaterialId, MaterialName, MaterialCode,
core.asCsv(ParameterArray(Code1,Code2,Code3,Code4,Code5,Code6,Code7,Code8,Code9,Code10,
Code11,Code12,Code13,Code14,Code15,Code16,Code17,Code18,Code19,Code20,
Code21,Code22,Code23,Code24,Code25,Code26,Code27,Code28,Code29,Code30)) MaterialCodes,
core.asCsv(ParameterArray(Value1,Value2,Value3,Value4,Value5,Value6,Value7,Value8,Value9,Value10,
Value11,Value12,Value13,Value14,Value15,Value16,Value17,Value18,Value19,Value20,
Value21,Value22,Value23,Value24,Value25,Value26,Value27,Value28,Value29,Value30)) MaterialNames
FROM Materialpropsspec
top
EV#MaterialRuns
SELECT SiteName, SiteCode, WorkcentreName, WorkcentreCode, BlockRunCode, mr.Quantity Capacity,
       StartDate, FinishDate, mrp.ProductName RunProperties,
       mr.Id MaterialRunId
FROM MaterialRuns mr
JOIN IH#workcentres wc ON wc.WorkcentreId = mr.WorkcentreId
JOIN MaterialRunProducts mrp ON mrp.MaterialRunId = mr.Id
WHERE TRUNC(Finishdate) >= TRUNC(core.Getinternaldate)
top
EV#MaterialSupercessions
    SELECT ms.*,
    euf.LocationId,
    l.LocationName,
    l.LocationCode,
    fm.MaterialName FromMaterialName,
    fm.MaterialCode FromMaterialCode,
    tm.MaterialName ToMaterialName,
    tm.MaterialCode ToMaterialCode,
    fm.Id FromMaterialId,
    tm.Id ToMaterialId,
    sr.Frompropertycodes,
    sr.ToPropertyCodes,
    sr.Properties,
    sr.Hierarchylevels,
    sr.HierarchyCodes,
    core.asCsv(ParameterArray(fmc.Code1,fmc.Code2,fmc.Code3,fmc.Code4,fmc.Code5,fmc.Code6,fmc.Code7,fmc.Code8,fmc.Code9,fmc.Code10,
    fmc.Code11,fmc.Code12,fmc.Code13,fmc.Code14,fmc.Code15,fmc.Code16,fmc.Code17,fmc.Code18,fmc.Code19,fmc.Code20,
    fmc.Code21,fmc.Code22,fmc.Code23,fmc.Code24,fmc.Code25,fmc.Code26,fmc.Code27,fmc.Code28,fmc.Code29,fmc.Code30)) FromMaterialProperties,
    core.asCsv(ParameterArray(tmc.Code1,tmc.Code2,tmc.Code3,tmc.Code4,tmc.Code5,tmc.Code6,tmc.Code7,tmc.Code8,tmc.Code9,tmc.Code10,
    tmc.Code11,tmc.Code12,tmc.Code13,tmc.Code14,tmc.Code15,tmc.Code16,tmc.Code17,tmc.Code18,tmc.Code19,tmc.Code20,
    tmc.Code21,tmc.Code22,tmc.Code23,tmc.Code24,tmc.Code25,tmc.Code26,tmc.Code27,tmc.Code28,tmc.Code29,tmc.Code30)) ToMaterialProperties
    FROM MaterialSupercessions ms
    JOIN SiteMaterialUsages euf ON (ms.SiteMaterialUsageId = euf.Id)
    JOIN SiteMaterialUsages eut ON (ms.OnSiteMaterialUsageId = eut.Id)
    JOIN Locations l on l.Id = euf.LocationId
    JOIN Materials fm ON (fm.Id = euf.MaterialId)
    JOIN Materials tm ON (tm.Id = eut.MaterialId)
    JOIN MaterialPropsSpec fmc ON (fm.Id = fmc.MaterialId)
    JOIN MaterialPropsSpec tmc ON (tm.Id = tmc.MaterialId)
    LEFT JOIN SupercessionRules sr ON (sr.Id = ms.SupercessionRuleId)
top
EV#MaterialUnits
  SELECT m.MaterialCode, m.MaterialName, UnitName, UnitDescription, mu.*
    FROM IH#AllMaterialUnits mu
  JOIN Materials m
  ON m.Id = mu.MaterialId
  JOIN Units u
  ON u.Id = mu.UnitId
top
EV#OrderLines

SELECT ob.Ordercode, ol.Linenocode,
dsmu.LocationName DestinationLocationName,
dsmu.LocationCode DestinationLocationCode,
dsmu.MaterialName DestinationMaterialName,
dsmu.MaterialCode DestinationMaterialCode,
wc.LocationName SourceLocationName,
wc.LocationCode SourceLocationCode,
ssmu.MaterialName SourceMaterialName,
ssmu.MaterialCode SourceMaterialCode,
wc.WorkcentreName,
wc.WorkcentreCode,
ols.OrderLineStatusCode,
ols.OrderLineStatusName,
DespatchDate, ConsumptionDate, DeliveryDate, RequestedDate,
mr.BlockRunCode,
mr.Finishdate RunFinishDate,
FinalWeight
FROM OrderLines ol
JOIN OrderBooks ob ON ob.Id = ol.OrderBookId
JOIN OrderLineStatuses ols ON ols.Id = ol.ORderLineStatusID
JOIN EV#SiteMaterialUsages dsmu ON dsmu.Id = ol.SiteMaterialUsageId
JOIN IH#Workcentres wc ON wc.WorkcentreId = ol.WorkcentreId
LEFT JOIN EV#SiteMaterialUsages ssmu ON ssmu.Id = ol.SourceSiteMaterialUsageId
LEFT JOIN OrderOperations oo ON oo.OrderLineId = ol.Id
LEFT JOIN MaterialRuns mr ON mr.Id = oo.MaterialRunId
top
EV#RealInventoryProfiles
SELECT s.MaterialId, s.LocationCode, s.MaterialCode, s.LocationName, s.MaterialName,
cs.LocationName ConsignmentCustomerName, cs.LocationCode ConsignmentCustomerCode,
WorkcentreCode, WorkcentreName, SiteName, SiteCode,
ip.*
FROM RealInventoryProfiles ip
JOIN IH#sku s
ON s.Id = ip.Sitematerialusageid
LEFT JOIN Locations cs
on cs.Id = ip.ConsignmentLocationId
JOIN IH#Workcentres wc
ON wc.LocationId = s.LocationId
top
EV#ReplenishedSubstitutedSku
SELECT f.LocationName FromLocationName, f.LocationCode FromLocationCode, t.LocationName ToLocationName,
t.LocationCode ToLocationCode, f.MaterialName FromMaterialName, f.MaterialCode FromMaterialCode,
t.MaterialName ToMaterialName, t.MaterialCode ToMaterialCode, rs.*
FROM   Replenishedsubstitutedsku rs
JOIN   EV#SiteMaterialUsages f
ON     f.id = rs.SiteMaterialUsageId
JOIN   EV#SiteMaterialUsages t
ON     t.id = rs.OnSiteMaterialUsageId

top
EV#RequestedInventoryProfiles
SELECT ip.SiteMaterialUSageId, ip.ConsignmentLocationId, DateFrom DateFrom,
ip.Opening,

DECODE((SELECT VALUE FROM SYSTEMPARAMETERS WHERE ParameterName = 'RPClosingCalcMethod'), 'DeliveryDate', PlannedInventory,
First_value(Opening) OVER(PARTITION BY ip.SiteMaterialUSageId, ip.ConsignmentLocationId ORDER BY ip.DateFrom)
+ SUM(TentativeOrdersIn + FirmOrdersIn) OVER(PARTITION BY ip.SiteMaterialUSageId, ip.ConsignmentLocationId ORDER BY ip.DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
- (TentativeORdersIn + FirmOrdersIn)
- SUM(Consumption) OVER(PARTITION BY ip.SiteMaterialUSageId, ip.ConsignmentLocationId ORDER BY ip.DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
)  Closing,

DECODE((SELECT VALUE FROM SYSTEMPARAMETERS WHERE ParameterName = 'RPClosingCalcMethod'), 'DeliveryDate', Opening,
First_value(Opening) OVER(PARTITION BY ip.SiteMaterialUSageId, ip.ConsignmentLocationId ORDER BY DateFrom) +
SUM(RequestedOrdersIn + FirmOrdersIn)
OVER(PARTITION BY ip.SiteMaterialUSageId,
ip.ConsignmentLocationId ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) -
SUM(Consumption + RequestedOrdersOut - TentativeOrdersOut)
OVER(PARTITION BY ip.SiteMaterialUSageId,
ip.ConsignmentLocationId ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) -
(RequestedOrdersIn + FirmOrdersIn) + (Consumption + RequestedOrdersOut - TentativeOrdersOut)) IdealOpening,
DECODE((SELECT VALUE FROM SYSTEMPARAMETERS WHERE ParameterName = 'RPClosingCalcMethod'), 'DeliveryDate', Opening,
First_value(Opening) OVER(PARTITION BY ip.SiteMaterialUSageId, ip.ConsignmentLocationId ORDER BY DateFrom) +
SUM(NVL(FinalOrders, 0) + FirmOrdersIn)
OVER(PARTITION BY ip.SiteMaterialUSageId,
ip.ConsignmentLocationId ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) -
SUM(Consumption + RequestedOrdersOut - TentativeOrdersOut)
OVER(PARTITION BY ip.SiteMaterialUSageId,
ip.ConsignmentLocationId ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) -
(NVL(FinalOrders, 0) + FirmOrdersIn) + (Consumption + RequestedOrdersOut - TentativeOrdersOut)) RequestedOpening,
FirmOrdersIn FirmOrdersIn, RequestedOrdersIn IdealOrdersIn,
    NVL(ol.FinalOrders, 0) RequestedDateOrdersIn,
NVL(old.DeliveryOrders, 0) DeliveryOrdersIn,
SUM(RequestedOrdersIn) OVER(PARTITION BY ip.SiteMaterialUSageId, ip.ConsignmentLocationId ORDER BY DateFrom) CumulativeIdealOrders,
SUM(NVL(ol.FinalOrders, 0)) OVER(PARTITION BY ip.SiteMaterialUSageId, ip.ConsignmentLocationId ORDER BY DateFrom) CumulativeRequestedOrders,
SUM(NVL(old.DeliveryOrders, 0)) OVER(PARTITION BY ip.SiteMaterialUSageId, ip.ConsignmentLocationId ORDER BY DateFrom) CumulativeDeliveryOrders,
(ip.ConsumptionOrders - TentativeOrdersOut) FirmOrdersOut, RequestedOrdersOut TentativeOrdersOut,
ConsumptionForecast ForecastDemand,
DECODE((SELECT VALUE FROM SYSTEMPARAMETERS WHERE ParameterName = 'RPClosingCalcMethod'), 'DeliveryDate',
PlannedInventory,
First_value(Opening) OVER(PARTITION BY ip.SiteMaterialUSageId, ip.ConsignmentLocationId ORDER BY DateFrom) +
SUM(RequestedOrdersIn + FirmOrdersIn)
OVER(PARTITION BY ip.SiteMaterialUSageId, ip.ConsignmentLocationId ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
- (RequestedOrdersIn + FirmOrdersIn) - SUM(Consumption + RequestedOrdersOut - TentativeOrdersOut)
OVER(PARTITION BY ip.SiteMaterialUSageId,
ip.ConsignmentLocationId ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)) IdealClosing,

DECODE((SELECT VALUE FROM SYSTEMPARAMETERS WHERE ParameterName = 'RPClosingCalcMethod'), 'DeliveryDate',
PlannedInventory,
First_value(Opening) OVER(PARTITION BY ip.SiteMaterialUSageId, ip.ConsignmentLocationId ORDER BY DateFrom) +
SUM(NVL(FinalOrders, 0))
OVER(PARTITION BY ip.SiteMaterialUSageId,
ip.ConsignmentLocationId ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) -
(NVL(FinalOrders, 0) + FirmOrdersIn) - SUM(Consumption + RequestedOrdersOut - TentativeOrdersOut)
OVER(PARTITION BY ip.SiteMaterialUSageId,
ip.ConsignmentLocationId ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)) RequestedClosing,
SafetyStock SafetyStock
FROM   InventoryProfiles ip
LEFT   JOIN (SELECT SiteMaterialUsageId, o.Toconsignmentlocationid ConsignmentLocationId, RequestedDate,
SUM(FinalWeight) FinalOrders
FROM   OrderLines o
WHERE  OrderLineStatusID = (SELECT TO_NUMBER(ol.Id)
FROM   OrderLineStatuses ol, SystemParameters sp
WHERE  ParameterName = 'ReplenishmentDefaultTentativeStatus'
AND    ol.OrderLineStatusName = sp.Value)
GROUP  BY SiteMaterialUsageId, o.Toconsignmentlocationid, RequestedDate) ol
ON     ol.RequestedDate = ip.DateFrom
AND    ol.SiteMaterialUsageId = ip.SiteMaterialUsageId
AND    NVL(ol.ConsignmentLocationId, 0) = NVL(ip.ConsignmentLocationId, 0)
LEFT   JOIN (SELECT SiteMaterialUsageId, o.Toconsignmentlocationid ConsignmentLocationId, DeliveryDate,
SUM(FinalWeight) DeliveryOrders
FROM   OrderLines o
WHERE  OrderLineStatusID = (SELECT TO_NUMBER(ol.Id)
FROM   OrderLineStatuses ol, SystemParameters sp
WHERE  ParameterName = 'ReplenishmentDefaultTentativeStatus'
AND    ol.OrderLineStatusName = sp.Value)
GROUP  BY SiteMaterialUsageId, o.Toconsignmentlocationid, DeliveryDate) OLD
ON     old.DeliveryDate = ip.DateFrom
AND    old.SiteMaterialUsageId = ip.SiteMaterialUsageId
AND    NVL(old.ConsignmentLocationId, 0) = NVL(ip.ConsignmentLocationId, 0)

ORDER  BY 1, 2, 3
top
EV#RPCustomerDemandNoSuper
SELECT * FROM
EV#CustomerReplenishedDemand uh
WHERE NOT EXISTS(SELECT 1 from IH#MaterialSupercessions ms
where ms.OnSiteMaterialUsageId = uh.SiteMaterialUsageId
OR ms.SiteMaterialUsageId = uh.SiteMaterialUsageId)
top
EV#RPSourceRuns
SELECT SiteName, SiteCode, WorkcentreName, WorkcentreCode, BlockRunCode, OriginalCapacity, Capacity, OriginalDuration, Duration,
       sr.StartDate, sr.FinishDate, CalculatedFinishDate, mrp.ProductName RunProperties,
       mr.Id MaterialRunId
FROM SourceRuns sr JOIN MaterialRuns mr
ON mr.id = sr.MaterialRunId
JOIN IH#workcentres wc ON wc.WorkcentreId = mr.WorkcentreId
JOIN MaterialRunProducts mrp ON mrp.MaterialRunId = mr.Id
top
EV#SelectiveData
SELECT smu.Id SiteMaterialUsageId, LocationName, LocationCode, MaterialName, MaterialCode,
EndUseCode, EndUseDescription, EndCustomerCode, EndCustomerName,
HistoryStartDate, StartDate, Successed, FirstPassId, SecondPassId, UseTradingDays
FROM SelectiveData sd JOIN Ev#sitematerialusages smu ON smu.Id = sd.SiteMaterialUsageId
top
EV#SiteMaterialUSages
SELECT smu.Id, l.LocationName, l.LocationCode, MaterialName, MaterialCode,
eu.endusecode, eu.EndUseDescription, ec.Locationcode EndCustomerCode,
ec.LocationName EndCustomerName, Replenished, smu.Status, ReplenishmentFlag
FROM   SiteMaterialUsages smu
JOIN   Locations l
ON     (smu.LocationId = l.Id)
JOIN   Materials m
ON     smu.MaterialId = m.Id
LEFT JOIN EndUses eu
ON eu.Id = smu.EndUseId
LEFT JOIN Locations ec
ON ec.Id = smu.EndCustomerId
top
EV#SNODemands
SELECT UserName, ScenarioName, TRUNC(DateFrom, 'month') DeliveryMonth, TRUNC(DateFrom, 'IW') DeliveryWeek,
       Forecast, NonMoveableFirm Orders, Inventory, Demand, MandatoryDemand,
       OptionalDemand, Netted, Aggregated, AfterPrenetting, SNODemand, Revenue, Margin, Allocation
FROM   SNODemands sd
JOIN   Ih#scenarios s
ON     s.UserId = sd.SnapshotUserId
AND    s.Id = sd.ScenarioId

top
EV#SNOForecast
SELECT UserName, SnapshotState, TRUNC(DateFrom, 'month') DeliveryMonth, TRUNC(DateFrom, 'IW') DeliveryWeek,
       System, Customer, Orders, Demand, MandatoryDemand, Netted, Aggregated, AfterPrenetting, SNODemand
FROM   ForecastBodySnapshots fb
JOIN   Ih#scenarios s
ON     s.UserId = fb.SnapshotUserId
top
EV#SNOPrenettingAllocations
SELECT UserName, ScenarioName,
ev.*,
sf.*,
WorkcentreName, SiteName
FROM Snoprenettingallocations sf
JOIN Scenarios s ON s.id = sf.ScenarioId
JOIN ScenarioSessions SS ON ss.SnapshotUserId = sf.SnapshotUserId
JOIN USERS u ON u.Id = ss.SnapshotUserId
JOIN IH#Workcentres wc ON wc.WorkcentreID = sf.WhWorkcentreId
JOIN EV#SiteMaterialUSages ev ON ev.Id = sf.SiteMaterialUsageId
top
EV#SnpItems
SELECT si.ID SnpItemId,
smu.*,
si.SiteMaterialUsageId, si.MaterialId, si.HierarchyId,
SI.PROPERTYVALUEID, si.CustomerRankId,
SI.ISWAREHOUSE,
Si.EndUseId
FROM SNOItems SI
JOIN Ev#sitematerialusages smu
ON smu.Id = si.SiteMaterialUsageId
top
EV#SNPLIndicatives
WITH PARAMETERS AS
(
  SELECT TRUNC(core.getInternalDate) CurrentDate, 
         StartWeek - INTERVAL '1' MINUTE FinishFrozenDate, 
         StartWeek, StartWeek - 1 FinishWeek, 
         SnapshotUserId, UserName
    FROM IH#ScenarioSessions
),
RemainingAllocation AS
(
  SELECT SnapshotUserId, SiteID, GradeId, (Diff * Duration / OriginalDuration) Indicative,
         StartMonth, FinishMonth, FinishWeek, CurrentDate,
         OriginalDuration, StartMonth1, FinishMonth1, Duration, Allocation, Orders, Diff
    FROM (
           SELECT SnapshotUserId, SiteId, GradeId, pp.CurrentDate, pp.FinishWeek, DeliveryMonth StartMonth,
                  Last_day(deliverymonth) FinishMonth, Last_day(deliverymonth) - DeliveryMonth + 1 OriginalDuration,
                  GREATEST(pp.CurrentDate, DeliveryMonth) StartMonth1,
                  LEAST(Last_day(deliverymonth), pp.FinishWeek) FinishMonth1,
                  LEAST(Last_day(deliverymonth), pp.FinishWeek) - GREATEST(pp.CurrentDate, DeliveryMonth) + 1 Duration,
                  SUM(Allocation) Allocation, SUM(OrdersWeight) Orders, SUM(Allocation) - SUM(OrdersWeight) Diff
             FROM IVMP#Indicatives i
            CROSS JOIN PARAMETERS pp
            WHERE DeliveryMonth BETWEEN TRUNC(pp.CurrentDate, 'month') AND TRUNC(pp.FinishWeek, 'month')
            GROUP BY SnapshotUserId, SiteId, GradeId, DeliveryMonth, Last_day(DeliveryMonth), pp.FinishWeek, pp.CurrentDate
          ) t
   WHERE Allocation > Orders
)
SELECT UserName, SiteName, SiteId, GradeCode, t.GradeID,
       CurrentDate, FinishWeek, StartMonth, FinishMonth,
       OriginalDuration, StartMonth1, FinishMonth1, Duration, Allocation, Orders, Diff, 
       Indicative
  FROM RemainingAllocation t
  JOIN Sites s
    ON s.Id = t.SiteId
  JOIN GradeProperties g
    ON g.GradeId = t.GradeId
  JOIN Users u 
    ON u.Id = t.SnapshotUSerId
 ORDER BY SiteName, GradeCode
top
EV#SNPLOpening
WITH PARAMETERS AS
(
  SELECT TRUNC(core.getInternalDate) CurrentDate, 
         StartWeek - INTERVAL '1' MINUTE FinishFrozenDate, 
         StartWeek, StartWeek - 1 FinishWeek, 
         SnapshotUserId, UserName
    FROM IH#ScenarioSessions
),
Opening AS
(
  SELECT SnapshotUserId, m.MaterialCode, l.LocationCode, 
         gm.GradeId, l.SiteId, parameters.CurrentDate DateFrom, 
         mt.IsFinishedGoods, NVL(Opening, 0) Opening
    FROM SiteMaterialUsages smu
   CROSS JOIN PARAMETERS
    JOIN Materials m
      ON m.Id = smu.MaterialId
    JOIN MaterialTypes mt
      ON mt.Id = m.MaterialTypeId
    JOIN GradeMaterials gm
      ON gm.MaterialId = m.Id
    JOIN Locations l
      ON l.Id = smu.LocationId
    JOIN WorkCentres wc
      ON wc.LocationId = l.Id
    LEFT JOIN RealInventoryProfiles rip
      ON rip.SiteMaterialUsageId = smu.Id
     AND rip.DateFrom = Parameters.CurrentDate
)
SELECT UserName, SiteName, t.MaterialCode, t.LocationCode, GradeCode, DateFrom, Opening
  FROM Opening t
  JOIN Sites s
    ON s.Id = t.SiteId
  JOIN GradeProperties g
    ON g.GradeId = t.GradeId
  JOIN Users u 
    ON u.Id = t.SnapshotUserId
 ORDER BY SiteName, GradeCode
top
EV#SNPLOrders
WITH PARAMETERS AS
(
  SELECT TRUNC(core.getInternalDate) CurrentDate, 
         StartWeek - INTERVAL '1' MINUTE FinishFrozenDate, 
         StartWeek, StartWeek - 1 FinishWeek, 
         SnapshotUserId, UserName
    FROM IH#ScenarioSessions
),
Orders AS
(
  SELECT SnapshotUserId, wc.SiteId, GradeId, FinalWeight OrdersWeight,
         DespatchDate, pp.StartWeek,
         ob.OrderCode, ol.LineNoCode
    FROM OrderBooks ob
    JOIN OrderLines ol 
      ON ol.OrderBookId = ob.Id
   CROSS JOIN PARAMETERS pp
    JOIN OrderLineStatuses ols
      ON ols.ID = ol.OrderLineStatusId
    JOIN GradeMaterials gm
      ON gm.MaterialId = ol.MaterialId
    JOIN IH#Workcentres wc
      ON wc.WorkcentreId = ol.WorkcentreId
   WHERE ols.OrderLineStatusCode = 'Firm'
     AND DespatchDate < pp.StartWeek
     AND OrderType = 'Customer'
)
   
SELECT UserName, SiteName, SiteId, GradeCode, t.GradeID,
       StartWeek, DespatchDate, t.OrderCode, t.LineNoCode, OrdersWeight Orders
  FROM Orders t
  JOIN Sites s
    ON s.Id = t.SiteId
  JOIN GradeProperties g
    ON g.GradeId = t.GradeId
  JOIN Users u 
    ON u.Id = t.SnapshotUSerId
 ORDER BY SiteName, GradeCode
top
EV#SNPLRunCapacity
WITH PARAMETERS AS
(
  SELECT TRUNC(core.getInternalDate) CurrentDate, 
         StartWeek - INTERVAL '1' MINUTE FinishFrozenDate, 
         StartWeek, StartWeek - 1 FinishWeek, 
         SnapshotUserId, UserName
    FROM IH#ScenarioSessions
),
RunCapacity AS
(
  SELECT SnapshotUserId, mr.BlockRunCode, SiteId, GradeId, pp.CurrentDate, pp.FinishFrozenDate, 
         mr.StartDate OriginalStartDate,
         mr.FinishDate OriginalFinishDate, 
         mr.FinishDate - mr.StartDate OriginalDuration,
         GREATEST(mr.StartDate, pp.CurrentDate) StartDate, 
         LEAST(mr.FinishDate, pp.FinishFrozenDate) FinishDate,
         LEAST(mr.FinishDate, pp.FinishFrozenDate) - GREATEST(mr.StartDate, pp.CurrentDate) Duration,
         Quantity OriginalCapacity,
         Quantity 
           * (LEAST(mr.FinishDate, pp.FinishFrozenDate) - GREATEST(mr.StartDate, pp.CurrentDate)) 
           / (mr.FinishDate - mr.StartDate) Capacity
   FROM MaterialRuns mr
  CROSS JOIN PARAMETERS pp
   JOIN MaterialRunProducts mrp
     ON mrp.MaterialRunId = mr.Id
   JOIN IH#Workcentres wc
     ON mr.WorkcentreID = wc.WorkcentreId
   JOIN GradeProperties gp
     ON gp.Gradecode = mrp.ProductName
  WHERE (mr.StartDate BETWEEN pp.CurrentDate AND pp.FinishFrozenDate 
         OR mr.FinishDate BETWEEN pp.CurrentDate AND pp.FinishFrozenDate)
)
SELECT UserName, SiteName, GradeCode, BlockRunCode, 
       CurrentDate, FinishFrozenDate, 
       OriginalStartDate, OriginalFinishDate, OriginalDuration,
       StartDate, FinishDate, Duration, OriginalCapacity, Capacity
  FROM RunCapacity t
  JOIN Sites s
    ON s.Id = t.SiteId
  JOIN GradeProperties g
    ON g.GradeId = t.GradeId
  JOIN Users u 
    ON u.Id = t.SnapshotUSerId
 ORDER BY SiteName, GradeCode
top
EV#SNPLTotal
WITH PARAMETERS AS
(
     SELECT TRUNC(core.getInternalDate) CurrentDate, StartWeek - INTERVAL '1' MINUTE FinishFrozenDate, StartWeek,
            StartWeek - 1 FinishWeek, SnapshotUserId, UserName
       FROM IH#ScenarioSessions
),
Opening AS
(
  SELECT SnapshotUserId, gm.GradeId, l.SiteId, parameters.CurrentDate DateFrom, mt.IsFinishedGoods, SUM(NVL(Opening, 0)) Opening
    FROM SiteMaterialUsages smu
   CROSS JOIN PARAMETERS
    JOIN Materials m
      ON m.Id = smu.MaterialId
    JOIN MaterialTypes mt
      ON mt.Id = m.MaterialTypeId
    JOIN GradeMaterials gm
      ON gm.MaterialId = m.Id
    JOIN Locations l
      ON l.Id = smu.LocationId
    JOIN WorkCentres wc
      ON wc.LocationId = l.Id
    LEFT JOIN Realinventoryprofiles rip
      ON rip.SiteMaterialUsageId = smu.Id
     AND rip.DateFrom = Parameters.CurrentDate
   GROUP BY SnapshotUSerId, parameters.CurrentDate, gm.GradeId, l.SiteId, mt.IsFinishedGoods
),
RunCapacity AS
(
  SELECT SnapshotUserId, SiteId, GradeId, SUM(Capacity) Capacity
    FROM (SELECT SnapshotUserId, SiteId, GradeId, pp.CurrentDate, pp.FinishFrozenDate, mr.StartDate OriginalStartDate,
                 mr.FinishDate OriginalFinishDate, mr.FinishDate - mr.StartDate OriginalDuration,
                 GREATEST(mr.StartDate, pp.CurrentDate) StartDate, LEAST(mr.FinishDate, pp.FinishFrozenDate) FinishDate,
                 LEAST(mr.FinishDate, pp.FinishFrozenDate) - GREATEST(mr.StartDate, pp.CurrentDate) Duration,
                 Quantity OriginalCapacity,
                 Quantity * (LEAST(mr.FinishDate, pp.FinishFrozenDate) - GREATEST(mr.StartDate, pp.CurrentDate)) 
                 / (mr.FinishDate - mr.StartDate) Capacity
           FROM MaterialRuns mr
          CROSS JOIN PARAMETERS pp
           JOIN MaterialRunProducts mrp
             ON mrp.MaterialRunId = mr.Id
           JOIN IH#Workcentres wc
             ON mr.WorkcentreID = wc.WorkcentreId
           JOIN GradeProperties gp
             ON gp.Gradecode = mrp.ProductName
          WHERE (mr.StartDate BETWEEN pp.CurrentDate AND pp.FinishFrozenDate 
                 OR mr.FinishDate BETWEEN pp.CurrentDate AND pp.FinishFrozenDate)
         )
   GROUP BY SnapshotUserId, SiteId, GradeId
),
Orders AS
(
  SELECT SnapshotUserId, wc.SiteId, GradeId, SUM(FinalWeight) OrdersWeight
    FROM OrderLines ol
   CROSS JOIN PARAMETERS pp
    JOIN OrderLineStatuses ols
      ON ols.ID = ol.OrderLineStatusId
    JOIN GradeMaterials gm
      ON gm.MaterialId = ol.MaterialId
    JOIN IH#Workcentres wc
      ON wc.WorkcentreId = ol.WorkcentreId
   WHERE ols.Orderlinestatuscode = 'Firm'
     AND DespatchDate < pp.StartWeek
     AND OrderType = 'Customer'
   GROUP BY SnapshotUserId, wc.SiteId, GradeId
),
RemainingAllocation AS
(
  SELECT SnapshotUserId, SiteID, GradeId, SUM(Diff * Duration / OriginalDuration) Allocation
    FROM (
           SELECT SnapshotUserId, SiteId, GradeId, pp.CurrentDate, pp.FinishWeek, DeliveryMonth StartMonth,
                  Last_day(deliverymonth) FinishMonth, Last_day(deliverymonth) - DeliveryMonth + 1 OriginalDuration,
                  GREATEST(pp.CurrentDate, DeliveryMonth) StartMonth1,
                  LEAST(Last_day(deliverymonth), pp.FinishWeek) FinishMonth1,
                  LEAST(Last_day(deliverymonth), pp.FinishWeek) - GREATEST(pp.CurrentDate, DeliveryMonth) + 1 Duration,
                  SUM(Allocation) Allocation, SUM(OrdersWeight) Orders, SUM(Allocation) - SUM(OrdersWeight) Diff
             FROM IVMP#Indicatives i
            CROSS JOIN PARAMETERS pp
            WHERE DeliveryMonth BETWEEN TRUNC(pp.CurrentDate, 'month') AND TRUNC(pp.FinishWeek, 'month')
            GROUP BY SnapshotUserId, SiteId, GradeId, DeliveryMonth, Last_day(deliverymonth), pp.FinishWeek, pp.CurrentDate) t
    WHERE Allocation > Orders
    GROUP BY SnapshotUserId, SiteID, GradeId
),
Totals AS
(
   SELECT SnapshotUserId, Siteid, GradeID, Opening, 0 Capacity, 0 OrdersWeight, 0 Allocation
     FROM Opening
    UNION ALL
   SELECT SnapshotUserId, Siteid, GradeID, 0 Opening, Capacity, 0 OrdersWeight, 0 Allocation
     FROM RunCapacity
    UNION ALL
   SELECT SnapshotUserId, Siteid, GradeID, 0 Opening, 0 Capacity, OrdersWeight, 0 Allocation
     FROM Orders
    UNION ALL
   SELECT SnapshotUserId, Siteid, GradeID, 0 Opening, 0 Capacity, 0 OrdersWeight, Allocation
     FROM RemainingAllocation
)
SELECT UserName, SiteName, GradeCode, SiteId, t.GradeID, SUM(Opening) Opening, 
       SUM(Capacity) Capacity, SUM(OrdersWeight) Orders, SUM(Allocation) Indicatives,
       SUM(Opening) + SUM(Capacity) - SUM(OrdersWeight) - SUM(Allocation) SNPOpening
  FROM Totals t
  JOIN Sites s
    ON s.Id = t.SiteId
  JOIN GradeProperties g
    ON g.GradeId = t.GradeId
  JOIN Users u 
    ON u.Id = t.SnapshotUSerId
 GROUP BY UserName, SiteName, GradeCode, t.SiteId, t.GradeID
 ORDER BY SiteName, GradeCode
top
EV#SourceLists
SELECT sl.Id SourceListId, sl.IsFull,
LISTAGG(WorkcentreName, ',')  WITHIN GROUP (ORDER BY WorkcentreName) AS SourceListNames,
LISTAGG(WorkcentreCode, ',')  WITHIN GROUP (ORDER BY WorkcentreCode) AS SourceListCodes
 FROM Sourcelists sl JOIN SourceListSources s
ON sl.Id = s.SourceListId
JOIN workcentres wc ON wc.Id = s.WorkcentreId
GROUP BY sl.Id, sl.IsFull
top
EV#SourceRunsRequestedDate
SELECT WorkcentreName, WorkcentreCode, BlockRunCode, mrp.ProductName RunProperties, Capacity, sr.StartDate,
       sr.FinishDate, CalculatedFinishDate, mr.Id MaterialRunId, MinRequestedDate, MaxRequestedDate, FinalWeight
FROM   SourceRuns sr
JOIN   MaterialRuns mr
ON     mr.id = sr.MaterialRunId
JOIN   workcentres wc
ON     wc.Id = mr.WorkcentreId
JOIN   MaterialRunProducts mrp
ON     mrp.MaterialRunId = mr.Id
JOIN   (SELECT ol.WorkcentreId, MaterialRunId, MIN(RequestedDate) MinRequestedDate, MAX(RequestedDate) MaxRequestedDate,
               SUM(FinalWeight) FinalWeight
        FROM   OrderLines ol
        JOIN   OrderOperations oo
        ON     oo.OrderLineId = ol.Id
        WHERE  ol.OrderLineStatusId = 1
        GROUP  BY ol.WorkcentreId, MaterialRunId) t
ON     t.MaterialRunId = sr.MaterialRunId
ORDER  BY WorkcentreName, mrp.ProductName, StartDate
top
EV#SourcingAllocation
SELECT UserName, ScenarioName, TRUNC(SourceDate, 'month') SourceMonth, TRUNC(SourceDate, 'IW') SourceWeek,
       TRUNC(DeliveryDate, 'month') DeliveryMonth, TRUNC(DeliveryDate, 'IW') DeliveryWeek,
	   WorkcentreName, Allocation, CycleInventory, Revenue, Margin, ProductionCost, InventoryCost
FROM   SourcingAllocation sa
JOIN   Ih#Scenarios s
ON     s.UserId = sa.SnapshotUserId
AND    s.Id = sa.ScenarioId
JOIN   IH#Workcentres wc
ON     wc.WorkcentreID = sa.WorkcentreId

top
EV#supersededopeningprofiles

SELECT smu.LocationName, smu.LocationCode,
smu.MaterialName, smu.MaterialCode,
smu.ConsignmentCustomerName, smu.ConsignmentCustomerCode, r.*
FROM Ih#supersededopeningprofiles r
JOIN EV#AllSiteMaterialUsages smu
ON smu.Id = r.SiteMaterialUsageId
AND NVL(smu.ConsignmentLocationId,0) = NVL(r.ConsignmentLocationId,0)
top
EV#TentativeOrderLines
Select LocationName, LocationCode, MaterialName, MaterialCode,
EndUseCode, EndUseDescription, EndCustomerCode, EndCustomerName,
WorkcentreName, WorkcentreCode, BlockRunCode, OrderLineStatusName,
ol.*, NVL(oo.MaterialRunId,0) MaterialRunId
from OrderLines ol
JOIN EV#SiteMaterialUsages smu ON ol.SiteMaterialUsageId = smu.Id
LEFT JOIN OrderOperations oo ON oo.OrderLineId = ol.Id
LEFT JOIN MaterialRuns mr ON mr.Id = oo.MaterialRunId
JOIN OrderLineStatuses ols ON ols.Id = ol.OrderLineStatusId
JOIN Workcentres wc ON wc.id = ol.Workcentreid
WHERE OrderLineStatusName IN (
SELECT Value
FROM   SystemParameters sp
WHERE  ParameterName = 'ReplenishmentDefaultTentativeStatus')

top
EV#TransportTimeTable

Select t.LocationName ToLocationName,  t.LocationCode ToLocationCode,
 f.LocationName FromLocationName, f.LocationCode FromLocationCode,
 j.JOURNEYCODE,
 j.TimePeriod DurationInDays,
 tt.*
 from TransportTimeTable tt
join JourneysIPlanView j on tt.JourneyId = j.JourneyId
join locations f on f.ID = tt.FromLocationId
join locations t on t.Id = tt.ToLocationId

top
EV#UsageHistories
SELECT smu.Id SiteMaterialUSageId, LocationName, LocationCode, MaterialName, MaterialCode,
EndUseCode, EndUseDescription, EndCustomerCode, EndCustomerName,
DateFrom, Weight, AdjustedWeight, Price, WorkcentreCode, WorkcentreName
FROM UsageHistories uh
JOIN EV#SiteMaterialUSages smu
ON smu.Id = uh.SiteMaterialUsageID
LEFT JOIN Workcentres wc
ON wc.Id = uh.WorkcentreId
top
EV#UsageHistoriesNoSuper
SELECT *
FROM EV#UsageHistories uh
WHERE NOT EXISTS(SELECT 1 from IH#MaterialSupercessions ms
where ms.OnSiteMaterialUsageId = uh.SiteMaterialUsageId
OR ms.SiteMaterialUsageId = uh.SiteMaterialUsageId)
top
EV#WarehouseSku

SELECT SiteMaterialUsageId, ConsignmentLocationId,
l.LocationName, l.LocationCode, MaterialName, MaterialCode,
cl.LocationName CustomerName, cl.LocationCode CustomerCode,
 Replenished
FROM   IH#WHSkus smu
JOIN   Locations l
ON     (smu.LocationId = l.Id)
JOIN   Materials m
ON     smu.MaterialId = m.Id
LEFT JOIN Locations cl
ON cl.Id = smu.ConsignmentLocationId
top
EV#WeeklyForecastBodies
SELECT fb.SiteMaterialUSageId, LocationName, LocationCode, MaterialName, MaterialCode, EndUseCode, EndUseDescription,
       EndCustomerCode, EndCustomerName, s.DateFromIW DateFromWeek, fb.DateFrom DateFromMonth,
       OriginalSystem * s.Coef OriginalSystem, SYSTEM * s.Coef SYSTEM, Customer * c.Coef Customer, FINAL * f.Coef FINAL
FROM   ForecastBodies fb
JOIN   EV#SiteMaterialUSages smu
ON     smu.Id = fb.SiteMaterialUsageID
JOIN   ForecastWeeklyCoefs s
ON     s.Id = fb.SystemWeeklyCoefId
AND    fb.DateFrom = s.DateFrom
JOIN   ForecastWeeklyCoefs c
ON     c.Id = fb.SystemWeeklyCoefId
AND    fb.DateFrom = c.DateFrom
JOIN   ForecastWeeklyCoefs f
ON     f.Id = fb.SystemWeeklyCoefId
AND    fb.DateFrom = f.DateFrom
WHERE  fb.ForecastId = forecasting.getLatestForecast()
AND    s.DateFromIW = f.DateFromIW
AND    c.DateFromIw = f.DatefromIw
AND    s.Datefrom = f.DateFrom
AND    c.Datefrom = f.DateFrom
top
EV#WorkcentreTimeTable

SELECT
 fw.WorkcentreName FromWorkcentreName, fw.WorkcentreCode FromWorkcentreCode,
 tw.WorkcentreName ToWorkcentreName, tw.WorkcentreCode ToWorkcentreCode,
 j.JOURNEYCODE,
 j.TimePeriod DurationInDays,
 tt.*
 FROM
 TransportTimeTable tt
join JourneysIPlanView j on tt.JourneyId = j.JourneyId
join locations f on NVL(f.TransportLocationId, f.ID) = tt.FromLocationId
join locations t on NVL(t.TransportLocationId, t.Id) = tt.ToLocationId
join workcentres fw on fw.LocationId = f.Id
join workcentres tw on tw.LocationId = t.Id

top
EV#WrongConsignmentCustomer
SELECT v.LocationName, v.LocationCode, v.MAterialName, v.MaterialCode, l.LocationName CustomerName, l.LocationCode CustomerCode
FROM Consignmentparameters cp
JOIN  EV#SITEMATERIALUSAGES v ON v.Id = cp.SiteMaterialUSageID
JOIN Locations l ON l.Id = cp.CustomerId
WHERE EXISTS (SELECT 1 FROM IH#Workcentres wc WHERE wc.LocationId = cp.CustomerId)
top
EV#WrongConsignmentSku
SELECT v.LocationName, v.LocationCode, v.MAterialName, v.MaterialCode, l.LocationName CustomerName, l.LocationCode CustomerCode
FROM Consignmentparameters cp
JOIN  EV#SITEMATERIALUSAGES v ON v.Id = cp.SiteMaterialUSageID
JOIN  SiteMaterialUSages smu ON v.Id = smu.Id
JOIN Locations l ON l.Id = cp.CustomerId
WHERE NOT EXISTS (SELECT 1 FROM IH#Workcentres wc WHERE wc.LocationId = smu.LocationId)
top
EV#WrongSourceLists
SELECT SiteMaterialUSageId, smu.LocationName, smu.LocationCode,
SMU.MaterialName, smu.MaterialCode, smu.endusecode,
smu.EndUSeDescription,
smu.EndCustomerCode,
smu.EndCustomerName,
smu2.SourceListId, sl.Id, sources, sl.SourceList, sl.IsFull
FROM   (SELECT SiteMaterialUSageId,
                TO_CHAR(core.Ascsv(CAST(COLLECT(WorkcentreId ORDER BY WorkcentreId) AS myIdentityArray))) Sources
         FROM   InitialSources
         GROUP  BY SiteMaterialUsageID) t
JOIN   EV#SiteMAterialUSages smu
ON     smu.ID = t.SiteMaterialUSageId
JOIN   SiteMAterialUSages smu2
ON     smu2.ID = smu.Id
LEFT   JOIN SourceLists sl
ON     sl.SourceList = t.Sources
WHERE  (SourceListId != sl.Id OR sources != sl.SourceList)

top
EVC#OverloadedStocks
SELECT ip.*, ip.roundOrderUnits(ip.SiteMaterialUsageId, ip.ConsignmentLocationId, 0) MinORderQuantity
FROM   EV#InventoryProfiles ip
WHERE  DateFrom = (SELECT MAX(DateFrom) FROM InventoryProfiles)
AND    PlannedInventory - SafetyStock > ip.roundOrderUnits(ip.SiteMaterialUsageId, ip.ConsignmentLocationId, 0)
top
EVC#SourcePriorityDates
WITH q AS (
SELECT SourceSiteMAterialUSageId, MIN(DateFrom - TimePeriod) DateFrom, MIN(DateTo - TimePeriod) DateTo FROM Replenishedcustomersku
GROUP BY SourceSiteMAterialUSageId
)
SELECT ip.*, q.DateFrom SourceDateFrom, q.DateTo SourceDateTo
FROM InventoryPRofiles ip JOIN q ON ip.SiteMaterialUsageId = q.SourceSiteMaterialUsageId
WHERE  ConsumptionForecast > 0
AND (ip.DateFrom < q.DateFrom OR  ip.DateFrom > q.DateTo)
top
EVC#StockViolations
SELECT * FROM EV#InventoryProfiles WHERE
tentativeordersout > 0
AND plannedinventory < 0
top
EVC#StockViolationsRuns
SELECT ol.Id, s.LocationName, s.MaterialName, ol.SiteMaterialUsageId, ol.MaterialId, ol.WorkcentreId,
ol.RequestedDate, ol.DeliveryDate, ol.FinalWeight
FROM   OrderLines ol
JOIN  IH#Sku s ON s.Id = ol.SiteMaterialUSageID
WHERE  OrderLineStatusId = 1
AND    RequestedDate < DeliveryDate
                       AND    EXISTS (SELECT 1
FROM   SourceRuns sr
JOIN   SourceRunMaterials rm
ON     rm.materialrunid = sr.MaterialRunId
WHERE  rm.MaterialId = ol.MAterialId
AND    sr.Capacity > ip.roundOrderUnits(ol.Sitematerialusageid, ol.ToConsignmentLocationId, 1)
AND    sr.Calculatedfinishdate < ol.Requesteddate
                                 AND    sr.WorkcentreID = ol.WorkcentreId)
AND    EXISTS (SELECT 1 FROM IH#Workcentres wc WHERE wc.WorkcentreTypeName = 'Paper Machine' AND wc.WorkcentreId = ol.WorkcentreId)
AND  EXISTS (SELECT 1 FROM EV#REQUESTEDINVENTORYPROFILES ip WHERE ip.SiteMaterialUSageId = ol.SiteMaterialUsageId
AND NVL(ip.Consignmentlocationid,0) = NVL(ol.Toconsignmentlocationid,0)
AND Closing < SafetyStock
              AND datefrom BETWEEN ol.RequestedDate AND ol.DeliveryDate)
top
ExcludedSAMaterialsIPlanView
select * from materials m
where exists(select 1 from expandedmaterials em,propertyvalues pv,
excludedpropertiesfromsa sa
where em.materialid = m.id
and em.propertyvalueid = pv.id
and sa.propertyid = pv.propertyid
and sa.value = pv.value)
top
ExcludedSKUFromSAIPlanView
select * from Sitematerialusages smu
where exists(select 1 from expandedmaterials em,propertyvalues pv,
excludedpropertiesfromsa sa
where em.materialid = smu.materialid
and em.propertyvalueid = pv.id
and sa.propertyid = pv.propertyid
and sa.value = pv.value)
top
ExpandedEndUseSKUIPlanView
SELECT smu.Id SiteMaterialUsageId, EndUseId, m.*, l.*, MaterialName ProductName, MaterialCode ProductCode,
       e.*, smu.Status, CurrencyName, ll.CurrencyId,
       ec.*, smu.SkuProperty1, smu.SkuProperty2,
       smu.SkuProperty3, smu.SkuProperty4, smu.SkuProperty5
FROM   SiteMaterialUsages smu
LEFT JOIN   Materialpropsspec m
ON     smu.MaterialId = m.MaterialId
LEFT   JOIN Expandedlocationsspec l
ON     smu.LocationId = l.LocationId
JOIN   (SELECT loc.Id, NVL(loc.CurrencyId, dc.CurrencyId) CurrencyId
        FROM   Locations loc, (SELECT Id CurrencyId FROM Currencies WHERE IsInternal = 1) dc) ll
ON     (ll.Id = smu.LocationId)
JOIN   Currencies c
ON     (c.ID = ll.CurrencyId)
JOIN   MaterialTypes mt
ON     (m.MaterialTypeId = mt.Id)
LEFT   JOIN Enduses e
ON     (e.ID = smu.EndUseId)
LEFT   JOIN IH#EndCustomerHierarchies ec
ON     ec.EndCustomerId = NVL(smu.EndCustomerId,smu.LocationId)
top
FinishingLinesView
   SELECT LocationName, LocationCode, WorkcentreName,
   WorkcentreCode, SiteCode,
   SiteName, wc.Id WorkcentreId, l.Id LocationId, s.Id
   SiteId
   FROM Locations l, Workcentres wc, WorkcentreTypes wct, Sites s
   WHERE
   WorkcentreTypeName IN ('Finishing Line')
   AND wc.WorkcentreTypeId = wct.Id
   AND
   wc.LocationId = l.Id
   AND l.SiteId = s.Id
top
FinishingWarehousesView
   SELECT LocationName, LocationCode, WorkcentreName,
   WorkcentreCode, SiteCode,
   SiteName, wc.Id WorkcentreId, l.Id LocationId, s.Id
   SiteId
   FROM Locations l, Workcentres wc, WorkcentreTypes wct, Sites s
   WHERE
   WorkcentreTypeName IN ('Warehouse')
   AND wc.WorkcentreTypeId = wct.Id
   AND
   wc.LocationId = l.Id
   AND l.SiteId = s.Id
top
ForecastMethodsIPlanView

SELECT f.Id, f.ForecastMethodName, t.ForecastMethodDesc, f.Internal, LanguageId
  FROM ForecastMethods f
  LEFT JOIN IT#ForecastMethods t ON t.ForecastMethodId = f.Id

top
GeneratedReplenishedOrdersView
   Select ol.Id, MaterialName Material, l.LocationName Location,
   cl.LocationName
   ToConsignment,
   WorkcentreCode, wcl.LocationName FromLocation,
   fcl.LocationName FromConsignment,
   OriginalWeight, DeliveryDate, DespatchDate
   from OrderLines ol, Locations l, Workcentres wc, Locations cl, Locations fcl,
   Materials m, Locations wcl
   WHERE ol.LocationId = l.Id
   and wc.Id=ol.WorkcentreId
   AND m.Id = ol.MaterialId
   AND wc.LocationId = wcl.Id
   AND
   ol.ToConsignmentLocationId = cl.Id (+)
   AND ol.FromConsignmentLocationId =
   fcl.Id (+)
   Order by ol.Id
top
GradeCostsIPlanView
SELECT  GradeId, GradeCode, WorkcentreId,
DateFrom, NVL(LEAD(DateFrom, 1) over( PARTITION BY GradeId, WorkcentreId order by DateFrom), to_date('01-01-2050', 'DD-MM-YYYY')) - 1 DateTo,
Cost, RuleWeighting
FROM
(
SELECT GradeId, GradeCode, WorkcentreId, DateFrom, Cost, RuleWeighting,
       RANK() over(PARTITION BY GradeId, WorkcentreId ORDER BY RuleWeighting DESC) r
FROM
(
SELECT DISTINCT GradeId, GradeCode, cr.WorkcentreId, cr.Id, cr.effective AS DateFrom, cr.Cost, cr.RuleWeighting
FROM   ExpandedCostRules ecr, CostRules cr, GradeMaterials gm
WHERE  ecr.MaterialId = gm.MaterialId
AND    cr.Id = ecr.CostRuleId
) t)
WHERE R = 1
top
GridsIPlanView
  SELECT g.Name GridName, p.PageName, IsColumnsAsRows, 'Grids.' || g.Name || '.' || gc.FieldName LanguageKey, gc.*
FROM Grids g
JOIN GridColumns gc ON (g.Id = gc.GridId)
LEFT JOIN Pages p ON (p.Id = g.PageId)
top
GroupedConsignmentSKUIPlanView
    

SELECT *
FROM   (SELECT SKuKey, SiteMaterialUsageId, cv.ConsignmentLocationId, cv.MaterialId, cv.LocationId,
                cv.WarehouseLocationId, Replenished,
                cv.AlternateProduct || '-' || NVL(cv.ConsignmentLocationId, 0) || '-' || WarehouseLocationId WarehouseGroupKey,
                WarehouseLocationId AS GroupId,
                SIGN(SUM(Replenished)
                      over(PARTITION BY WarehouseLocationId, cv.AlternateProduct, cv.ConsignmentLocationId)) IncludedInGroup,
                GroupKey
         FROM   IH#skus cv
         WHERE  WarehouseLocationID IS NOT NULL
  /* Excluded because it join into warehouse group by alternate products. ? */
         UNION ALL
         SELECT SKuKey, SiteMaterialUsageId, cv.ConsignmentLocationId, cv.MaterialId, cv.LocationId,
                cv.WarehouseLocationId, Replenished,
                cv.AlternateProduct || '-' || NVL(cv.ConsignmentLocationId, 0) || '-' || cv.LocationId WarehouseGroupKey,
                WarehouseLocationId AS GroupId,
                SIGN(SUM(Replenished) over(PARTITION BY cv.LocationId, cv.AlternateProduct, cv.ConsignmentLocationId)) IncludedInGroup,
                GroupKey
         FROM   IH#Skus cv
         WHERE  WarehouseLocationID IS NULL
          AND cv.AlternateProduct IS NOT NULL
)
WHERE  IncludedInGroup = 1


top
HierarchyLevelsIPlanView

SELECT Id, HierarchyLevelName,
REGEXP_REPLACE(HierarchyLevelName, '[^[:alnum:]_]', '') AS HierarchyName,
UPPER('H_' || REGEXP_REPLACE(HierarchyLevelName, '[^[:alnum:]_]', '')) AS HierarchyViewName,
UPPER('H_' || REGEXP_REPLACE(HierarchyLevelName, '[^[:alnum:]_]', '') || 'CODE') AS HierarchyViewCode,
HierarchyLevelName as HierarchyDesc,
'HierarchyCode' || ROW_NUMBER() Over(ORDER BY Id) FieldHierarchyCode,
'HierarchyName' || ROW_NUMBER() Over(ORDER BY Id) FieldHierarchyValue,
ROW_NUMBER() Over(ORDER BY Id) OrderNo,
HierarchyLevelNo
FROM HierarchyLevels

top
IE#Materials
SELECT m.Id, m.MaterialCode ProductCode, s.MaterialCode SourceProductCode, mt.MaterialTypeName ProductType,
       ms.MaterialTypeName SourceProductType, m.SourceMaterialId
FROM   Materials m
JOIN   MaterialTypes mt
ON     (m.MaterialTypeId = mt.Id)
LEFT   JOIN Materials s
ON     (m.SourceMaterialId = s.Id)
LEFT   JOIN MaterialTypes ms
ON     (s.MaterialTypeId = ms.Id)

top
IE#OrderLines
SELECT ol.Id, ob.Ordercode, ol.LineNoCode, ob.OrderCode || '-' || ol.LineNoCode OrderLineCode,
ols.OrderLineStatusName, wc.WorkcentreCode, l.LocationName, FinalWeight, ol.MaterialId, ol.LocationId,
ol.WorkcentreId OrderLineStatusId, NVL(InitialOrderLineStatusId,0) InitialOrderLineStatusId, SkuKey, SourceSkuKey,
DeliveryDate, ConsumptionDate, m.MaterialCode ProductCode, mt.MaterialTypeName ProductType,
ols.OrderLineStatusCode, olsi.OrderLineStatusName InitialOrderLineStatus
FROM   OrderLines ol, OrderLineStatuses ols, Workcentres wc, Locations l, OrderBooks ob, Materials m, MaterialTypes mt,
OrderLineStatuses olsi
WHERE  ol.OrderBookId = ob.Id
AND    ol.OrderLineStatusId = ols.Id
AND    wc.Id = ol.WorkcentreId
AND    l.Id = ol.LocationId
AND   m.Id = ol.MaterialId
AND  mt.Id = m.MaterialTypeId
AND ol.InitialOrderLineStatusId = olsi.Id (+)
top
IE#Sku

   SELECT l.LocationCode Location, m.MaterialCode Product,
   MaterialTypeName, smu.LocationId, smu.MaterialId,  m.MaterialTypeId, eu.Id EndUseId,
   smu.Status Forecasted, Replenished, EndCustomerId,
   smu.Id
   FROM   SiteMaterialUsages smu
   JOIN   Materials m
   ON     (m.Id = smu.MaterialId)
   JOIN   Locations l
   ON     (l.Id = smu.LocationID)
   JOIN   MaterialTypes mt
   ON     (mt.Id = m.MaterialTypeId)
   LEFT JOIN   endUses eu
   ON     (eu.Id = smu.EndUseid)
   LEFT JOIN   Locations e
   ON     (e.Id = smu.EndCustomerID)


top
IE#SupercessionRules
SELECT sr.Id, TestCode, StartDate, Percentage, AutoCreateSku, HierarchyLevels, HierarchyCodes, Properties,
       FromPropertyCodes, ToPropertyCodes
FROM   SupercessionRules sr
top
IH#AllMaterialSupercessions
SELECT ms.Id,
ms.SiteMaterialUsageId, ms.OnSiteMaterialUsageId,
ms.TYPE, ms.SupercessionRuleId, ms.StartDate, ms.GeneratedFromId, ms.Percentage, ms.LevelNo, ms.DisableSupersededItems,
smut.LocationId ToLocationId,
lf.LocationName FromLocationName,
lf.LocationCode FromLocationCode,
lt.LocationName ToLocationName,
lt.LocationCode ToLocationCode,
fm.MaterialName FromMaterialName,
fm.MaterialCode FromMaterialCode,
euf.EndUseCode EndUseCodeFrom,
euf.EndUseDescription EndUseFrom,
tm.MaterialName ToMaterialName,
tm.MaterialCode ToMaterialCode,
eut.EndUseCode EndUseCodeTo,
eut.EndUseDescription EndUseTo,
fm.Id FromMaterialId,
tm.Id ToMaterialId,
ecf.LocationCode FromEndCustomerCode,
ect.LocationCode ToEndCustomerCode,
smuf.Status,
smut.Status TargetStatus
FROM (
SELECT ms.ID, ms.SiteMaterialUsageId, ms.OnSiteMaterialUsageId,
ms.TYPE, ms.SupercessionRuleId, ms.StartDate, ms.GeneratedFromId, ms.Percentage, ms.LevelNo, ms.DisableSupersededItems,
ROW_NUMBER() OVER(PARTITION BY OnSiteMaterialUSageId, SiteMaterialUSageId, StartDate ORDER BY StartDate) RankLevel
FROM MaterialSupercessions ms
WHERE Type IN ('Supersession', 'Both', 'ReplaceLocation')
AND NOT EXISTS (Select 1 from MaterialSupercessions ms2
WHERE ms2.SiteMaterialUsageId = ms.SiteMaterialUsageId
AND ms2.OnSiteMaterialUsageId = ms.OnSiteMaterialUsageId
AND ms2.Type = ms.Type
AND ms2.StartDate < ms.StartDate)
) ms
JOIN SiteMaterialUsages smuf ON (ms.SiteMaterialUsageId = smuf.Id)
JOIN SiteMaterialUsages smut ON (ms.OnSiteMaterialUsageId = smut.Id)
JOIN Locations lf on lf.Id = smuf.LocationId
JOIN Locations lt on lt.Id = smut.LocationId
JOIN Materials fm ON (fm.Id = smuf.MaterialId)
JOIN Materials tm ON (tm.Id = smut.MaterialId)
LEFT JOIN EndUses euf on euf.Id = smuf.EndUseId
LEFT JOIN EndUses eut on eut.Id = smut.EndUseId
LEFT JOIN Locations ecf on ecf.Id = NVL(smuf.EndCustomerId, smuf.LocationId)
LEFT JOIN Locations ect on ect.Id = NVL(smut.EndCustomerId, smut.LocationId)
WHERE RankLevel = 1
top
IH#AllMaterialUnits
SELECT m.Id MaterialId, UnitId, Dividend, Divisor
FROM Materials m
JOIN MaterialUnits mu ON mu.MaterialId = m.Id
UNION ALL
SELECT m.Id, u.Id, Dividend, Divisor
FROM Materials m CROSS JOIN IH#WeightUnits u
WHERE Dividend != -1
top
IH#AllocationBodies

SELECT a.SiteMaterialUsageId, DeliveryMonth, DeliveryWeek, NVL(l.CalendarId, dp.DefaultCalendarId) CalendarId,
Customer Allocation,
SUM(Customer) OVER (PARTITION BY SiteMaterialUsageId, DeliveryMonth) MonthlyAllocation
FROM (SELECT SiteMaterialUsageId, DeliveryMonth, DeliveryWeek, SUM(Customer) Customer
FROM Allocationbodies
GROUP BY SiteMaterialUsageId, DeliveryMonth, DeliveryWeek) a
JOIN sitematerialusages smu
ON smu.Id = a.Sitematerialusageid
JOIN locations l ON l.Id = smu.LocationId
CROSS JOIN IH#DefaultParameters dp
top
IH#AllocationForNetting

SELECT SiteMaterialUsageid, t.workcentreId, wc.SiteId, SourceWeek, SourceMonth, ConversionFactor, SUM(Allocation) Allocation, SUM(Orders) Orders,
       SUM(DECODE(WorkcentreTypeName, 'Paper Machine', Allocation, 0)) ApplicableAllocation,
       SUM(DECODE(WorkcentreTypeName, 'Paper Machine', Orders, 0)) ApplicableOrders
FROM   (SELECT ab.SiteMaterialUsageId, ab.WorkcentreId, ab.SourceWeek, ab.SourceMonth, Customer Allocation, 0 Orders, NVL(r.ConversionFactor, 1) ConversionFactor
         FROM   AllocationBodies ab
        JOIN SitematerialUsages smu
        ON smu.id = ab.SiteMaterialUsageId
         LEFT   JOIN IVBS#ActualProductionRates r
         ON r.WorkcentreId = ab.Workcentreid
         AND r.MaterialId = smu.MaterialId
         UNION ALL
         SELECT ol.SiteMaterialUsageId, ol.WorkcentreId, TRUNC(NVL(ConsumptionDate, DespatchDate), 'IW') SourceWeek,
                TRUNC(NVL(ConsumptionDate, DespatchDate), 'month') SourceMonth, 0 Allocation, FinalWeight  Orders, NVL(ConversionFactor, 1) ConversionFactor
         FROM   OrderLines ol
         JOIN   OrderLineStatuses OLs
         ON     ols.Id = ol.OrderLineStatusId
         LEFT   JOIN IVBS#ActualProductionRates r
				   ON r.WorkcentreId = ol.Workcentreid
					 AND r.MaterialId = ol.MaterialId
         WHERE  ols.OrderLineStatusCode IN ('Firm', 'Completed')) t
JOIN   IH#Workcentres wc
ON     wc.WorkcentreId = t.WorkcentreId
GROUP  BY SiteMaterialUsageid, t.workcentreId, wc.SiteId, SourceWeek,
          SourceMonth, ConversionFactor
top
IH#AllocationReasons
SELECT * from Reasons Where ReasonType = 'Allocation'
top
IH#AreaPageActions

WITH p AS (
           SELECT Id, PageDescription, RTRIM(REPLACE(LTRIM(SYS_CONNECT_BY_PATH(PageDescription, ' / '), ' / '), PageDescription, ''), ' / ') PagePath,
		   Cloud
           FROM   pages p
           WHERE  Cloud > 0
		   AND CONNECT_BY_ISLEAF = 1
           CONNECT BY PRIOR Id = CloudParentPageId
           START  WITH ID IN (SELECT ID
                              FROM   Pages
                              WHERE  Cloud > 0
                              AND    CloudParentPageId IS NULL)
           ORDER  SIBLINGS BY Cloud
)
SELECT a.Id, p.PagePath, PageDescription, NVL(a.Title, a.ActionDescription) Description, a.ActionHint ActionDescription
FROM   (SELECT * FROM Actions WHERE IsDefault = 0) a
JOIN   p
ON     (p.Id = a.PageId)
Order by p.PagePath, PageDescription,  NVL(a.Title, a.ActionDescription)

top
IH#BaseUnits
SELECT u.Id UnitId, u.UnitTypeId, ut.UnitTypeName, u.UnitName, u.UnitDescription, u.IsBaseUnit, u.MaterialTypeId
FROM Units u JOIN UnitTypes ut ON ut.Id = u.UnitTypeId
WHERE IsBaseUnit = 1
top
IH#BOMMaterials
SELECT b.Id, b.BomCode, dm.MaterialCode, dm.MaterialName, sm.MaterialCode SourceMaterialcode, sm.MaterialName SourceMaterialName, bm.Multiplier, bm.Divider,
dm.MaterialId MaterialId, sm.MaterialId SourceMaterialId, dm.MaterialTypeName, sm.MaterialTypeName SourceMaterialTypeName
FROM BOm b
JOIN Productionconfigurations pc ON pc.bomId = b.Id
JOIN Materialpropsspec dm ON pc.MaterialId = dm.MaterialId
JOIN BOMMaterials bm ON bm.bomId = b.Id
JOIN Materialpropsspec sm ON sm.MaterialId = bm.MaterialId


top
IH#BomSku
SELECT f.MaterialCode FromMaterialCode, f.MaterialName FromMaterialName,
t.MaterialCode ToMaterialCode, t.MaterialName ToMaterialName,
l.LocationName, l.LocationCode, wc.LocationCode SourceLocationCode,
wc.LocationId SourceLocationId, wc.WorkcentreId,
fsmu.Replenished FromReplenished,
tsmu.Replenished TOReplenished,
fsmu.Id FromSiteMaterialUsageId,
tsmu.Id ToSiteMaterialUsageId,
bom.*
FROM Billofmaterials bom
JOIN Materials f ON bom.Frommaterialid = f.Id
JOIN Materials t ON bom.tomaterialid = t.Id
JOIN Locations l ON l.Id = bom.LocationId
JOIN IH#Workcentres wc ON wc.SiteId = l.SiteId
    AND wc.WorkcentreTypeName = 'Warehouse'
    AND bom.LocationId != wc.LocationId
JOIN SiteMaterialUsages tsmu ON tsmu.LocationId = bom.LocationId AND tsmu.MaterialId = t.Id
JOIN SiteMaterialUsages fsmu ON fsmu.LocationId = wc.LocationId AND fsmu.MaterialId = f.Id
top
IH#BSODemandAnalysis
SELECT OperatorUserId, WorkCentreId, GradeId, OrdersWeight, OrdersDuration, 
       OriginalAllocationsWeight, OriginalAllocationsDuration, RemainingAllocationsWeight, RemainingAllocationsDuration,
       NVL(NominalDuration,-1) NominalDuration, NVL(AdjustedDuration,-1) AdjustedDuration,
       OptimizedDuration, OptimizedWeight
  FROM (
          SELECT OperatorUserId, WorkCentreId, GradeId,
                 sum(OrdersWeight) as OrdersWeight,
                 sum(OrdersDuration) as OrdersDuration,
                 sum(OriginalAllocationsWeight) as OriginalAllocationsWeight,
                 sum(OriginalAllocationsDuration) as OriginalAllocationsDuration,
                 sum(RemainingAllocationsWeight) as RemainingAllocationsWeight,
                 sum(RemainingAllocationsDuration) as RemainingAllocationsDuration,                     
                 sum(NominalDuration) as NominalDuration,
                 SUM(AdjustedDuration) AS AdjustedDuration,
                 sum(OptimizedDuration) as OptimizedDuration,
                 SUM(OptimizedWeight) AS OptimizedWeight
            FROM (
                   SELECT OperatorUserId, i.WorkCentreId, i.GradeId, 
                          DECODE(i.OrderLineId, 0, 0, i.RemainingWeight) OrdersWeight,
                          DECODE(i.OrderLineId, 0, 0, i.RemainingDuration) OrdersDuration,
                          DECODE(i.OrderLineId, 0, i.OriginalWeight, 0) OriginalAllocationsWeight,
                          DECODE(i.OrderLineId, 0, i.OriginalDuration, 0) OriginalAllocationsDuration,
                          DECODE(i.OrderLineId, 0, i.RemainingWeight, 0) RemainingAllocationsWeight,
                          DECODE(i.OrderLineId, 0, i.RemainingDuration, 0) RemainingAllocationsDuration,
                          NULL NominalDuration, NULL AdjustedDuration,
                          0 OptimizedDuration, 0 OptimizedWeight
                     FROM IH#BSOInput i
                    WHERE i.IsLiveRun = 0
                    UNION ALL 
                   SELECT w.OperatorUserId, p.WorkCentreid, p.GradeId, 0, 0, 0, 0, 0, 0, NominalDuration, AdjustedDuration, 0, 0
                     FROM IH#BSOPrograms p
                     JOIN BSOWorkCentreData w ON w.WorkCentreId = p.WorkCentreId
                    UNION ALL
                   SELECT w.OperatorUserId, r.WorkCentreId, r.GradeId, 
                          0, 0, 0, 0, 0, 0, NULL, NULL,
                          r.InitialDuration - r.SwitchoverDuration, 
                          (r.InitialDuration - r.SwitchoverDuration) / 60 * NVL(r.Rate,0)
                     FROM OptimizedRuns r
                     JOIN BSOWorkCentreData w ON w.WorkCentreId = r.WorkCentreId
                    WHERE r.CampaignType = 1
                      AND r.IsLiveRun = 0
                      AND r.FsBlock = 0
                      AND r.OppBlock = 0
                      AND r.IsShut = 0
                 )
           GROUP BY OperatorUserId, WorkCentreId, GradeId
       ) t
 WHERE t.GradeId IS NOT NULL
top
IH#BSOGenerationPeriod
WITH params AS 
( 
    SELECT NVL(MAX(Value), 'NoRestriction') DemandDurationBehaviour, 
           core.getInternalDate InternalDate,
           to_date('01-01-2050', 'DD-MM-YYYY') MaxDate
      FROM SystemParameters
     WHERE ParameterName = 'BSODemandDurationBehaviour'
),
dates AS 
(
  SELECT OperatorUserId, WorkCentreId, 
         MIN(StartDate) StartDate, MAX(DemandDate) DemandDate, MAX(FinishDate) RunDate
    FROM (
           SELECT OperatorUserId, WorkCentreId, DateFrom DemandDate, NULL StartDate, NULL FinishDate
             FROM BSOOrdersData
            WHERE IsLiveRun = 0
            UNION ALL
           SELECT OperatorUserId, WorkCentreId, DECODE(LiveAllocationPeriod, 'Month', last_day(DateFrom), DateFrom + 7) DemandDate, NULL StartDate, NULL FinishDate
             FROM BSOAllocationData
             CROSS JOIN (SELECT Value LiveAllocationPeriod FROM SystemParameters WHERE ParameterName = 'LiveAllocationPeriod')
            WHERE IsLiveRun = 0
            UNION ALL 
           SELECT w.OperatorUserId, p.WorkCentreId, NULL, MIN(p.StartDate) StartDate, MAX(p.FinishDate) FinishDate
             FROM BSOPrograms p
             JOIN BSOWorkCentreData w ON w.WorkCentreId = p.WorkCentreId
			GROUP BY w.OperatorUserId, p.WorkCentreId
         ) d
   GROUP BY OperatorUserId, WorkCentreId          
          
)
SELECT OperatorUserId, WorkCentreId, NVL(StartDate, params.InternalDate) StartDate,
       NVL(CASE DemandDurationBehaviour
                WHEN 'OnlyConsiderDemands' THEN DemandDate
                WHEN 'OnlyConsiderRuns' THEN RunDate
                WHEN 'OnlyConsiderDemandsOrRuns' THEN LEAST(DemandDate, RunDate)
                WHEN 'NoRestriction' THEN params.MaxDate
            END, params.MaxDate) FinishDate
  FROM dates
 CROSS JOIN params
top
IH#BSOGroupingProperties

SELECT DISTINCT GradeId, pv.PropertyValueCode GroupProperties
FROM ExpandedMaterials em JOIN GradeMaterials gm
ON em.MaterialId = gm.MaterialId
JOIN PropertyValues pv ON pv.Id = em.PropertyValueID
JOIN Properties p ON p.Id = pv.PropertyId
WHERE p.PropertyName = (SELECT MIN(VALUE) FROM SystemParameters WHERE ParameterName = 'BSOGroupingProperty')

top
IH#BSOInput
SELECT i.OperatorUserId, i.WorkCentreId, i.DateFrom + 12/24 DateFrom, i.GradeId, i.FinishingId,
       i.OriginalDuration, i.OriginalWeight, i.RemainingDuration, i.RemainingWeight, i.Priority, i.OrderLineId, i.Rate, i.IsLiveRun,
       i.OperationTypeId, i.NextWorkcentreId, i.NextOperationTypeId, i.NextSourcePeriod, i.NextWeight, i.NextCoef, DemandControlAllocationWeight,
       TRUNC(p.StartDate) StartDate, TRUNC(p.FinishDate) FinishDate
  FROM (
         SELECT OperatorUserId, o.WorkCentreId, o.DateFrom, o.GradeId, o.FinishingId,
                o.Duration OriginalDuration, o.Weight OriginalWeight, o.Duration RemainingDuration, o.Weight RemainingWeight,
                99 Priority, o.OrderLineId, o.Rate, o.IsLiveRun, OperationTypeId, NextWorkcentreId, NULL NextSourcePeriod, NextOperationTypeId, NULL NextWeight, NULL NextCoef,
                0 DemandControlAllocationWeight
           FROM BSOOrdersData o
          WHERE o.Duration > 0
          UNION ALL
         SELECT OperatorUserId, a.WorkCentreId, a.DateFrom + t.Id DateFrom, a.GradeId, a.FinishingId,
                a.Duration/7 OriginalDuration, a.Duration * Rate/60/7 OriginalWeight,
                a.RemainingDuration/7 RemainingDuration, a.RemainingDuration * Rate/60/7 RemainingWeight,
                a.Priority, 0 OrderLineId, a.Rate, a.IsLiveRun, a.OperationTypeId, a.NextWorkcentreId,
                a.NextSourcePeriod, a.NextOperationTypeId, a.NextWeight / 7 NextWeight, a.NextCoef,
                a.OriginalWeight / 7 DemandControlAllocationWeight
           FROM BSOAllocationData a, (SELECT Level - 1 Id FROM dual CONNECT BY level <= 7) t
          WHERE a.Duration > 0
            AND EXISTS (SELECt 1 FROM SystemParameters WHERE ParameterName = 'LiveAllocationPeriod' And Value IN ('Week', 'WeekMonth'))
            UNION ALL
         SELECT OperatorUserId, a.WorkCentreId, t.DateFrom DateFrom, a.GradeId, a.FinishingId,
                a.Duration/DaysInMonth OriginalDuration, a.Duration * Rate/60/DaysInMonth OriginalWeight,
                a.RemainingDuration/DaysInMonth RemainingDuration, a.RemainingDuration * Rate/60/DaysInMonth RemainingWeight,
                a.Priority, 0 OrderLineId, a.Rate, a.IsLiveRun, a.OperationTypeId, a.NextWorkcentreId,
                a.NextSourcePeriod, a.NextOperationTypeId, a.NextWeight / DaysInMonth NextWeight, a.NextCoef,
                a.OriginalWeight / DaysInMonth DemandControlAllocationWeight
           FROM BSOAllocationData a JOIN (
                  SELECT DateFrom, DateFromMonth, CAST(TO_CHAR(LAST_DAY(DateFromMonth), 'DD') AS INT) DaysInMonth
                  FROM   CalendarSources
                  WHERE  CalendarId = (SELECT VALUE FROM SystemParameters WHERE ParameterName = 'DefaultCalendar')
                  ) t
           ON TRUNC(a.DateFrom, 'month') = t.DateFromMonth
          WHERE a.Duration > 0
          AND EXISTS (SELECt 1 FROM SystemParameters WHERE ParameterName = 'LiveAllocationPeriod' And Value IN ('Month'))
       ) i
  JOIN IH#BSOGenerationPeriod p
    ON i.WorkCentreId = p.WorkCentreId
   AND i.OperatorUserId = p.OperatorUserId
   AND i.DateFrom BETWEEN TRUNC(p.StartDate) AND TRUNC(p.FinishDate)
top
IH#BSOPrograms
SELECT p.Id, p.WorkCentreId, g.SequenceNo, g.GradeId, 
       NVL(g.Duration * GREATEST(0, SUM(g.Duration) OVER (PARTITION BY p.Id) - p.ShutLength) / NULLIF(SUM(g.Duration) OVER (PARTITION BY p.Id),0),0) NominalDuration,
       NVL(g.Duration * GREATEST(0, p.DurationAdj - p.ShutLength) / NULLIF(SUM(g.Duration) OVER (PARTITION BY p.Id),0),0) AdjustedDuration
  FROM BSOPrograms p 
  JOIN BSOProgramGrades g ON g.BSOProgramId = p.Id
 ORDER BY g.SequenceNo 
top
IH#Bundles
SELECT b.Name, bv.* FROM Bundles b JOIN bundleValues bv ON bv.Bundleid = b.Id
top
IH#CalendarDailyCoefs
SELECT CalendarId, TO_char(last_day(DateFrom), 'DD') Day, DateFrom, MonthDate, WeekDate, IsWorkingDay,
DECODE(MonthSum, 0, 0, WeekSum / MonthSum) AS Coef, WeekSum, MonthSum,
TO_char(last_day(DateFrom), 'DD') TotalDays
FROM   (
SELECT  CalendarId, DateFrom, DateFromMonth AS MonthDate, DateFromIW AS WeekDate, IsWorkingDay,
SUM(IsWorkingDay) over(PARTITION BY CalendarId, DateFromMonth, DateFromIW) AS WeekSum,
SUM(IsWorkingDay) over(PARTITION BY CalendarId, DateFromMonth) AS MonthSum
FROM   CalendarSources cs)
top
IH#CalendarWeeklyCoefs
SELECT c.*, SUM(WeekMonthCoef) OVER (PARTITION BY CalendarId, WeekDate) totalWeekCoef
 FROM
(
SELECT DISTINCT CalendarId, DateFromMonth MonthDate, DateFromIW WeekDate, WeekMonthCoef
FROM CalendarSources
) c

top
IH#CalendarWeekMonthSources Coefficients for weekly/month periods.

    SELECT CalendarId,
       CASE
           WHEN DateFromIW > DateFromMonth THEN
            DateFromIW
           ELSE
            DateFromMonth
       END DateFrom, SUM(IsWorkingDay) WorkingDays, SUM(1) TotalDays,
       DECODE(SUM(1), 7, 1, SUM(IsWorkingDay) / MIN(WeekWorkingDays)) PeriodCoef
FROM   (SELECT CalendarId, DateFrom, DateFromIW, DateFromMonth, IsWorkingDay,
                SUM(IsWorkingDay) OVER(PARTITION BY CalendarId, DateFromIW) WeekWorkingDays
         FROM   CalendarSources)
GROUP  BY CalendarId,
          CASE
              WHEN DateFromIW > DateFromMonth THEN
               DateFromIW
              ELSE
               DateFromMonth
          END
top
IH#CompanyGradeSafetyStock
SELECT c.CompanyName, m.MaterialName, m.MaterialCode, gp.GradeCode, DateFrom, SafetyStock
FROM inventoryprofiles ip JOIN
Companies c ON ip.companyId = c.Id
JOIN materials m ON m.Id = ip.MaterialId
JOIN GradeMaterials gm ON gm.MaterialID = m.Id
JOIN Gradeproperties gp ON gp.GradeId = gm.GradeId
top
IH#CompanySafetyStocks
        SELECT c.CompanyName, m.MaterialName, m.MaterialCode, ip.ConsignmentLocationId, gp.GradeCode, DateFrom, SafetyStock,
        core.AsCsv(SET(CAST(COLLECT(DISTINCT ssm.Safetystockmethodname ORDER BY ssm.Safetystockmethodname) AS
        ParameterArray))) SafetyStockMethods, MIN(LowQuantity) minLowQuantity,
        MIN(HighQuantity) MinHighQuantity, COUNT(1) SkuQuantity,
        core.AsCsv(SET(CAST(COLLECT(DISTINCT to_char(LowQuantity)) AS ParameterArray))) LowQuantityValues,
        core.AsCsv(SET(CAST(COLLECT(DISTINCT to_char(HighQuantity)) AS ParameterArray))) HighQuantityValues
        FROM   inventoryprofiles ip
        JOIN   Companies c
        ON     ip.companyId = c.Id
        JOIN   materials m
        ON     m.Id = ip.MaterialId
        JOIN   GradeMaterials gm
        ON     gm.MaterialID = m.Id
        JOIN   Gradeproperties gp
        ON     gp.GradeId = gm.GradeId
        JOIN   Locations l
        ON     l.CompanyId = c.Id
        JOIN   IH#Skus smu
        ON     smu.LocationId = l.ID
        AND    smu.MaterialId = m.Id
        AND    NVL(smu.ConsignmentLocationId, 0) = NVL(ip.ConsignmentLocationID,0)
        CROSS  JOIN Ih#defaultparameters p
        JOIN   Safetystockmethods ssm
        ON     ssm.Id =
        COALESCE(c.Safetystockmethodid, l.SafetyStockMethodId, smu.SafetyStockMethodId, p.DefaultSafetyStockMethodId)
        WHERE  smu.Replenished = 1
        GROUP  BY c.CompanyName, m.MaterialName, m.MaterialCode, ip.ConsignmentLocationId, gp.GradeCode, DateFrom, SafetyStock
top
IH#ConfigurationConversions
SELECT c.SnapshotUserId, c.Id, c.ProductionConfigurationId, prs.OperationtypeId, prs.OrderNo StageNo,
       NVL(Multiplier, 1) Multiplier, NVL(Divider, 1) Divider
FROM   (SELECT SnapshotUserId, Id, MIN(ProductionConfigurationId) ProductionConfigurationId
         FROM   ConfigurationSnapshots
         GROUP  BY SnapshotUserId, ID) c
JOIN   ProductionConfigurations pc
ON     pc.Id = c.ProductionConfigurationId
JOIN   ProductRouteStages prs
ON     prs.ProductRouteId = pc.ProductRouteId
LEFT   JOIN OperationTypeConversions otc
ON     otc.OperationTypeid = prs.OperationTypeId
AND    pc.Id = otc.ProductionConfigurationId
top
IH#ConfigurationOperations
SELECT pc.Id ProductionConfigurationId, pc.ProductRouteId, prs.OperationTypeId, ot.WorkcentreTypeId,
       prs.OrderNo StageNo,
       SUM(1) OVER(PARTITION BY pc.Id, pc.ProductRouteId) OperationsQuantity
  FROM ProductionConfigurations pc
  JOIN Productroutestages prs
    ON pc.ProductRouteId = prs.ProductRouteId
  JOIN OperationTypes OT 
    ON ot.Id = prs.OperationtypeId
top
IH#ConfigurationSources

SELECT t.ProductionConfigurationId, t.ProductRouteId, SiteMaterialUsageId, LocationId, Materialid, t.OperationTypeId,
       ValidSources, PrimaryValidSources, BomId, r.OrderNo, NVL(c.IsLastCoProductStage,0) IsLastCoProductStage,
       NVL(Multiplier,1) Multiplier,
       NVL(divider,1) Divider, InputUnitId, OutputUnitId,
       r.IsLastStage,
       NVL(Multiplier,1) || '^' || InputUnitId || '/' || NVL(divider,1) || '^' || OutputUnitId || '-' || NVL(c.IsLastCoProductStage,0) ConversionHash
FROM
(
SELECT pc.Id ProductionConfigurationId, pc.ProductRouteId, smu.Id SiteMaterialUsageId, smu.LocationId, pc.Materialid, prs.OperationTypeId,
       ValidSources, PrimaryValidSources, pc.BomId
FROM   IH#Productionconfigurations pc
JOIN   IH#ProductRoutes pr
ON     pr.Id = pc.Productrouteid
JOIN   IH#Productroutestages prs
ON     prs.ProductRouteId = pr.Id
LEFT   JOIN IH#ValidSources vs
ON     vs.Productionconfigurationid = pc.Id
AND    vs.OperationTypeId = prs.OperationTypeId
JOIN   SiteMaterialUsages smu
ON     smu.MaterialId = pc.materialId
WHERE  NOT EXISTS (SELECT 1
        FROM   InitialSources s
        WHERE  s.Sitematerialusageid = smu.Id
       AND    (SELECT NVL(MIN(to_number(VALUE)),0) FROM SystemPArameters WHERE ParameterName = 'SNPInitialSources') = 1
           OR s.OperationTypeId = prs.OperationTypeId)
UNION ALL
SELECT pc.Id, pc.ProductRouteId, SiteMaterialUsageId, smu.LocationId, pc.Materialid, s.OperationTypeId,
core.AsCsv(CAST(COLLECT(to_char(s.WorkcentreId) ORDER BY s.WorkcentreId) AS ParameterArray)) ValidSources,
core.AsCsv(CAST(COLLECT(to_char(s.WorkcentreId) ORDER BY s.WorkcentreId) AS ParameterArray)) PrimaryValidSources,
pc.BomId
FROM InitialSources s
JOIN SiteMaterialUsages smu
ON smu.Id = s.SiteMaterialUsageId
JOIN ProductionConfigurations pc
ON pc.MaterialId = smu.MAterialId
AND NOT EXISTS(SELECT 1 From ValidSources vs
              WHERE vs.ProductionConfigurationId = pc.Id
              AND s.OperationTypeId = vs.OperationTypeID)
group by pc.Id, pc.ProductRouteId, SiteMaterialUsageId, smu.LocationId, pc.Materialid, s.OperationTypeId, pc.BomId

UNION ALL

SELECT pc.Id, pc.ProductRouteId, SiteMaterialUsageId, smu.LocationId, pc.Materialid, s.OperationTypeId,
core.AsCsv(CAST(COLLECT(to_char(s.WorkcentreId) ORDER BY s.WorkcentreId) AS ParameterArray)) ValidSources,
core.AsCsv(CAST(COLLECT(to_char(s.WorkcentreId) ORDER BY s.WorkcentreId) AS ParameterArray)) PrimaryValidSources,
pc.BomId
FROM InitialSources s
JOIN SiteMaterialUsages smu
ON smu.Id = s.SiteMaterialUsageId
JOIN ProductionConfigurations pc
ON pc.MaterialId = smu.MAterialId
JOIN ValidSources vs
ON vs.ProductionConfigurationId = pc.Id
AND vs.OperationTypeId = s.OperationTypeId
AND vs.WorkcentreId = s.WorkcentreId
group by pc.Id, pc.ProductRouteId, SiteMaterialUsageId, smu.LocationId, pc.Materialid, s.OperationTypeId, pc.BomId
) t

LEFT JOIN Operationtypeconversions c
ON c.ProductionConfigurationId = t.ProductionConfigurationId
AND c.OperationtypeId = t.OperationtypeId

JOIN IH#ProductRouteStages r
ON r.ProductRouteId  = t.ProductRouteId
AND r.OperationTypeId = t.OperationTypeId

Order by SiteMaterialUsageId
top
IH#ConsumptionProfiles
SELECT SiteMaterialUsageId, ConsignmentLocationId, DateFrom,
First_value(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(FirmOrdersIn + TentativeOrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0)
              - NVL(SUM(ConsumptionForecast + TentativeOrdersOut + ConsumptionOrders) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) Opening,
FirmOrdersIn, TentativeOrdersIn, Consumption, TentativeOrdersOut, ConsumptionOrders, ConsumptionForecast, PlannedInventory,
     First_value(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(FirmOrdersIn + TentativeOrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND p.ClosingMethod PRECEDING),0)
              - NVL(SUM(ConsumptionForecast + TentativeOrdersOut + ConsumptionOrders) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING),0) Closing


FROM InventoryProfiles ip
CROSS JOIN (SELECT UseTentativeOrders, DECODE(RPClosingCalculationMethod, 'AfterDeliveryDate', 1, 0) ClosingMethod FROM IH#ReplenishmentParameters) p
/*WHERE ip.SiteMaterialUsageId =2*/
ORDER BY DateFrom
top
IH#ConvertedExchangeRates
SELECT er.DateFrom, er.DateTo, er.Currencyid FromCurrencyId, er2.CurrencyId ToCurrencyId,
 er.Multiplier FromMultiplier, er.Divider FromDivider,
er2.Multiplier ToMultiplier, er2.Divider TODivider
FROM   ExpandedExchangeRates er
JOIN   ExpandedExchangeRates er2
ON     er.DateFrom BETWEEN er2.DateFrom AND er2.DateTo  
top
IH#CoProductLists
SELECT MaterialId, SUM(Percentage) Percentage,
core.asCsv(CAST(COLLECT(CoProductMaterialId || ':' || Percentage ORDER BY CoProductMaterialId) AS PArameterArray), ';') CoProductList
FROM CoProducts
GROUP BY MaterialId

top
IH#CustomerAdditiveConsumption
SELECT p.SiteMaterialUsageId, p.ConsignmentLocationId, p.SourceSiteMaterialUsageId,
       NVL2(p.SiteMaterialUsageId, p.SiteMaterialUsageId || '-' || NVL(p.ConsignmentLocationId, 0), '') SkuKey,
       NVL2(p.SourceSiteMaterialUsageId, p.SourceSiteMaterialUsageId || '-' || NVL(p.ConsignmentLocationId, 0), '') SourceSkuKey,
       a.DateFrom, a.Forecast, Demand, Orders, NettedOrders, Portion, TotalTimePeriod, IsDirect, Consumption,
       p.DateFrom SourcingStartDate, p.DateTo SourcingFinishDate,
       CASE
           WHEN a.DateFrom BETWEEN p.DateFrom AND p.DateTo THEN
            a.Consumption * (p.Portion / 100)
           ELSE
            NULL
       END PortionConsumption,
       LEAD(CASE
                WHEN a.DateFrom BETWEEN p.DateFrom AND p.DateTo THEN
                 a.Consumption * (p.Portion / 100)
                ELSE
                 NULL
            END, TotalTimePeriod, 0) OVER(PARTITION BY p.SiteMaterialUsageId, p.ConsignmentLocationId, p.SourceSiteMaterialUsageId ORDER BY a.DateFrom) WarehouseConsumption
FROM   IH#EndPointSkuPortions p
JOIN   ReplenishedCustomerDemands a
ON     a.Sitematerialusageid = p.SiteMaterialUsageId
ORDER  BY 1, 3, 4
top
IH#CustomerEndConsumption

SELECT p.SiteMaterialUsageId, p.ConsignmentLocationId, p.SourceSiteMaterialUsageId,
NVL2(p.SiteMaterialUsageId, p.SiteMaterialUsageId || '-' || NVL(p.ConsignmentLocationId, 0), '') SkuKey,
NVL2(p.SourceSiteMaterialUsageId, p.SourceSiteMaterialUsageId || '-' || NVL(p.ConsignmentLocationId, 0), '') SourceSkuKey,
a.DateFrom, a.Forecast, Demand, Orders, NettedOrders,
Portion, TotalTimePeriod, IsDirect, Consumption, p.DateFrom SourcingStartDate, p.DateTo SourcingFinishDate,
CASE WHEN a.DateFrom BETWEEN p.DateFrom AND p.DateTo THEN a.Consumption * (p.Portion / 100) ELSE NULL END PortionConsumption,
LEAD(CASE WHEN a.DateFrom BETWEEN p.DateFrom AND p.DateTo THEN a.Consumption * (p.Portion / 100) ELSE NULL END, TotalTimePeriod, 0)
OVER(PARTITION BY p.SiteMaterialUsageId, p.ConsignmentLocationId, p.SourceSiteMaterialUsageId
ORDER BY a.DateFrom) WarehouseConsumption
FROM   IH#EndPointSkuPortions2 p
JOIN ReplenishedCustomerDemands a
ON   a.Sitematerialusageid = p.SiteMaterialUsageId
ORDER BY 1,3,4
top
IH#CustomerSkuCalendars

SELECT smu.Id SiteMaterialUsageId, smu.LocationId, smu.MaterialId, NULL ConsignmentLocationId, EndUseId,
NVL(EndCustomerId, LocationId) EndCustomerId, NVL(ccl.CalendarId, p.DefaultCalendarId) CalendarId
FROM   SiteMaterialUsages smu
CROSS  JOIN IH#DefaultParameters p
JOIN   Locations ccl
ON     (smu.LocationId = ccl.Id)
JOIN   Companies c
ON     (c.Id = ccl.CompanyID)
AND    NOT EXISTS (SELECT * FROM workcentres wc WHERE wc.LocationId = smu.LocationId)

top
IH#CustomerSkus

SELECT smu.Id SiteMaterialUsageId, EndUseId, NVL(EndCustomerId, LocationId) EndCustomerId,
       MaterialId, LocationId, smu.Status, smu.TurnOffForecastId, smu.TurnOnForecastid, smu.NeedCheckForecastId,
       smu.AlternateProduct, smu.ExistingAlternateProduct, 
       NVL(smu.UpperPercentile, p.DefaultSKUUpperPercentile) UpperPercentile, NVL(smu.LowerPercentile, p.DefaultSKULowerPercentile) LowerPercentile,
       smu.ForecastStartDate, smu.ForecastFinishDate, NVL(smu.ForecastMethodId, DefaultForecastMethodId) ForecastMethodId,
       DECODE(smu.DefaultCustomerForecast, 'NotSet', l.DefaultCustomerForecast, smu.DefaultCustomerForecast) DefaultCustomerForecast,
       smu.HistoryStartDate, smu.ReplenishmentFlag, cr.Id CustomerRankId, cr.CustomerRankDesc, smu.SourceListId, 
       NVL(smu.NettingAlgorithm, p.DefaultNettingAlgorithm) NettingAlgorithm,
       smu.SkuProperty1, smu.SkuProperty2, smu.SkuProperty3, smu.SkuProperty4, smu.SkuProperty5, smu.SkuProperties,
       smu.InhibitProduction, smu.InhibitSFGSearch, NVL(smu.DDQContingency, 0) DDQContingency,
       NVL(smu.MaxCapacity,0) MaxCapacity,
       ep.Price,
       ep.CurrencyId,
       smu.SkuKey, ConsumptionType
  FROM SiteMaterialUsages smu
  JOIN Locations l ON l.Id = smu.LocationId
  JOIN Companies c ON c.Id = l.CompanyId
  JOIN Materials m ON m.Id = smu.MaterialId
  LEFT JOIN EndUses eu ON eu.Id = smu.EndUseId
  LEFT JOIN Locations ec ON ec.Id = smu.EndCustomerId
  CROSS JOIN IH#DefaultParameters p
  LEFT JOIN CustomerRanks cr ON COALESCE(smu.CustomerRankId, l.CustomerRankId, c.CustomerRankId, p.DefaultCustomerRankId) = cr.Id
  LEFT JOIN IH#ExpandedPrices ep ON (ep.SiteMaterialUsageId = smu.Id AND core.getTruncatedInternalDate between ep.DateFrom and ep.DateTo)
  WHERE NOT EXISTS(SELECT 1 FROM WorkCentres w WHERE w.LocationId = smu.LocationId)
top
IH#CustomerSourcePriorities

SELECT sp.Id, sp.SiteMaterialUsageId, sp.DestinationLocationId, sp.DestinationMaterialId,
       sp.SourceSiteMaterialUsageId, sp.SourceLocationId, sp.SourceMaterialId,
       DECODE(sp.IsConsignmentStock, 0, sp.ConsignmentLocationId, sp.DestinationLocationId) ConsignmentLocationId,
       sp.WorkCentreId, sp.Priority, sp.Portion, sp.SourcePriorityRuleId, sp.JourneyId, sp.MaterialTypeId,
       sp.IsConsignmentStock, sp.RPJourneyId, sp.DateFrom, sp.DateTo, s.Replenished
  FROM SourcePriorities sp
  JOIN (SELECT ID AS SiteMaterialUsageId, NULL CustomerId, Replenished
          FROM SiteMaterialUsages smu
         UNION ALL
        SELECT SiteMaterialUsageId, CustomerId, Replenished
          FROM ConsignmentParameters cp) s
    ON s.SiteMaterialUsageId = sp.SourceSiteMaterialUsageId
   AND NVL(s.CustomerId,0) = DECODE(sp.IsConsignmentStock, 0, NVL(sp.ConsignmentLocationId,0), sp.DestinationLocationId)
 WHERE sp.Priority = 1
   AND EXISTS(SELECT 1 FROM SiteMaterialUsages smu WHERE smu.Id = sp.SiteMaterialUsageId AND smu.Status = 1)
   AND NOT EXISTS(SELECT 1 FROM WorkCentres w WHERE w.LocationId = sp.ConsignmentLocationId)
top
IH#CycleAvailableDuration

SELECT wc.SiteId, mr.WorkcentreId, ct.CycleTypeId, wc.WorkcentreTypeId, wc.WorkcentreTypeName,
WorkcentreName, SiteName, CycleType,
TRUNC(mr.StartDate, 'IW') DateFrom, SUM(AvailableDuration) AvailableDuration
FROM   IH#RunAvailableDuration mr
JOIN   MaterialRunProducts mrp
ON     mrp.MaterialRunId = mr.Id
JOIN   IH#Workcentres wc
ON     mr.WorkcentreId = wc.WorkcentreId
JOIN   IH#CycleTypes ct
ON     ct.DetailId = mrp.DetailId
GROUP BY wc.SiteId, mr.WorkcentreId, ct.CycleTypeId, wc.WorkcentreTypeId, wc.WorkcentreTypeName,
WorkcentreName, SiteName, CycleType, TRUNC(mr.StartDate, 'IW')

top
IH#CycleFixedPeriods
WITH p AS
(
     SELECT Trunc(MAX(core.getInternalDate), 'IW') StartWeek FROM dual 
)
SELECT ct.CycleTypeId, 
       ct.CycleType, 
       ct.DetailId, 
       p.StartWeek,
       p.StartWeek + ct.FixedPeriodInWeeks * 7 CycleFixedPeriodWeek,
       ct.Frequency, 
       ct.WeekTolerance, 
       ct.Priority, 
       ct.ProducingDay, 
       ct.GroupName, 
       ct.FixedPeriodInWeeks
  FROM IH#CycleTypes ct
 CROSS JOIN p
top
IH#CycleProductionPeriods
WITH p AS 
    (
    SELECT MAX(core.getInternalDate) StartDate, NVL(MAX(mr.FinishDate), MAX(core.getInternalDate)) FinishDate
      FROM (SELECT MAX(FinishDate) FinishDate FROM MaterialRuns) mr
    )  
    SELECT DateWeek StartPeriod, 
           DateWeek + 7 EndPeriod, 
           ROW_NUMBER() OVER(Order by DateWeek) - 1 PeriodNumber, 
           7 PeriodLength
      FROM (SELECT DISTINCT TRUNC(Column_value, 'IW') DateWeek
              FROM TABLE((SELECT core.DateGenerator(p.StartDate, p.FinishDate) FROM p))
           )
top
IH#CycleTypeMaterials

SELECT CycleTypeId, MaterialId, DetailId
FROM
(
 SELECT ct.Id CycleTypeId, m.MaterialId, m.DetailId,
       DENSE_RANK() OVER (PARTITION BY ct.Id, m.MaterialId ORDER BY m.DetailId) r
  FROM IH#DetailsMaterial m
  JOIN CycleTypes ct ON ct.Detailid = m.DetailId
  )
WHERE r = 1
top
IH#CycleTypes
    SELECT d.PropertiesCode CycleType, ct.Id CycleTypeId,
        DetailId, Frequency, WeekTolerance, ct.Priority, ProducingDay, GroupName, FixedPeriodInWeeks
    FROM CycleTypes ct
    JOIN Ih#hierarchypropertydetails d
    ON d.ID = ct.DetailId
top
IH#CycleUtilisation
WITH m AS 
(
SELECT ct.Id CycleTypeId, m.MaterialId, m.DetailId,
       DENSE_RANK() OVER (PARTITION BY ct.Id, m.MaterialId ORDER BY m.DetailId) ct_m,
       DENSE_RANK() OVER (PARTITION BY ct.Id, m.DetailId ORDER BY m.MaterialId) ct_d
  FROM IH#DetailsMaterial m
  JOIN CycleTypes ct ON ct.Detailid = m.DetailId
),
orders AS 
(
SELECT Trunc(COALESCE(oo.FinishTime, oo.DueDate, ol.DespatchDate), 'IW') DateFrom,
       oo.WorkCentreId, 
       ol.SourceMaterialId,
       m.CycleTypeId, 
       oo.MaterialRunId,
       oo.StartTime,
       oo.FinishTime,
       DECODE(ols.OrderOperationStatusCode, 'System', 0, 1) IsFirm,
       oo.Quantity,
       oo.OperationDuration
  FROM OrderLines ol
  JOIN OrderOperations oo
    ON oo.OrderLineId = ol.Id
  JOIN OrderOperationStatuses ols
    ON ols.Id = oo.OrderOperationStatusId
  JOIN m ON m.MaterialId = ol.SourceMaterialId AND m.ct_m = 1 
 WHERE ols.OrderOperationStatusCode IN ('System', 'Firm', 'Completed')
),
durations AS 
(
SELECT ol.DateFrom,
       ol.WorkCentreId, 
       ol.CycleTypeId, 
       ol.MaterialRunId,
       CASE WHEN ol.IsFirm = 0 THEN 0  
            ELSE ol.OperationDuration / 60
       END OrdersHours,
       CASE WHEN ol.IsFirm = 1 THEN 0  
            ELSE ol.OperationDuration / 60
       END TentativeHours
  FROM orders ol
 WHERE (ol.StartTime IS NULL OR ol.FinishTime IS NULL)  
 UNION ALL 
SELECT sp.StartPeriod DateFrom,
       ol.WorkCentreId, 
       ol.CycleTypeId, 
       ol.MaterialRunId,
       CASE WHEN ol.IsFirm = 0 THEN 0  
            ELSE (
                   (CASE WHEN Sign(sp.EndPeriod - ol.FinishTime) = -1 THEN sp.EndPeriod ELSE ol.FinishTime END)
                    - 
                   (CASE WHEN Sign(sp.StartPeriod - ol.StartTime) = -1 THEN ol.StartTime ELSE sp.StartPeriod END)
                 ) * 24   
       END OrdersHours,
       CASE WHEN ol.IsFirm = 1 THEN 0  
            ELSE (
                   (CASE WHEN Sign(sp.EndPeriod - ol.FinishTime) = -1 THEN sp.EndPeriod ELSE ol.FinishTime END)
                    - 
                   (CASE WHEN Sign(sp.StartPeriod - ol.StartTime) = -1 THEN ol.StartTime ELSE sp.StartPeriod END)
                 ) * 24   
       END TentativeHours
  FROM orders ol
 CROSS JOIN IH#CycleProductionPeriods sp
 WHERE (ol.StartTime IS NOT NULL AND ol.FinishTime IS NOT NULL)
   AND ol.StartTime <= sp.EndPeriod
   AND ol.FinishTime >= sp.StartPeriod  
),
runs AS 
(
SELECT Trunc(mr.StartDate, 'IW') DateFrom, 
       mr.WorkCentreId, 
       mrp.MaterialRunId, 
       m.CycleTypeId,
       mr.InitialDuration / 60 DurationHours
  FROM MaterialRuns mr
  JOIN MaterialRunProducts mrp ON mrp.MaterialRunId = mr.Id
  JOIN m ON m.DetailId = mrp.DetailId AND m.ct_d = 1
),
o AS 
(
SELECT DateFrom,
       WorkCentreId, 
       CycleTypeId, 
       SUM(OrdersHours) OrdersHours,
       SUM(TentativeHours) TentativeHours
  FROM durations
 GROUP BY DateFrom, WorkCentreId, CycleTypeId
),
r AS 
(
SELECT DateFrom, 
       WorkCentreId, 
       CycleTypeId,
       SUM(DurationHours) DurationHours,
       SUM(DurationHours - NVL(TotalOrders,0)) NotUsedRunHours,
       SUM(NVL(TotalOrders,0)) AssignOnRunHours
  FROM runs 
  LEFT JOIN (SELECT MaterialRunId, SUM(OrdersHours + TentativeHours) TotalOrders 
               FROM durations
              GROUP BY MaterialRunId) oo ON oo.MaterialRunId = runs.MaterialRunId 
 GROUP BY DateFrom, WorkCentreId, CycleTypeId 
)
SELECT DateFrom SourcePeriod, 
       WorkCentreId, 
       CycleTypeId,
       SUM(OrdersHours) OrdersHours,
       SUM(TentativeHours) TentativeOrdersHours,
       SUM(DurationHours) DurationHours,
       SUM(NotUsedRunHours) UnUsedRunHours,
       SUM(AssignOnRunHours) UsedRunHours
  FROM 
(  
SELECT o.DateFrom, 
       o.WorkCentreId, 
       o.CycleTypeId,
       o.OrdersHours,
       o.TentativeHours,
       0 DurationHours,
       0 NotUsedRunHours,
       0 AssignOnRunHours
  FROM o
 UNION ALL
SELECT r.DateFrom, 
       r.WorkCentreId, 
       r.CycleTypeId,
       0 OrdersHours,
       0 TentativeHours,
       r.DurationHours,
       r.NotUsedRunHours,
       r.AssignOnRunHours
  FROM r
)
GROUP BY DateFrom, WorkCentreId, CycleTypeId
top
IH#DailyAllocationDistribution

SELECT ab.SiteMaterialUsageId, cs.DateFrom, cs.DateFromMonth, cs.IsWorkingDay, cs.MonthSum, cs.WeekSum,
Allocation WeeklyAllocation, MonthlyAllocation,
CASE WHEN DeliveryWeek IS NULL
   THEN   DECODE(cs.MonthSum, 0, 0, ab.MonthlyAllocation * cs.IsWorkingDay / cs.MonthSum)
   ELSE   DECODE(cs.WeekSum, 0, 0, ab.Allocation * cs.IsWorkingDay / cs.WeekSum)
     END Demand
FROM IH#AllocationBodies ab
JOIN
 (SELECT c.*, SUM(IsWorkingDay) OVER(PARTITION BY CalendarId, DateFromMonth) MonthSum FROM CalendarSources c) CS
ON cs.CalendarId = ab.CalendarId
AND cs.DateFromIW = NVL(ab.DeliveryWeek, cs.DateFromIw)
AND cs.DateFromMonth = NVL(ab.DeliveryMonth, cs.DateFromMonth)
top
IH#DailyDemandDistribution
WITH p AS (SELECT NVL(MIN(VALUE), 'Forecast') ReplenishmentDemandType
           FROM SystemParameters WHERE PArameterName = 'ReplenishmentDemandType')
SELECT SiteMaterialusageId, DateFrom, DateFromMonth, IsWorkingDay, MonthSum, WeekSum,
WeeklyAllocation WeeklyDemand, MonthlyAllocation MonthlyDemand, DEMAND, NVL(smu.ConsumptionType, p.ReplenishmentDemandType) ConsumptionType
FROM IH#DailyAllocationDistribution a
JOIN SiteMaterialUSages smu
ON smu.Id = a.SiteMaterialUsageId
CROSS JOIN p
WHERE NVL(smu.ConsumptionType, p.ReplenishmentDemandType) = 'Allocation'
UNION ALL
SELECT SiteMaterialusageId, DateFrom, DateFromMonth, IsWorkingDay, MonthSum, WeekSum,
WeeklyForecast WeeklyDemand, MonthlyForecast MonthlyDemand, DEMAND, NVL(smu.ConsumptionType, p.ReplenishmentDemandType) ConsumptionType
FROM IH#DailyForecastDistribution a
JOIN SiteMaterialUSages smu
ON smu.Id = a.SiteMaterialUsageId
CROSS JOIN p
WHERE NVL(smu.ConsumptionType, p.ReplenishmentDemandType) = 'Forecast'
top
IH#DailyForecastDistribution
SELECT fb.SiteMaterialUsageId, cs.DateFrom, cs.DateFromMonth, cs.IsWorkingDay, cs.MonthSum, cs.WeekSum,
FINAL WeeklyForecast, MonthlyForecast,
CASE WHEN NVL(WeeklyEdited,0) = 0
	 THEN 	DECODE(cs.MonthSum, 0, 0, fb.MonthlyForecast * cs.IsWorkingDay / cs.MonthSum)
	 ELSE 	DECODE(cs.WeekSum, 0, 0, fb.Final * cs.IsWorkingDay / cs.WeekSum)
		 END Demand
FROM IH#ForecastBodies fb, (SELECT c.*, SUM(IsWorkingDay) OVER(PARTITION BY CalendarId, DateFromMonth) MonthSum FROM CalendarSources c) CS
WHERE cs.CalendarId = fb.CalendarId
AND cs.DateFromIW = fb.DateFromIW
AND cs.DateFromMonth = fb.DateFrom
top
IH#DailyRange
SELECT DateFrom, TRUNC(DateFrom, 'IW') DateWeek, TRUNC(Datefrom, 'month') DateMonth FROM CalendarSources
WHERE CalendarId IN (SELECT VALUE FROM SystemParameters WHERE ParameterName = 'DefaultCalendar')
top
IH#DataSourceFields
    SELECT ds.Name DataSourceName, ds.Title, ds.Description DataSourceDescription, DataSourceId,
    dsf.Id, dsf.Name, dsf.Description, Expression, IsCustomField, DataType, Category,
    EntityType, OrderNo, NVL(Filtered, DefaultFiltered) Filtered,
    Helper, HelperColumn,
    Partition, ParentField, Function,
    UnitTypeId, UnitId, CurrencyId, IsCurrency, IsMandatory,
    IncludeNullCondition, DefaultFiltered
    FROM DataSources ds join DataSourceFields dsf on ds.Id = dsf.DataSourceId
top
IH#DefaultOperationTypes
select WorkcentreId, DefaultOperationTypeId
FROM
(
       SELECT WorkcentreId, COUNT(*) QuantityOfOperations, MIN(OperationTypeId) DefaultOperationTypeId
       FROM   Ih#validoperationsources
       GROUP  BY WorkcentreId
)
Where QuantityOfOperations = 1
top
IH#DefaultParameters

SELECT MAX(DECODE(ParameterName, 'DefaultRank', to_number(VALUE), NULL)) AS DefaultCustomerRankId,
       MAX(DECODE(ParameterName, 'DefaultForecastMethod', to_number(VALUE), NULL)) AS DefaultForecastMethodId,
       MAX(DECODE(ParameterName, 'DefaultSafetyStockMethod', to_number(VALUE), NULL)) AS DefaultSafetyStockMethodId,
       MAX(DECODE(ParameterName, 'DefaultCalendar', to_number(VALUE), NULL)) AS DefaultCalendarId,
       MAX(DECODE(ParameterName, 'DefaultSchedule', to_number(VALUE), NULL)) AS DefaultScheduleId,
       MAX(DECODE(ParameterName, 'DefaultCompany', to_number(VALUE), NULL)) AS DefaultCompanyId,
       MAX(DECODE(ParameterName, 'InternalCurrency', to_number(VALUE), NULL)) AS InternalCurrencyId,
       MAX(DECODE(ParameterName, 'DefaultSafetyStockPercentWarning', to_number(VALUE), NULL)) AS DefaultSSPercentWarning,
       MAX(DECODE(ParameterName, 'DefaultNettingAlgorithm', VALUE, NULL)) AS DefaultNettingAlgorithm,
       MAX(DECODE(ParameterName, 'BaseWeightUnit', VALUE, NULL)) AS BaseWeightUnitId,
       MAX(DECODE(ParameterName, 'BaseTimeUnit', VALUE, NULL)) AS BaseTimeUnitId,
       MAX(DECODE(ParameterName, 'UseTradingDays', VALUE, NULL)) AS UseTradingDays,
       MAX(DECODE(ParameterName, 'DefaultSKULowerPercentile', VALUE, NULL)) AS DefaultSKULowerPercentile,
       MAX(DECODE(ParameterName, 'DefaultSKUUpperPercentile', VALUE, NULL)) AS DefaultSKUUpperPercentile
FROM
(
      SELECT ParameterName, VALUE 
        FROM SystemParameters
       WHERE ParameterName IN
             ('DefaultRank', 'DefaultForecastMethod', 'DefaultSafetyStockMethod', 'DefaultCalendar',
             'DefaultSchedule', 'DefaultCompany', 'DefaultSafetyStockPercentWarning', 'DefaultNettingAlgorithm', 'UseTradingDays',
	     'DefaultSKULowerPercentile', 'DefaultSKUUpperPercentile')
       UNION ALL
      SELECT 'InternalCurrency', to_char(ID)
        FROM Currencies c
       WHERE IsInternal =1
       UNION ALL
      SELECT 'BaseWeightUnit', to_char(u.Id) 
        FROM Units u
        JOIN UnitTypes ut ON ut.Id = u.UnitTypeId 
       WHERE ut.UnitTypeName = 'Weight' 
         AND u.IsBaseUnit = 1
       UNION ALL
      SELECT 'BaseTimeUnit', to_char(u.Id) 
        FROM Units u
        JOIN UnitTypes ut ON ut.Id = u.UnitTypeId 
       WHERE ut.UnitTypeName = 'Time' 
         AND u.IsBaseUnit = 1
)

top
IH#DefaultWeeklyCoefs

SELECT DISTINCT CalendarId, RangeId, t.MonthDate, t.WeekDate,
                         DECODE(SUM(t.x) OVER(PARTITION BY CalendarId, RangeId, MonthDate), 0, 0,
                                 SUM(t.x) OVER(PARTITION BY CalendarId, RangeId, MonthDate, WeekDate) / SUM(t.x)
                                  OVER(PARTITION BY CalendarId, RangeId, MonthDate)) Coef, WeekSum
         FROM   (SELECT CalendarId, RangeId, TO_char(DateFrom, 'DD') DAY, DateFrom, MonthDate, WeekDate, IsWorkingDay,
                         v.Coef, WeekSum,
                         SUM(DECODE(IsWorkingDay, 0, v.Coef, 0)) OVER(PARTITION BY CalendarId, RangeId, MonthDate) SS,
                         CASE
                             WHEN isWorkingday = 0 THEN
                              0
                             ELSE
                              v.Coef * 1 /
                              (1 - SUM(DECODE(IsWorkingDay, 0, v.Coef, 0)) OVER(PARTITION BY CalendarId, RangeId, MonthDate))
                         END x
                  FROM   IH#CalendarDailyCoefs CS
                  LEFT   JOIN IH#ForecastRangeValues v
                  ON     TO_char(DateFrom, 'DD') BETWEEN v.DayFrom AND v.DayTo

                  ) t


top
IH#DerivedCharacteristics
SELECT Id,
       CharacteristicName AS PropertyName,
       CharacteristicName AS PropertyDesc,
       UPPER('DC_' || REGEXP_REPLACE(CharacteristicName, '[^[:alnum:]_]', '')) PropertyViewName,
       'DerivedCharacteristic' || ROW_NUMBER() Over(ORDER BY Id) FieldProperty,
       HierarchyLevelNO OrderNo
  FROM DerivedCharacteristics
top
IH#DerivedRulesSku
SELECT siteMaterialUsageId, Derivedcharacteristicid, CharacteristicValue
FROM
(
SELECT r.Id, r.derivedcharacteristicid, r.Ruleweighting, CharacteristicValue, t.Column_Value siteMaterialUsageId,
       ROW_NUMBER() OVER(PARTITION BY r.Derivedcharacteristicid, t.Column_Value ORDER BY r.RuleWeighting DESC) rr
FROM   Derivedcharacteristicrules r, TABLE(ip.getDerivedSkus(r.Id, 1)) t
)
WHERE rr = 1
top
IH#DetailsDescription
WITH q AS
 (
 SELECT *
  FROM   HierarchyPropertyDetails UNPIVOT
         EXCLUDE NULLS
          (VALUE FOR PROPERTY IN(

                                 HierarchyCode1, HierarchyCode2, HierarchyCode3, HierarchyCode4, HierarchyCode5,
                                 HierarchyCode6, HierarchyCode7, HierarchyCode8, HierarchyCode9, HierarchyCode10,
                                 HierarchyCode11, HierarchyCode12, HierarchyCode13, HierarchyCode14, HierarchyCode15,
                                 Code1, Code2, Code3, Code4, Code5, Code6, Code7, Code8, Code9, Code10,
                                 Code11, Code12, Code13, Code14, Code15, Code16, Code17, Code18, Code19, Code20,
                                 Code21, Code22, Code23, Code24, Code25, Code26, Code27, Code28, Code29, Code30,
                                 LocationCode, ProductCode))
                                 )
SELECT q.Id, core.asCsv(CAST(COLLECT(OriginalName || ': ' || VALUE ORDER BY OrderNo) AS ParameterArray), ' ') DESCRIPTION
FROM   q
JOIN   Ih#modelcharacteristics h
ON     UPPER(h.FieldCode) = Upper(Property)
GROUP BY q.Id
top
IH#DetailsEndCustomerLocation
SELECT ec.Id EndCustomerId, d.Id DetailId
  FROM Locations ec
  LEFT JOIN ExpandedLocationsSpec els ON els.LocationId = ec.Id
  JOIN HierarchyPropertyDetails d
    ON (
            (d.LocationCode IS NULL OR d.LocationCode = ec.LocationCode)
        AND (d.EndCustomerHierarchyCode1 IS NULL OR d.EndCustomerHierarchyCode1 = els.HierarchyCode1)
        AND (d.EndCustomerHierarchyCode2 IS NULL OR d.EndCustomerHierarchyCode2 = els.HierarchyCode2)
        AND (d.EndCustomerHierarchyCode3 IS NULL OR d.EndCustomerHierarchyCode3 = els.HierarchyCode3)
        AND (d.EndCustomerHierarchyCode4 IS NULL OR d.EndCustomerHierarchyCode4 = els.HierarchyCode4)
        AND (d.EndCustomerHierarchyCode5 IS NULL OR d.EndCustomerHierarchyCode5 = els.HierarchyCode5)
        AND (d.EndCustomerHierarchyCode6 IS NULL OR d.EndCustomerHierarchyCode6 = els.HierarchyCode6)
        AND (d.EndCustomerHierarchyCode7 IS NULL OR d.EndCustomerHierarchyCode7 = els.HierarchyCode7)
        AND (d.EndCustomerHierarchyCode8 IS NULL OR d.EndCustomerHierarchyCode8 = els.HierarchyCode8)
        AND (d.EndCustomerHierarchyCode9 IS NULL OR d.EndCustomerHierarchyCode9 = els.HierarchyCode9)
        AND (d.EndCustomerHierarchyCode10 IS NULL OR d.EndCustomerHierarchyCode10 = els.HierarchyCode10)
        AND (d.EndCustomerHierarchyCode11 IS NULL OR d.EndCustomerHierarchyCode11 = els.HierarchyCode11)
        AND (d.EndCustomerHierarchyCode12 IS NULL OR d.EndCustomerHierarchyCode12 = els.HierarchyCode12)
        AND (d.EndCustomerHierarchyCode13 IS NULL OR d.EndCustomerHierarchyCode13 = els.HierarchyCode13)
        AND (d.EndCustomerHierarchyCode14 IS NULL OR d.EndCustomerHierarchyCode14 = els.HierarchyCode14)
        AND (d.EndCustomerHierarchyCode15 IS NULL OR d.EndCustomerHierarchyCode15 = els.HierarchyCode15)
   )

top
IH#DetailsEndUse
SELECT eu.Id EndUseId, d.Id DetailId
  FROM EndUses eu
  JOIN HierarchyPropertyDetails d
    ON (
        (d.EndUseCode IS NULL OR d.EndUseCode = eu.EndUseCode)
         AND (d.Property1 IS NULL OR d.Property1 = eu.Property1)
         AND (d.Property2 IS NULL OR d.Property2 = eu.Property2)
         AND (d.Property3 IS NULL OR d.Property3 = eu.Property3)
         AND (d.Property4 IS NULL OR d.Property4 = eu.Property4)
         AND (d.Property5 IS NULL OR d.Property5 = eu.Property5)
         AND (d.Property6 IS NULL OR d.Property6 = eu.Property6)
         AND (d.Property7 IS NULL OR d.Property7 = eu.Property7)
         AND (d.Property8 IS NULL OR d.Property8 = eu.Property8)
         AND (d.Property9 IS NULL OR d.Property9 = eu.Property9)
         AND (d.Property10 IS NULL OR d.Property10 = eu.Property10)
         AND (d.Property11 IS NULL OR d.Property11 = eu.Property11)
         AND (d.Property12 IS NULL OR d.Property12 = eu.Property12)
         AND (d.Property13 IS NULL OR d.Property13 = eu.Property13)
         AND (d.Property14 IS NULL OR d.Property14 = eu.Property14)
         AND (d.Property15 IS NULL OR d.Property15 = eu.Property15)
       )
top
IH#DetailsHierarchy

SELECT h.HierarchyId, hf.Hierarchylevelid, d.Id DetailId, d.Priority
FROM   ExpandedHierarchiesSpec h
JOIN   Hierarchies hf
ON     (hf.Id = h.HierarchyId)
JOIN   Hierarchypropertydetails d
ON     (
                (d.hierarchyCode1 IS NULL OR d.HierarchyCode1 = h.Hierarchycode1)
            AND (d.hierarchyCode2 IS NULL OR d.HierarchyCode2 = h.Hierarchycode2)
            AND (d.hierarchyCode3 IS NULL OR d.HierarchyCode3 = h.Hierarchycode3)
            AND (d.hierarchyCode4 IS NULL OR d.HierarchyCode4 = h.Hierarchycode4)
            AND (d.hierarchyCode5 IS NULL OR d.HierarchyCode5 = h.Hierarchycode5)
            AND (d.hierarchyCode6 IS NULL OR d.HierarchyCode6 = h.Hierarchycode6)
            AND (d.hierarchyCode7 IS NULL OR d.HierarchyCode7 = h.Hierarchycode7)
            AND (d.hierarchyCode8 IS NULL OR d.HierarchyCode8 = h.Hierarchycode8)
            AND (d.hierarchyCode9 IS NULL OR d.HierarchyCode9 = h.Hierarchycode9)
            AND (d.hierarchyCode10 IS NULL OR d.HierarchyCode10 = h.Hierarchycode10)
            AND (d.hierarchyCode11 IS NULL OR d.HierarchyCode11 = h.Hierarchycode11)
            AND (d.hierarchyCode12 IS NULL OR d.HierarchyCode12 = h.Hierarchycode12)
            AND (d.hierarchyCode13 IS NULL OR d.HierarchyCode13 = h.Hierarchycode13)
            AND (d.hierarchyCode14 IS NULL OR d.HierarchyCode14 = h.Hierarchycode14)
            AND (d.hierarchyCode15 IS NULL OR d.HierarchyCode15 = h.Hierarchycode15)

       )

top
IH#DetailsLocation
SELECT lf.Id LocationId, d.Id DetailId
FROM   Locations lf
LEFT JOIN Expandedlocationsspec l ON     (lf.Id = l.LocationId)
JOIN   Hierarchypropertydetails d
            ON (
                (d.LocationCode IS NULL OR d.LocationCode = lf.LocationCode)
            AND (d.hierarchyCode1 IS NULL OR d.HierarchyCode1 = l.Hierarchycode1)
            AND (d.hierarchyCode2 IS NULL OR d.HierarchyCode2 = l.Hierarchycode2)
            AND (d.hierarchyCode3 IS NULL OR d.HierarchyCode3 = l.Hierarchycode3)
            AND (d.hierarchyCode4 IS NULL OR d.HierarchyCode4 = l.Hierarchycode4)
            AND (d.hierarchyCode5 IS NULL OR d.HierarchyCode5 = l.Hierarchycode5)
            AND (d.hierarchyCode6 IS NULL OR d.HierarchyCode6 = l.Hierarchycode6)
            AND (d.hierarchyCode7 IS NULL OR d.HierarchyCode7 = l.Hierarchycode7)
            AND (d.hierarchyCode8 IS NULL OR d.HierarchyCode8 = l.Hierarchycode8)
            AND (d.hierarchyCode9 IS NULL OR d.HierarchyCode9 = l.Hierarchycode9)
            AND (d.hierarchyCode10 IS NULL OR d.HierarchyCode10 = l.Hierarchycode10)
            AND (d.hierarchyCode11 IS NULL OR d.HierarchyCode11 = l.Hierarchycode11)
            AND (d.hierarchyCode12 IS NULL OR d.HierarchyCode12 = l.Hierarchycode12)
            AND (d.hierarchyCode13 IS NULL OR d.HierarchyCode13 = l.Hierarchycode13)
            AND (d.hierarchyCode14 IS NULL OR d.HierarchyCode14 = l.Hierarchycode14)
            AND (d.hierarchyCode15 IS NULL OR d.HierarchyCode15 = l.Hierarchycode15)

       )
top
IH#DetailsMaterial
SELECT m.MaterialId, d.Id DetailId, d.Priority, m.MaterialTypeId, d.PropertyBits
      FROM MaterialPropsSpec m
        JOIN Materials mf ON (mf.Id = m.MaterialId)
        JOIN Hierarchypropertydetails d
      ON (
                (d.ProductCode IS NULL OR d.ProductCode = mf.MaterialCode)
            AND (d.Code1 IS NULL OR d.Code1 = m.code1)
            AND (d.Code2 IS NULL OR d.Code2 = m.code2)
            AND (d.Code3 IS NULL OR d.Code3 = m.code3)
            AND (d.Code4 IS NULL OR d.Code4 = m.code4)
            AND (d.Code5 IS NULL OR d.Code5 = m.code5)
            AND (d.Code6 IS NULL OR d.Code6 = m.code6)
            AND (d.Code7 IS NULL OR d.Code7 = m.code7)
            AND (d.Code8 IS NULL OR d.Code8 = m.code8)
            AND (d.Code9 IS NULL OR d.Code9 = m.code9)
            AND (d.Code10 IS NULL OR d.Code10 = m.code10)
            AND (d.Code11 IS NULL OR d.Code11 = m.code11)
            AND (d.Code12 IS NULL OR d.Code12 = m.code12)
            AND (d.Code13 IS NULL OR d.Code13 = m.code13)
            AND (d.Code14 IS NULL OR d.Code14 = m.code14)
            AND (d.Code15 IS NULL OR d.Code15 = m.code15)
            AND (d.Code16 IS NULL OR d.Code16 = m.code16)
            AND (d.Code17 IS NULL OR d.Code17 = m.code17)
            AND (d.Code18 IS NULL OR d.Code18 = m.code18)
            AND (d.Code19 IS NULL OR d.Code19 = m.code19)
            AND (d.Code20 IS NULL OR d.Code20 = m.code20)
            AND (d.Code21 IS NULL OR d.Code21 = m.code21)
            AND (d.Code22 IS NULL OR d.Code22 = m.code22)
            AND (d.Code23 IS NULL OR d.Code23 = m.code23)
            AND (d.Code24 IS NULL OR d.Code24 = m.code24)
            AND (d.Code25 IS NULL OR d.Code25 = m.code25)
            AND (d.Code26 IS NULL OR d.Code26 = m.code26)
            AND (d.Code27 IS NULL OR d.Code27 = m.code27)
            AND (d.Code28 IS NULL OR d.Code28 = m.code28)
            AND (d.Code29 IS NULL OR d.Code29 = m.code29)
            AND (d.Code30 IS NULL OR d.Code30 = m.code30)
          )
top
IH#DetailsPropertyValue
WITH pp AS 
(
SELECT DISTINCT 
       p.Code1, p.Code2, p.Code3, p.Code4, p.Code5, p.Code6, p.Code7, p.Code8, p.Code9, p.Code10,
       p.Code11, p.Code12, p.Code13, p.Code14, p.Code15, p.Code16, p.Code17, p.Code18, p.Code19, p.Code20,
       p.Code21, p.Code22, p.Code23, p.Code24, p.Code25, p.Code26, p.Code27, p.Code28, p.Code29, p.Code30
  FROM MaterialPropsSpec p
)
SELECT pp.*, d.Id DetailId 
  FROM HierarchyPropertyDetails d, pp
 WHERE 1=1
   AND (d.Code1 IS NULL OR d.Code1 = pp.Code1)
   AND (d.Code2 IS NULL OR d.Code2 = pp.Code2)
   AND (d.Code3 IS NULL OR d.Code3 = pp.Code3)
   AND (d.Code4 IS NULL OR d.Code4 = pp.Code4)
   AND (d.Code5 IS NULL OR d.Code5 = pp.Code5)
   AND (d.Code6 IS NULL OR d.Code6 = pp.Code6)
   AND (d.Code7 IS NULL OR d.Code7 = pp.Code7)
   AND (d.Code8 IS NULL OR d.Code8 = pp.Code8)
   AND (d.Code9 IS NULL OR d.Code9 = pp.Code9)
   AND (d.Code10 IS NULL OR d.Code10 = pp.Code10)
   AND (d.Code11 IS NULL OR d.Code11 = pp.Code11)
   AND (d.Code12 IS NULL OR d.Code12 = pp.Code12)
   AND (d.Code13 IS NULL OR d.Code13 = pp.Code13)
   AND (d.Code14 IS NULL OR d.Code14 = pp.Code14)
   AND (d.Code15 IS NULL OR d.Code15 = pp.Code15)
   AND (d.Code16 IS NULL OR d.Code16 = pp.Code16)
   AND (d.Code17 IS NULL OR d.Code17 = pp.Code17)
   AND (d.Code18 IS NULL OR d.Code18 = pp.Code18)
   AND (d.Code19 IS NULL OR d.Code19 = pp.Code19)
   AND (d.Code20 IS NULL OR d.Code20 = pp.Code20)
   AND (d.Code21 IS NULL OR d.Code21 = pp.Code21)
   AND (d.Code22 IS NULL OR d.Code22 = pp.Code22)
   AND (d.Code23 IS NULL OR d.Code23 = pp.Code23)
   AND (d.Code24 IS NULL OR d.Code24 = pp.Code24)
   AND (d.Code25 IS NULL OR d.Code25 = pp.Code25)
   AND (d.Code26 IS NULL OR d.Code26 = pp.Code26)
   AND (d.Code27 IS NULL OR d.Code27 = pp.Code27)
   AND (d.Code28 IS NULL OR d.Code28 = pp.Code28)
   AND (d.Code29 IS NULL OR d.Code29 = pp.Code29)
   AND (d.Code30 IS NULL OR d.Code30 = pp.Code30)

top
IH#DetailsSku
SELECT smu.Id SiteMaterialUsageId, smu.LocationId, smu.MaterialID, m.MaterialTypeId, m.DetailId, m.Priority
FROM   SiteMaterialUsages smu
JOIN IH#DetailsMaterial m
ON m.MaterialID = smu.MaterialId
JOIN IH#DetailsLocation l
ON l.LocationId = smu.LocationId
WHERE l.DetailId = m.DetailId
top
IH#EndCustomerHierarchies
SELECT LocationId EndCustomerId,
LocationCode EndCustomerCode,
LocationName EndCustomerName,
HierarchyCode1 EndCustomerHierarchyCode1,
HierarchyCode2 EndCustomerHierarchyCode2,
HierarchyCode3 EndCustomerHierarchyCode3,
HierarchyCode4 EndCustomerHierarchyCode4,
HierarchyCode5 EndCustomerHierarchyCode5,
HierarchyCode6 EndCustomerHierarchyCode6,
HierarchyCode7 EndCustomerHierarchyCode7,
HierarchyCode8 EndCustomerHierarchyCode8,
HierarchyCode9 EndCustomerHierarchyCode9,
HierarchyCode10 EndCustomerHierarchyCode10,
HierarchyCode11 EndCustomerHierarchyCode11,
HierarchyCode12 EndCustomerHierarchyCode12,
HierarchyCode13 EndCustomerHierarchyCode13,
HierarchyCode14 EndCustomerHierarchyCode14,
HierarchyCode15 EndCustomerHierarchyCode15
FROM ExpandedLocationsSpec

top
IH#EndPointSkuPortions
SELECT m.MaterialName, l.LocationName, lrs.SiteMaterialUsageId SourceSiteMaterialUSageId, lrs.ConsignmentLocationId, rs.SitematerialusageId,
       DECODE(rs.StartSkuId, lrs.SiteMaterialUsageID, 1, 0) IsDirect, lrs.MaterialId, lrs.GroupKey, rs.DateFrom,
       rs.DateTo, MAX(lrs.TotalTimePeriod + rs.TimePeriod) TotalTimePeriod, SUM(rs.Portion) Portion
FROM   (SELECT PointId, SiteMaterialUsageId, ConsignmentLocationId, TotalTimePeriod, GroupKey, LocationId, MaterialId
         FROM   (SELECT rs.*,
                         ROW_NUMBER() OVER(PARTITION BY PointId, SiteMaterialUsageId, ConsignmentLocationId ORDER BY totalTimePeriod DESC) R
                  FROM   ReplenishedSku rs
									WHERE 1=1
									AND NVL(PriorityPath,1) = 1
									) t
         WHERE  t.r = 1) lrs
JOIN   (SELECT rp.Id PointId, rp.SiteMaterialUsageId StartSkuId, rcs.SiteMaterialUsageId, rcs.DateFrom, rcs.DateTo,
               Portion, rcs.TimePeriod
        FROM   ReplenishedCustomerSku rcs
        JOIN   ReplenishedPoints rp
        ON     rp.SiteMaterialUsageId = rcs.SourceSitematerialusageid) rs
ON     rs.PointID = lrs.PointId
JOIN   Locations l
ON     lrs.LocationId = l.Id
JOIN   Materials m
ON     lrs.MaterialId = m.Id
GROUP  BY m.MaterialName, l.LocationName, lrs.SiteMaterialUsageId, lrs.ConsignmentLocationId, rs.Sitematerialusageid,
          DECODE(rs.StartSkuId, lrs.SiteMaterialUsageID, 1, 0), lrs.MaterialId, lrs.GroupKey, rs.DateFrom,
          rs.DateTo
top
IH#EndPointSkuPortions2
        SELECT m.MaterialName, l.LocationName, lrs.SiteMaterialUsageId SourceSiteMaterialUSageId, lrs.ConsignmentLocationId, rs.SitematerialusageId, PriorityPath,
        DECODE(rs.StartSkuId, lrs.SiteMaterialUsageID, 1, 0) IsDirect, lrs.MaterialId, lrs.GroupKey, rs.DateFrom,
        rs.DateTo, MAX(lrs.TotalTimePeriod + rs.TimePeriod) TotalTimePeriod, SUM(rs.Portion) Portion
        FROM   (SELECT PointId, SiteMaterialUsageId, ConsignmentLocationId, TotalTimePeriod, GroupKey, LocationId, MaterialId, PriorityPath2 PriorityPath
        FROM   (SELECT rs.*, NVL(PriorityPath,1) PriorityPath2,
        ROW_NUMBER() OVER(PARTITION BY PointId, SiteMaterialUsageId, ConsignmentLocationId ORDER BY totalTimePeriod DESC) R
        FROM   ReplenishedSku rs
        WHERE 1=1
        ) t
        WHERE  t.r = 1) lrs
        JOIN   (SELECT rp.Id PointId, rp.SiteMaterialUsageId StartSkuId, rcs.SiteMaterialUsageId, rcs.DateFrom, rcs.DateTo,
        Portion, rcs.TimePeriod
        FROM   ReplenishedCustomerSku rcs
        JOIN   ReplenishedPoints rp
        ON     rp.SiteMaterialUsageId = rcs.SourceSitematerialusageid) rs
        ON     rs.PointID = lrs.PointId
        JOIN   Locations l
        ON     lrs.LocationId = l.Id
        JOIN   Materials m
        ON     lrs.MaterialId = m.Id
        GROUP  BY m.MaterialName, l.LocationName, lrs.SiteMaterialUsageId, lrs.ConsignmentLocationId, rs.Sitematerialusageid,
        DECODE(rs.StartSkuId, lrs.SiteMaterialUsageID, 1, 0), lrs.MaterialId, lrs.GroupKey, rs.DateFrom,
        PriorityPath,
        rs.DateTo
top
IH#EOrderingOrderLines
SELECT Id EntityId from OrderLines ol
WHERE NOT EXISTS (SELECT 1
                  FROM Workcentres wc
                  where ol.LocationID = wc.LocationID)
AND  NOT EXISTS(SELECT 1 FROM DDQUnConfirmedOrders o where o.OrderLineId = ol.Id)
top
IH#EOTOrderLines
SELECT Id EntityId from OrderLines ol
WHERE NOT EXISTS (SELECT 1
                  FROM Workcentres wc
                  where ol.LocationID = wc.LocationID)
AND ReAtpRequired = 0
AND NOT EXISTS(SELECT 1 FROM DDQUnConfirmedOrders o where o.OrderLineId = ol.Id)
top
IH#ExchangeRates
SELECT CurrencyName, DateFrom, DateTo, Multiplier, Divider, Multiplier / Divider Rate
FROM EXPANDEDEXCHANGERATES v JOIN Currencies c ON (c.Id = v.CurrencyId)
top
IH#ExpandedDetails Transposed HierarchyPropertyDetails for using as list field-value.
    

WITH q AS
 (SELECT *
  FROM   HierarchyPropertyDetails UNPIVOT
	EXCLUDE NULLS(VALUE FOR PROPERTY IN(HierarchyCode1, HierarchyCode2,
                                         HierarchyCode3, HierarchyCode4,
                                         HierarchyCode5, HierarchyCode6,
                                         HierarchyCode7, HierarchyCode8,
                                         HierarchyCode9, HierarchyCode10,
                                         HierarchyCode11, HierarchyCode12,
                                         HierarchyCode13, HierarchyCode14,
                                         HierarchyCode15, LocationCode, 
                                         Code1, Code2, Code3, Code4, Code5, Code6, Code7, Code8, Code9, Code10, 
                                         Code11, Code12, Code13, Code14, Code15, Code16, Code17, Code18, Code19, Code20, 
					                     Code21, Code22, Code23, Code24, Code25, Code26, Code27, Code28, Code29, Code30,
                                         Productcode)))
SELECT q.Id, h.FieldViewCode, h.OriginalName, VALUE
FROM   q
JOIN   Ih#modelcharacteristics h
ON     UPPER(h.FieldCode) = Upper(Property)
ORDER  BY 1
top
IH#ExpandedHierarchies
SELECT HierarchyId, MAX(Latitude) Latitude, MAX(Longitude) Longitude,
MAX(DECODE(OrderNo, 1, HierarchyCode, NULL)) AS HierarchyCode1, MAX(DECODE(OrderNo, 1, HierarchyName, NULL)) AS HierarchyName1,
MAX(DECODE(OrderNo, 2, HierarchyCode, NULL)) AS HierarchyCode2, MAX(DECODE(OrderNo, 2, HierarchyName, NULL)) AS HierarchyName2,
MAX(DECODE(OrderNo, 3, HierarchyCode, NULL)) AS HierarchyCode3, MAX(DECODE(OrderNo, 3, HierarchyName, NULL)) AS HierarchyName3,
MAX(DECODE(OrderNo, 4, HierarchyCode, NULL)) AS HierarchyCode4, MAX(DECODE(OrderNo, 4, HierarchyName, NULL)) AS HierarchyName4,
MAX(DECODE(OrderNo, 5, HierarchyCode, NULL)) AS HierarchyCode5, MAX(DECODE(OrderNo, 5, HierarchyName, NULL)) AS HierarchyName5,
MAX(DECODE(OrderNo, 6, HierarchyCode, NULL)) AS HierarchyCode6, MAX(DECODE(OrderNo, 6, HierarchyName, NULL)) AS HierarchyName6,
MAX(DECODE(OrderNo, 7, HierarchyCode, NULL)) AS HierarchyCode7, MAX(DECODE(OrderNo, 7, HierarchyName, NULL)) AS HierarchyName7,
MAX(DECODE(OrderNo, 8, HierarchyCode, NULL)) AS HierarchyCode8, MAX(DECODE(OrderNo, 8, HierarchyName, NULL)) AS HierarchyName8,
MAX(DECODE(OrderNo, 9, HierarchyCode, NULL)) AS HierarchyCode9, MAX(DECODE(OrderNo, 9, HierarchyName, NULL)) AS HierarchyName9,
MAX(DECODE(OrderNo, 10, HierarchyCode, NULL)) AS HierarchyCode10, MAX(DECODE(OrderNo, 10, HierarchyName, NULL)) AS HierarchyName10,
MAX(DECODE(OrderNo, 11, HierarchyCode, NULL)) AS HierarchyCode11, MAX(DECODE(OrderNo, 11, HierarchyName, NULL)) AS HierarchyName11,
MAX(DECODE(OrderNo, 12, HierarchyCode, NULL)) AS HierarchyCode12, MAX(DECODE(OrderNo, 12, HierarchyName, NULL)) AS HierarchyName12,
MAX(DECODE(OrderNo, 13, HierarchyCode, NULL)) AS HierarchyCode13, MAX(DECODE(OrderNo, 13, HierarchyName, NULL)) AS HierarchyName13,
MAX(DECODE(OrderNo, 14, HierarchyCode, NULL)) AS HierarchyCode14, MAX(DECODE(OrderNo, 14, HierarchyName, NULL)) AS HierarchyName14,
MAX(DECODE(OrderNo, 15, HierarchyCode, NULL)) AS HierarchyCode15, MAX(DECODE(OrderNo, 15, HierarchyName, NULL)) AS HierarchyName15
FROM   (SELECT eh.HierarchyId, h.HierarchyCode, h.HierarchyName, hl.OrderNo, Latitude, Longitude
FROM   ExpandedHierarchies eh, Hierarchies h, HierarchyLevelsIPlanView hl
WHERE  h.Id = eh.ParentHierarchyId
AND    h.HierarchyLevelId = hl.Id)
GROUP  BY HierarchyId

top
IH#ExpandedHierarchyDetails Transposed HierarchyPropertyDetails for using in SupercessionRules.
    
WITH q AS
 (
 SELECT *
  FROM   HierarchyPropertyDetails UNPIVOT
         EXCLUDE NULLS
          (VALUE FOR PROPERTY IN(

                                 HierarchyCode1, HierarchyCode2, HierarchyCode3, HierarchyCode4, HierarchyCode5,
                                 HierarchyCode6, HierarchyCode7, HierarchyCode8, HierarchyCode9, HierarchyCode10,
                                 HierarchyCode11, HierarchyCode12, HierarchyCode13, HierarchyCode14, HierarchyCode15,
                                 LocationCode))
																 )
SELECT q.Id, core.asCsv(CAST(COLLECT(h.FieldViewCode ORDER BY OrderNo) AS ParameterArray)) Fields,
core.asCsv(CAST(COLLECT(VALUE ORDER BY OrderNo) AS ParameterArray)) FieldValues
FROM   q
JOIN   Ih#modelcharacteristics h
ON     UPPER(h.FieldCode) = Upper(Property)
GROUP BY q.Id
top
IH#ExpandedLocations
SELECT LocationId, LocationName, LocationCode,
MAX(DECODE(OrderNo, 1, HierarchyCode, NULL)) AS HierarchyCode1, MAX(DECODE(OrderNo, 1, HierarchyName, NULL)) AS HierarchyName1,
MAX(DECODE(OrderNo, 2, HierarchyCode, NULL)) AS HierarchyCode2, MAX(DECODE(OrderNo, 2, HierarchyName, NULL)) AS HierarchyName2,
MAX(DECODE(OrderNo, 3, HierarchyCode, NULL)) AS HierarchyCode3, MAX(DECODE(OrderNo, 3, HierarchyName, NULL)) AS HierarchyName3,
MAX(DECODE(OrderNo, 4, HierarchyCode, NULL)) AS HierarchyCode4, MAX(DECODE(OrderNo, 4, HierarchyName, NULL)) AS HierarchyName4,
MAX(DECODE(OrderNo, 5, HierarchyCode, NULL)) AS HierarchyCode5, MAX(DECODE(OrderNo, 5, HierarchyName, NULL)) AS HierarchyName5,
MAX(DECODE(OrderNo, 6, HierarchyCode, NULL)) AS HierarchyCode6, MAX(DECODE(OrderNo, 6, HierarchyName, NULL)) AS HierarchyName6,
MAX(DECODE(OrderNo, 7, HierarchyCode, NULL)) AS HierarchyCode7, MAX(DECODE(OrderNo, 7, HierarchyName, NULL)) AS HierarchyName7,
MAX(DECODE(OrderNo, 8, HierarchyCode, NULL)) AS HierarchyCode8, MAX(DECODE(OrderNo, 8, HierarchyName, NULL)) AS HierarchyName8,
MAX(DECODE(OrderNo, 9, HierarchyCode, NULL)) AS HierarchyCode9, MAX(DECODE(OrderNo, 9, HierarchyName, NULL)) AS HierarchyName9,
MAX(DECODE(OrderNo, 10, HierarchyCode, NULL)) AS HierarchyCode10, MAX(DECODE(OrderNo, 10, HierarchyName, NULL)) AS HierarchyName10,
MAX(DECODE(OrderNo, 11, HierarchyCode, NULL)) AS HierarchyCode11, MAX(DECODE(OrderNo, 11, HierarchyName, NULL)) AS HierarchyName11,
MAX(DECODE(OrderNo, 12, HierarchyCode, NULL)) AS HierarchyCode12, MAX(DECODE(OrderNo, 12, HierarchyName, NULL)) AS HierarchyName12,
MAX(DECODE(OrderNo, 13, HierarchyCode, NULL)) AS HierarchyCode13, MAX(DECODE(OrderNo, 13, HierarchyName, NULL)) AS HierarchyName13,
MAX(DECODE(OrderNo, 14, HierarchyCode, NULL)) AS HierarchyCode14, MAX(DECODE(OrderNo, 14, HierarchyName, NULL)) AS HierarchyName14,
MAX(DECODE(OrderNo, 15, HierarchyCode, NULL)) AS HierarchyCode15, MAX(DECODE(OrderNo, 15, HierarchyName, NULL)) AS HierarchyName15
FROM   (SELECT el.LocationId, l.LocationName, l.LocationCode, h.HierarchyCode, h.HierarchyName,
HierarchyLevelId, hl.OrderNo
FROM   ExpandedLocations el
JOIN Hierarchies h ON h.Id = el.HierarchyId
JOIN Hierarchylevelsiplanview hl ON hl.Id = h.HierarchyLevelId
JOIN Locations l ON l.Id = el.LocationId
)
GROUP  BY LocationId, LocationName, LocationCode
UNION ALL
SELECT l.Id, LocationName, LocationCode,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL
from locations l
Where HierarchyId is null
top
IH#ExpandedPrices

SELECT SiteMaterialUsageId, DateFrom, DateTo, CurrencyId, Price
FROM ExpandedPrices
WHERE 'PriceRules' = (SELECT NVL(MIN(VALUE),'PriceRules') FROM SystemParameters  WHERE ParameterName = 'PriceRuleType')
UNION ALL
SELECT SiteMaterialUsageId, DateFrom, DateTo, CurrencyId, Price
FROM AverageExpandedPrices
WHERE 'PriceRules' != (SELECT NVL(MIN(VALUE),'PriceRules') FROM SystemParameters  WHERE ParameterName = 'PriceRuleType')


top
IH#ExpandedProperties
SELECT PropertyValueId,
       MAX(DECODE(OrderNo, 1, PropertyValueCode, NULL)) AS Code1, MAX(DECODE(OrderNo, 1, VALUE, NULL)) AS Value1,
       MAX(DECODE(OrderNo, 2, PropertyValueCode, NULL)) AS Code2, MAX(DECODE(OrderNo, 2, VALUE, NULL)) AS Value2,
       MAX(DECODE(OrderNo, 3, PropertyValueCode, NULL)) AS Code3, MAX(DECODE(OrderNo, 3, VALUE, NULL)) AS Value3,
       MAX(DECODE(OrderNo, 4, PropertyValueCode, NULL)) AS Code4, MAX(DECODE(OrderNo, 4, VALUE, NULL)) AS Value4,
       MAX(DECODE(OrderNo, 5, PropertyValueCode, NULL)) AS Code5, MAX(DECODE(OrderNo, 5, VALUE, NULL)) AS Value5,
       MAX(DECODE(OrderNo, 6, PropertyValueCode, NULL)) AS Code6, MAX(DECODE(OrderNo, 6, VALUE, NULL)) AS Value6,
       MAX(DECODE(OrderNo, 7, PropertyValueCode, NULL)) AS Code7, MAX(DECODE(OrderNo, 7, VALUE, NULL)) AS Value7,
       MAX(DECODE(OrderNo, 8, PropertyValueCode, NULL)) AS Code8, MAX(DECODE(OrderNo, 8, VALUE, NULL)) AS Value8,
       MAX(DECODE(OrderNo, 9, PropertyValueCode, NULL)) AS Code9, MAX(DECODE(OrderNo, 9, VALUE, NULL)) AS Value9,
       MAX(DECODE(OrderNo, 10, PropertyValueCode, NULL)) AS Code10, MAX(DECODE(OrderNo, 10, VALUE, NULL)) AS Value10,
       MAX(DECODE(OrderNo, 11, PropertyValueCode, NULL)) AS Code11, MAX(DECODE(OrderNo, 11, VALUE, NULL)) AS Value11,
       MAX(DECODE(OrderNo, 12, PropertyValueCode, NULL)) AS Code12, MAX(DECODE(OrderNo, 12, VALUE, NULL)) AS Value12,
       MAX(DECODE(OrderNo, 13, PropertyValueCode, NULL)) AS Code13, MAX(DECODE(OrderNo, 13, VALUE, NULL)) AS Value13,
       MAX(DECODE(OrderNo, 14, PropertyValueCode, NULL)) AS Code14, MAX(DECODE(OrderNo, 14, VALUE, NULL)) AS Value14,
       MAX(DECODE(OrderNo, 15, PropertyValueCode, NULL)) AS Code15, MAX(DECODE(OrderNo, 15, VALUE, NULL)) AS Value15,
       MAX(DECODE(OrderNo, 16, PropertyValueCode, NULL)) AS Code16, MAX(DECODE(OrderNo, 16, VALUE, NULL)) AS Value16,
       MAX(DECODE(OrderNo, 17, PropertyValueCode, NULL)) AS Code17, MAX(DECODE(OrderNo, 17, VALUE, NULL)) AS Value17,
       MAX(DECODE(OrderNo, 18, PropertyValueCode, NULL)) AS Code18, MAX(DECODE(OrderNo, 18, VALUE, NULL)) AS Value18,
       MAX(DECODE(OrderNo, 19, PropertyValueCode, NULL)) AS Code19, MAX(DECODE(OrderNo, 19, VALUE, NULL)) AS Value19,
       MAX(DECODE(OrderNo, 20, PropertyValueCode, NULL)) AS Code20, MAX(DECODE(OrderNo, 20, VALUE, NULL)) AS Value20,

       MAX(DECODE(OrderNo, 21, PropertyValueCode, NULL)) AS Code21, MAX(DECODE(OrderNo, 21, VALUE, NULL)) AS Value21,
       MAX(DECODE(OrderNo, 22, PropertyValueCode, NULL)) AS Code22, MAX(DECODE(OrderNo, 22, VALUE, NULL)) AS Value22,
       MAX(DECODE(OrderNo, 23, PropertyValueCode, NULL)) AS Code23, MAX(DECODE(OrderNo, 23, VALUE, NULL)) AS Value23,
       MAX(DECODE(OrderNo, 24, PropertyValueCode, NULL)) AS Code24, MAX(DECODE(OrderNo, 24, VALUE, NULL)) AS Value24,
       MAX(DECODE(OrderNo, 25, PropertyValueCode, NULL)) AS Code25, MAX(DECODE(OrderNo, 25, VALUE, NULL)) AS Value25,
       MAX(DECODE(OrderNo, 26, PropertyValueCode, NULL)) AS Code26, MAX(DECODE(OrderNo, 26, VALUE, NULL)) AS Value26,
       MAX(DECODE(OrderNo, 27, PropertyValueCode, NULL)) AS Code27, MAX(DECODE(OrderNo, 27, VALUE, NULL)) AS Value27,
       MAX(DECODE(OrderNo, 28, PropertyValueCode, NULL)) AS Code28, MAX(DECODE(OrderNo, 28, VALUE, NULL)) AS Value28,
       MAX(DECODE(OrderNo, 29, PropertyValueCode, NULL)) AS Code29, MAX(DECODE(OrderNo, 29, VALUE, NULL)) AS Value29,
       MAX(DECODE(OrderNo, 30, PropertyValueCode, NULL)) AS Code30, MAX(DECODE(OrderNo, 30, VALUE, NULL)) AS Value30

 FROM   (SELECT em.PropertyValueId, pv.PropertyValueCode,
                pv.Value, pv.PropertyId, p.OrderNo
         FROM   ExpandedPropertyValues em, PropertyValues pv, Propertiesiplanview p
         WHERE  pv.Id = em.ParentPropertyValueId
         AND    pv.PropertyId = p.Id)
      GROUP  BY PropertyValueId

top
IH#ExpandedPropertyValues
SELECT ep.PropertyValueId, pv.PropertyValueCode, Value, pv.PropertyId, p.PropertyName
FROM Expandedpropertyvalues ep
jOIN PropertyValues pv ON (pv.Id = ep.ParentPropertyvalueid)
JOIN Properties p ON (p.Id = pv.PropertyId)
ORDER BY 1
top
IH#FinForecastBudgets

WITH mer AS
(SELECT er.FromCurrencyId, er.DateFrom, (1 / (er.FromMultiplier / er.FromDivider)) * er.ToMultiplier / er.ToDivider Coef
FROM   MonthlyExchangeRates er
WHERE  er.ToCurrencyId = (SELECT MIN(c.Id) FROM Currencies c WHERE c.IsInternal = 1)),
converted AS
(SELECT fb.DateFrom, fb.SiteMaterialUsageId,
Final,
Round(fb.ForecastedPrice * er.Coef, 4) FinalPrice,
Round(fb.NominalCost * erc.Coef, 4) NominalCost,
NVL(last_value(DECODE(NominalCostAdjustment, 0, NULL, NominalCostAdjustment) IGNORE NULLS)
OVER(PARTITION BY fb.SitematerialUsageId ORDER BY fb.DateFrom rows BETWEEN unbounded preceding AND 0
preceding), 0) NCA,
NVL(last_value(DECODE(ValueAddAdjustment, 0, NULL, ValueAddAdjustment) IGNORE NULLS)
OVER(PARTITION BY fb.SitematerialUsageId ORDER BY fb.DateFrom rows BETWEEN unbounded preceding AND 0
preceding), 0) VAA
FROM   IH#ForecastBudgets fb
JOIN   mer er
ON     er.FromCurrencyId = fb.PriceCurrencyId
AND    fb.DateFrom = er.DateFrom
JOIN   mer erc
ON     erc.FromCurrencyId = fb.CostCurrencyId
AND    fb.DateFrom = erc.DateFrom
),
calculated AS
(SELECT DateFrom, SiteMaterialUsageId, FINAL,
FinalPrice + (FinalPrice - NominalCost) * NVL(VAA, 0) / 100 + NominalCost * NVL(NCA, 0) / 100 FinalPrice,
NominalCost * (100 + NVL(NCA, 0)) / 100 NominalCost,
(FinalPrice - NominalCost) * (100 + NVL(VAA, 0)) / 100 ValueAdd
FROM   converted c
)

SELECT  c.DateFrom, c.SiteMaterialUsageId,
NVL(c.Final * c.FinalPrice, 0) BudgetRevenue,
NVL(c.Final * c.NominalCost, 0) BudgetNominalCost,
NVL(c.Final * c.ValueAdd, 0) BudgetValueAdd
FROM   calculated c
top
IH#FlatForecastChangeDetails
SELECT fc.ForecastChangeId,
f.CommentLink,
core.asCsv(fc.Value1) Value1, core.asCsv(fc.Value2) Value2, core.asCsv(fc.Value3) Value3,
core.asCsv(fc.Value4) Value4,  core.asCsv(fc.Value5) Value5, core.asCsv(fc.Value6) Value6,
core.asCsv(fc.Value7) Value7, core.asCsv(fc.Value8) Value8, core.asCsv(fc.Value9) Value9,
core.asCsv(fc.Value10) Value10, core.asCsv(fc.Value11) Value11, core.asCsv(fc.Value12) Value12,
core.asCsv(fc.Value13) Value13, core.asCsv(fc.Value14) Value14, core.asCsv(fc.Value15) Value15,

core.asCsv(fc.Value16) Value16, core.asCsv(fc.Value17) Value17, core.asCsv(fc.Value18) Value18,
core.asCsv(fc.Value19) Value19, core.asCsv(fc.Value20) Value20, core.asCsv(fc.Value21) Value21,
core.asCsv(fc.Value22) Value22, core.asCsv(fc.Value23) Value23, core.asCsv(fc.Value24) Value24,
core.asCsv(fc.Value25) Value25, core.asCsv(fc.Value26) Value26, core.asCsv(fc.Value27) Value27,
core.asCsv(fc.Value28) Value28, core.asCsv(fc.Value29) Value29, core.asCsv(fc.Value30) Value30,

core.asCsv(fc.hierarchyName1) HierarchyNam1, core.asCsv(fc.hierarchyName2) HierarchyName2, core.asCsv(fc.hierarchyName3) HierarchyName3,
core.asCsv(fc.hierarchyName4) HierarchyName4, core.asCsv(fc.hierarchyName5) HierarchyName5, core.asCsv(fc.hierarchyName6) HierarchyName6,
core.asCsv(fc.hierarchyName7) HierarchyName7, core.asCsv(fc.hierarchyName8) HierarchyName8, core.asCsv(fc.hierarchyName9) HierarchyName9,
core.asCsv(fc.hierarchyName10) HierarchyName10, core.asCsv(fc.hierarchyName11) HierarchyName11, core.asCsv(fc.hierarchyName12) HierarchyName12,
core.asCsv(fc.hierarchyName13) HierarchyName13, core.asCsv(fc.hierarchyName14) HierarchyName14, core.asCsv(fc.hierarchyName15) HierarchyName15,
core.asCsv(fc.Property1) Property1, core.asCsv(fc.Property2) Property2, core.asCsv(fc.Property3) Property3,
core.asCsv(fc.Property4) Property4, core.asCsv(fc.Property5) Property5, core.asCsv(fc.Property6) Property6,
core.asCsv(fc.Property7) Property7, core.asCsv(fc.Property8) Property8, core.asCsv(fc.Property9) Property9,
core.asCsv(fc.Property10) Property10, core.asCsv(fc.Property11) Property11, core.asCsv(fc.Property12) Property12,
core.asCsv(fc.Property13) Property13, core.asCsv(fc.Property14) Property14, core.asCsv(fc.Property15) Property15,

core.asCsv(fc.Property16) Property16, core.asCsv(fc.Property17) Property17, core.asCsv(fc.Property18) Property18,
core.asCsv(fc.Property19) Property19, core.asCsv(fc.Property20) Property20, core.asCsv(fc.Property21) Property21,
core.asCsv(fc.Property22) Property22, core.asCsv(fc.Property23) Property23, core.asCsv(fc.Property24) Property24,
core.asCsv(fc.Property25) Property25, core.asCsv(fc.Property26) Property26, core.asCsv(fc.Property27) Property27,
core.asCsv(fc.Property28) Property28, core.asCsv(fc.Property29) Property29, core.asCsv(fc.Property30) Property30,

core.asCsv(fc.FullLocationCode) FullLocationCode,
core.asCsv(fc.FullLocationName) FullLocationName,
core.asCsv(fc.LocationCode) LocationCode,
core.asCsv(fc.LocationName) LocationName,
core.asCsv(fc.ProductCode) ProductCode,
core.asCsv(fc.AlternateProduct) AlternateProduct,
core.asCsv(fc.CurrencyDescription) CurrencyDescription,
core.asCsv(fc.CurrencyName) CurrencyName,
core.asCsv(fc.EndUseDescription) EndUseDescription,
core.asCsv(fc.MaterialTypeName) MaterialTypeName

FROM   IH#FlatForecastChanges fc
JOIN   ForecastChanges f
ON     (f.Id = fc.ForecastChangeId)
top
IH#FlatForecastChanges
SELECT ForecastChangeId,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE1', VALUE)) AS PArameterArray) AS Value1,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE2', VALUE)) AS PArameterArray) AS Value2,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE3', VALUE)) AS PArameterArray) AS Value3,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE4', VALUE)) AS PArameterArray) AS Value4,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE5', VALUE)) AS PArameterArray) AS Value5,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE6', VALUE)) AS PArameterArray) AS Value6,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE7', VALUE)) AS PArameterArray) AS Value7,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE8', VALUE)) AS PArameterArray) AS Value8,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE9', VALUE)) AS PArameterArray) AS Value9,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE10', VALUE)) AS PArameterArray) AS Value10,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE11', VALUE)) AS PArameterArray) AS Value11,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE12', VALUE)) AS PArameterArray) AS Value12,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE13', VALUE)) AS PArameterArray) AS Value13,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE14', VALUE)) AS PArameterArray) AS Value14,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE15', VALUE)) AS PArameterArray) AS Value15,

       CAST(COLLECT(DECODE(m.FieldName, 'VALUE16', VALUE)) AS PArameterArray) AS Value16,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE17', VALUE)) AS PArameterArray) AS Value17,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE18', VALUE)) AS PArameterArray) AS Value18,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE19', VALUE)) AS PArameterArray) AS Value19,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE20', VALUE)) AS PArameterArray) AS Value20,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE21', VALUE)) AS PArameterArray) AS Value21,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE22', VALUE)) AS PArameterArray) AS Value22,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE23', VALUE)) AS PArameterArray) AS Value23,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE24', VALUE)) AS PArameterArray) AS Value24,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE25', VALUE)) AS PArameterArray) AS Value25,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE26', VALUE)) AS PArameterArray) AS Value26,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE27', VALUE)) AS PArameterArray) AS Value27,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE28', VALUE)) AS PArameterArray) AS Value28,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE29', VALUE)) AS PArameterArray) AS Value29,
       CAST(COLLECT(DECODE(m.FieldName, 'VALUE30', VALUE)) AS PArameterArray) AS Value30,

       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME1', VALUE)) AS PArameterArray) AS HierarchyName1,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME2', VALUE)) AS PArameterArray) AS HierarchyName2,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME3', VALUE)) AS PArameterArray) AS HierarchyName3,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME4', VALUE)) AS PArameterArray) AS HierarchyName4,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME5', VALUE)) AS PArameterArray) AS HierarchyName5,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME6', VALUE)) AS PArameterArray) AS HierarchyName6,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME7', VALUE)) AS PArameterArray) AS HierarchyName7,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME8', VALUE)) AS PArameterArray) AS HierarchyName8,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME9', VALUE)) AS PArameterArray) AS HierarchyName9,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME10', VALUE)) AS PArameterArray) AS HierarchyName10,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME11', VALUE)) AS PArameterArray) AS HierarchyName11,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME12', VALUE)) AS PArameterArray) AS HierarchyName12,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME13', VALUE)) AS PArameterArray) AS HierarchyName13,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME14', VALUE)) AS PArameterArray) AS HierarchyName14,
       CAST(COLLECT(DECODE(m.FieldName, 'HIERARCHYNAME15', VALUE)) AS PArameterArray) AS HierarchyName15,

       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY1', VALUE)) AS PArameterArray) AS PROPERTY1,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY2', VALUE)) AS PArameterArray) AS PROPERTY2,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY3', VALUE)) AS PArameterArray) AS PROPERTY3,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY4', VALUE)) AS PArameterArray) AS PROPERTY4,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY5', VALUE)) AS PArameterArray) AS PROPERTY5,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY6', VALUE)) AS PArameterArray) AS PROPERTY6,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY7', VALUE)) AS PArameterArray) AS PROPERTY7,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY8', VALUE)) AS PArameterArray) AS PROPERTY8,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY9', VALUE)) AS PArameterArray) AS PROPERTY9,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY10', VALUE)) AS PArameterArray) AS PROPERTY10,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY11', VALUE)) AS PArameterArray) AS PROPERTY11,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY12', VALUE)) AS PArameterArray) AS PROPERTY12,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY13', VALUE)) AS PArameterArray) AS PROPERTY13,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY14', VALUE)) AS PArameterArray) AS PROPERTY14,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY15', VALUE)) AS PArameterArray) AS Property15,

       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY16', VALUE)) AS PArameterArray) AS Property16,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY17', VALUE)) AS PArameterArray) AS Property17,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY18', VALUE)) AS PArameterArray) AS Property18,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY19', VALUE)) AS PArameterArray) AS Property19,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY20', VALUE)) AS PArameterArray) AS Property20,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY21', VALUE)) AS PArameterArray) AS Property21,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY22', VALUE)) AS PArameterArray) AS Property22,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY23', VALUE)) AS PArameterArray) AS Property23,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY24', VALUE)) AS PArameterArray) AS Property24,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY25', VALUE)) AS PArameterArray) AS Property25,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY26', VALUE)) AS PArameterArray) AS Property26,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY27', VALUE)) AS PArameterArray) AS Property27,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY28', VALUE)) AS PArameterArray) AS Property28,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY29', VALUE)) AS PArameterArray) AS Property29,
       CAST(COLLECT(DECODE(m.FieldName, 'PROPERTY30', VALUE)) AS PArameterArray) AS Property30,

       CAST(COLLECT(DECODE(m.FieldName, 'ENDUSEDESCRIPTION', VALUE)) AS PArameterArray) AS ENDUSEDESCRIPTION,
       CAST(COLLECT(DECODE(m.FieldName, 'PRODUCTNAME', VALUE)) AS PArameterArray) AS PRODUCTNAME,
       CAST(COLLECT(DECODE(m.FieldName, 'PRODUCTCODE', VALUE)) AS PArameterArray) AS PRODUCTCODE,
       CAST(COLLECT(DECODE(m.FieldName, 'LOCATIONNAME', VALUE)) AS PArameterArray) AS LOCATIONNAME,
       CAST(COLLECT(DECODE(m.FieldName, 'LOCATIONCODE', VALUE)) AS PArameterArray) AS LOCATIONCODE,
       CAST(COLLECT(DECODE(m.FieldName, 'FULLLOCATIONNAME', VALUE)) AS PArameterArray) AS FULLLOCATIONNAME,
       CAST(COLLECT(DECODE(m.FieldName, 'FULLLOCATIONCODE', VALUE)) AS PArameterArray) AS FULLLOCATIONCODE,
       CAST(COLLECT(DECODE(m.FieldName, 'ALTERNATEPRODUCT', VALUE)) AS PArameterArray) AS ALTERNATEPRODUCT,
       CAST(COLLECT(DECODE(m.FieldName, 'MATERIALTYPENAME', VALUE)) AS PArameterArray) AS MATERIALTYPENAME,
       CAST(COLLECT(DECODE(m.FieldName, 'CURRENCYNAME', VALUE)) AS PArameterArray) AS CURRENCYNAME,
       CAST(COLLECT(DECODE(m.FieldName, 'CURRENCYDESCRIPTION', VALUE)) AS PArameterArray) AS CURRENCYDESCRIPTION

FROM ForecastChangeDetails d JOIN IH#MappedFields m ON (UPPER(d.FieldName) = UPPER(m.FieldViewName))
GROUP  BY ForecastChangeId
top
IH#FlatSku

SELECT Value1, Value2, Value3, Value4, Value5, Value6, Value7, Value8, Value9, Value10, Value11, Value12, Value13,
       Value14, Value15, Value16, Value17, Value18, Value19, Value20, 
       Value21, Value22, Value23, Value24, Value25, Value26, Value27, Value28, Value29, Value30,
       HierarchyName1, HierarchyName2, HierarchyName3, HierarchyName4, HierarchyName5, HierarchyName6,
       HierarchyName7, HierarchyName8, HierarchyName9, HierarchyName10, HierarchyName11, HierarchyName12,
       HierarchyName13, HierarchyName14, HierarchyName15, eu.Property1, eu.Property2, eu.Property3, eu.Property4, eu.Property5,
       eu.Property6, eu.Property7, eu.Property8, eu.Property9, eu.Property10, eu.Property11, eu.Property12, eu.Property13, eu.Property14,
       eu.Property15, l.LocationCode, m.MaterialCode ProductCode, l.LocationName, m.MaterialName ProductName,
       ExistingAlternateProduct ALTERNATEPRODUCT, CurrencyDescription, CurrencyName, mt.MaterialTypeName, eu.EndUseDescription,
       smu.SkuProperty1, smu.SkuProperty2, smu.SkuProperty3, smu.SkuProperty4, smu.SkuProperty5,
       l.LocationCode || ' ' || l.LocationName FullLocationCode,
       l.LocationName || ' ' || l.LocationCode FullLocationName
FROM   IH#CustomerSkus smu
JOIN   Materials m
ON     m.Id = smu.MaterialId
JOIN   MaterialTypes mt
ON     mt.ID = m.MaterialTypeId
JOIN   MaterialPropsSpec ms
ON     ms.MaterialId = m.Id
JOIN   (SELECT t.ID, LocationName, LocationCode, CurrencyDescription, CurrencyName
        FROM   (SELECT loc.Id, LocationName, LocationCode, loc.CurrencyId
                 FROM   Locations loc
                 WHERE  CurrencyId IS NOT NULL
                 UNION ALL
                 SELECT loc.Id, LocationName, LocationCode,
                        (SELECT MIN(Id) CurrencyId FROM Currencies WHERE IsInternal = 1) CurrencyId
                 FROM   Locations loc
                 WHERE  loc.CurrencyId IS NULL) t
        LEFT   JOIN Currencies c
        ON     (c.Id = t.CurrencyId)) l
ON     l.Id = smu.LocationId
LEFT   JOIN ExpandedLocationsSpec es
ON     es.LocationId = l.Id
LEFT   JOIN EndUses eu
ON     (eu.Id = smu.EndUseId)


top
IH#ForecastBodies
SELECT SiteMaterialUsageId, fb.DateFrom, DateFromIW, CalendarId, WeeklyEdited, fb.Final MonthlyForecast, SUM(fb.Final * fc.Coef) FINAL
FROM   ForecastBodies fb, ForecastWeeklyCoefs fc
WHERE  fc.Id = fb.FinalWeeklyCoefId
AND    fc.Datefrom = fb.DateFrom
GROUP  BY SiteMaterialUsageId, fb.DateFrom, DateFromIW, fb.Final, WeeklyEdited, CalendarId
top
IH#ForecastBudgets
SELECT fs.Name ForecastSnapshotName,
       b.Id, b.DateFrom, b.ForecastSnapshotId, b.SiteMaterialUsageId, b.FinalWeeklyCoefId,
       DECODE(fs.IsConstrained, 1, b.Final - b.UnAllocated, b.Final) Final,
       b.ForecastStatusId, b.PriceCurrencyId, b.SystemPrice, b.ForecastedPrice, b.CostCurrencyId,
       b.NominalCost, b.NominalCostAdjustment, b.ValueAddAdjustment, b.UnAllocated
  FROM ForecastSnapshotBodies b
  JOIN ForecastSnapshots fs
    ON fs.Id = b.ForecastSnapshotId
   AND IsBudget = 1
top
IH#ForecastChangeDetails
SELECT ForecastChangeId,
' AND ' || core.asCsv(CAST(COLLECT(FieldName || ' IN ( ' || ValueList || ')') AS PArameterArray), ' AND ') FILTER,
core.asCsv(CAST(COLLECT(FieldName) AS PArameterArray), ',') Fields,
core.asCsv(CAST(COLLECT(ValueList) AS PArameterArray), ',') FieldValues
FROM
(
SELECT ForecastChangeId, FieldName,
core.AsCsv(CAST(COLLECT('''' || Value || '''') AS PArameterArray), ', ') AS FilterValueList,
core.AsCsv(CAST(COLLECT(VALUE) AS PArameterArray), ';') AS ValueList
FROM ForecastChangeDetails
GROUP BY ForecastChangeId, FieldName
)
GROUP BY ForecastChangeId

top
IH#ForecastedLocations
SELECT *
FROM   Locations l
WHERE  NOT EXISTS (SELECT 1 FROM Workcentres wc WHERE wc.locationId = l.Id)
AND    EXISTS (SELECT 1
        FROM   IH#CustomerSkus smu
        WHERE  smu.Locationid = l.Id
        AND    Status = 1)
top
IH#ForecastedPrices
SELECT SiteMaterialUsageId, SystemPrice, ForecastedPrice, PriceCurrencyId, DateFrom, LAST_day(Datefrom) DateTo
FROM ForecastBodies
top
IH#ForecastOperations
SELECT * from ForecastOperations
top
IH#ForecastRangeValues
SELECT v.RangeId, DayFrom, DayTo, Percentage / 100 / (DayTo-DayFrom + 1) Coef
FROM ForecastRangeValues v
UNION ALL
SELECT 0, 1, 31, 100
FROM dual

top
IH#ForecastReasons
SELECT * from Reasons Where ReasonType = 'Forecast'
top
IH#Forecasts
SELECT f.*, LAG(ID, 1) OVER(ORDER BY StartDate) PreviousForecastId,
       LAG(StartDate, 1) OVER(ORDER BY StartDate) PreviousStartDate
FROM   Forecasts f
top
IH#ForecastSampleMethods
SELECT ForecastSampleId,
 core.AsCsv(CAST(COLLECT(MethodName) AS ParameterArray), '; ') Methods
 FROM Forecastsamplemethods sm
GROUP BY ForecastSampleId
top
IH#GridColumns
SELECT g.Name GridName, gc.* FROM  GridColumns gc
JOIN grids g ON g.Id = gc.GridId
top
IH#GroupedProductRouteStages

SELECT ProductRouteId, COUNT(1) quantity FROM ProductRouteStages prs
WHERE EXISTS (SELECT 1 FROM ProductionConfigurations pc WHERE pc.ProductRouteid = prs.ProductRouteid)
GROUP BY ProductRouteId
HAVING COUNT(1) > 1
top
IH#GroupedReplenishedSku
SELECT r.GroupId, r.GroupType, r.MaterialId, r.ConsignmentLocationId, r.GroupKey, MIN(HighQuantity) HighQuantity,
MIN(lowQuantity) LowQuantity, MIN(DaysOfSupply) DaysOfSupply, MIN(MaxDaysOfSupply) MaxDaysOfSupply,
MAX(TransportTime) TransportTime, MIN(SafetyStockMethodId) SafetyStockMethodId, MIN(MaxSafetyStockMethodId) MaxSafetyStockMethodId,
MIN(ForecastMethodId) ForecastMethodId,
GREATEST(1, MAX(ReplenishmentFrequency)) ReplenishmentFrequency,
GREATEST(1, MAX(MaxReplenishmentFrequency)) MaxReplenishmentFrequency,
MIN(HistoryStartDate) HistoryStartDate
FROM GroupedSku R
JOIN Replenishedsku rs
ON r.SiteMaterialUsageId = rs.SiteMaterialUsageId
AND NVL(r.ConsignmentLocationId,0) = NVL(rs.ConsignmentLocationId,0)
JOIN Replenishedpoints rp
ON  rs.PointId = rp.Id
WHERE isSelected = 1
GROUP BY r.GroupId, r.GroupType, r.MaterialId, r.ConsignmentlocationId, r.GroupKey
top
IH#GroupedSku
SELECT l.LocationName, l.LocationCode, m.MaterialName, m.MaterialCode,
cl.LocationCode ConsignmentCustomerCode, cl.LocationName ConsignmentCustomerName, gs.GroupKey, smu.SiteMaterialUsageId, smu.MaterialId,
gs.LocationId,  smu.Replenished,
SafetyStockMethodName, smu.UpperPercentile, smu.LowerPercentile,
gs.DaysOfSupply, gs.HighQuantity, gs.LowQuantity, gs.TransportTime, gs.ReplenishmentFrequency
FROM GroupedSku gs JOIN SafetyStockMethods ssm ON ssm.id = gs.SafetyStockMethodId
JOIN IH#skus smu ON smu.SiteMaterialUsageId = gs.SiteMaterialUSageId AND NVL(smu.ConsignmentLocationId,0) = NVL(gs.ConsignmentLocationId, 0)
JOIN Materials m ON m.Id = smu.MaterialId
JOIN Locations l ON l.Id = smu.LocationId
LEFT JOIN Locations cl ON cl.Id = gs.ConsignmentLocationId
top
IH#HierarchyPropertyDetails
SELECT d.*,
RTRIM(NVL2(HierarchyCode1, HierarchyCode1 || ' / ', '') ||
NVL2(HierarchyCode2, HierarchyCode2 || ' / ', '') ||
NVL2(HierarchyCode3, HierarchyCode3 || ' / ', '') ||
NVL2(HierarchyCode4, HierarchyCode4 || ' / ', '') ||
NVL2(HierarchyCode5, HierarchyCode5 || ' / ', '') ||
NVL2(HierarchyCode6, HierarchyCode6 || ' / ', '') ||
NVL2(HierarchyCode7, HierarchyCode7 || ' / ', '') ||
NVL2(HierarchyCode8, HierarchyCode8 || ' / ', '') ||
NVL2(HierarchyCode9, HierarchyCode9 || ' / ', '') ||
NVL2(HierarchyCode10, HierarchyCode10 || ' / ', '') ||
NVL2(HierarchyCode11, HierarchyCode11 || ' / ', '') ||
NVL2(HierarchyCode12, HierarchyCode12 || ' / ', '') ||
NVL2(HierarchyCode13, HierarchyCode13 || ' / ', '') ||
NVL2(HierarchyCode14, HierarchyCode14 || ' / ', '') ||
NVL2(HierarchyCode15, HierarchyCode15 || ' / ', '') ||
NVL2(LocationCode, LocationCode || ' / ', '') ||
NVL2(Code1, Code1 || ' / ', '') ||
NVL2(Code2, Code2 || ' / ', '') ||
NVL2(Code3, Code3 || ' / ', '') ||
NVL2(Code4, Code4 || ' / ', '') ||
NVL2(Code5, Code5 || ' / ', '') ||
NVL2(Code6, Code6 || ' / ', '') ||
NVL2(Code7, Code7 || ' / ', '') ||
NVL2(Code8, Code8 || ' / ', '') ||
NVL2(Code9, Code9 || ' / ', '') ||
NVL2(Code10, Code10 || ' / ', '') ||
NVL2(Code11, Code11 || ' / ', '') ||
NVL2(Code12, Code12 || ' / ', '') ||
NVL2(Code13, Code13 || ' / ', '') ||
NVL2(Code14, Code14 || ' / ', '') ||
NVL2(Code15, Code15 || ' / ', '') ||
NVL2(Code16, Code16 || ' / ', '') ||
NVL2(Code17, Code17 || ' / ', '') ||
NVL2(Code18, Code18 || ' / ', '') ||
NVL2(Code19, Code19 || ' / ', '') ||
NVL2(Code20, Code20 || ' / ', '') ||
NVL2(Code21, Code21 || ' / ', '') ||
NVL2(Code22, Code22 || ' / ', '') ||
NVL2(Code23, Code23 || ' / ', '') ||
NVL2(Code24, Code24 || ' / ', '') ||
NVL2(Code25, Code25 || ' / ', '') ||
NVL2(Code26, Code26 || ' / ', '') ||
NVL2(Code27, Code27 || ' / ', '') ||
NVL2(Code28, Code28 || ' / ', '') ||
NVL2(Code29, Code29 || ' / ', '') ||
NVL2(Code30, Code30 || ' / ', '') ||
NVL2(ProductCode, ProductCode || ' / ', ''),
' / ') Description,
core.AsCsv(ParameterArray(Code1, CODE2, Code3, CODE4, Code5, Code6, CODE7, Code8, CODE9, Code10,
Code11, CODE12, Code13, CODE14, Code15, Code16, CODE17, Code18, CODE19, Code20,
Code21, CODE22, Code23, CODE24, Code25, Code26, CODE27, Code28, CODE29, Code30), '#!#', 1) PropertiesCode,
core.AsCsv(ParameterArray(HierarchyCode1, HierarchyCode2, HierarchyCode3, HierarchyCode4, HierarchyCode5,
HierarchyCode6, HierarchyCode7, HierarchyCode8, HierarchyCode9, HierarchyCode10,
HierarchyCode11, HierarchyCode12, HierarchyCode13, HierarchyCode14, HierarchyCode15), '#!#', 1) HierarchiesCode
FROM HierarchyPropertyDetails d
top
IH#IdealProfiles
SELECT siteMaterialUsageId, ConsignmentLocationId, DateFrom,
       (First_value(Opening)
         OVER(PARTITION BY SiteMaterialUsageId, ConsignmentLocationId ORDER BY DateFrom) +
         NVL(SUM(FirmOrdersIn + RequestedOrdersIn)
             OVER(PARTITION BY SiteMaterialUsageId,
                  ConsignmentLocationId ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) -
         NVL(SUM(RequestedOrdersOut + Consumption - TentativeOrdersOut)
             OVER(PARTITION BY SiteMaterialUsageId,
                  ConsignmentLocationId ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0)) Opening,
       FirmOrdersIn FirmOrdersIn, RequestedOrdersIn TentativeOrdersIn,
       (ip.ConsumptionOrders - TentativeOrdersOut) FirmOrdersOut, RequestedOrdersOut TentativeOrdersOut,
       ConsumptionForecast ForecastDemand,
       (First_value(Opening)
         OVER(PARTITION BY SiteMaterialUsageId, ConsignmentLocationId ORDER BY DateFrom) +
         NVL(SUM(FirmOrdersIn + RequestedOrdersIn)
             OVER(PARTITION BY SiteMaterialUsageId,
                  ConsignmentLocationId ORDER BY DateFrom ROWS BETWEEN UNBOUNDED
                   PRECEDING AND ClosingMethod PRECEDING), 0) -
         NVL(SUM(RequestedOrdersOut + Consumption - TentativeOrdersOut)
             OVER(PARTITION BY SiteMaterialUsageId,
                  ConsignmentLocationId ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING), 0)) Closing,
       SafetyStock SafetyStock, MaxSafetyStock MaxSafetyStock, IsReceivingDate, IsRunAvailable
FROM   InventoryProfiles ip
CROSS JOIN (SELECT DECODE(RPClosingCalculationMethod, 'AfterDeliveryDate', 1, 0) ClosingMethod FROM IH#ReplenishmentParameters) p

top
IH#IdenticalConfigurations
SELECT t.*, DENSE_RANK() OVER (Order by t.ConfigurationHash, t.BomId) AS ID
 FROM
(
SELECT ProductionConfigurationId, BomId, ProductRouteId, SiteMaterialUsageId, LocationID, MaterialId,
core.asCsv(CAST(COLLECT(ot.OperationTypeName || ':' || ValidSources || ':' || ConversionHash ORDER BY OrderNo) AS ParameterArray), ';') ConfigurationHash
FROM IH#ConfigurationSources c
JOIN OperationTypes ot ON ot.Id = c.OperationTypeId
GROUP BY ProductionConfigurationId, BomId, ProductRouteId, SiteMaterialUsageId, LocationID, MaterialId
) t
top
IH#InitialSourceRules

SELECT sr.Id, detailId, srs.OperationTypeId, ot.OperationTypeName,
core.asCsv(CAST(COLLECT(wc.WorkcentreName) AS ParameterArray)) Workcentres,
core.asCsv(CAST(COLLECT(s.SiteName) AS ParameterArray)) Sites
FROM   InitialSourceRules sr
JOIN InitialSourceRuleSources srs
ON srs.InitialSourceRuleId = sr.Id
LEFT JOIN   Workcentres wc
ON     (wc.Id = srs.WorkcentreId)
LEFT  JOIN Sites s
ON     (s.Id = srs.SiteId)
LEFT JOIN OperationTypes ot
ON ot.Id = srs.OperationTypeId
GROUP BY sr.Id, detailId, srs.OperationTypeId, ot.OperationTypeName


top
IH#InitialSourceRuleSources
SELECT sr.InitialSourceRuleId, w.WorkcentreID, w.SiteId, sr.OperationTypeId
FROM Initialsourcerulesources sr JOIN Ih#workcentres w ON (w.SiteId = sr.SiteId)
WHERE sr.SiteId IS NOT NULL
AND w.IsProductionSource = 1
UNION
SELECT sr.InitialSourceRuleId, w.WorkcentreID, w.SiteId, sr.OperationTypeId
FROM InitialSourceRuleSources sr JOIN Ih#workcentres w ON (w.WorkcentreId = sr.WorkcentreId)
WHERE sr.WorkcentreId IS NOT NULL
AND w.IsProductionSource = 1
top
IH#InitialSources
SELECT s.Id, s.SiteMaterialUsageId, s.WorkcentreId, OperationTypeId, OperationTypeName,
l.LocationName, m.MaterialName, eu.EnduseDescription Enduse, ec.LocationName EndCustomer, WorkcentreName, SiteName
FROM initialsources s
JOIN SiteMaterialUsages smu ON (smu.Id = s.SiteMaterialUsageId)
JOIN Locations l ON (l.Id = smu.LocationId)
JOIN Materials m ON (m.Id = smu.MaterialId)
LEFT JOIN EndUses eu ON eu.Id = smu.EndUseId
LEFT JOIN Locations ec ON ec.Id = smu.EndCustomerId
JOIN IH#Workcentres wc ON (wc.WorkcentreId = s.WorkcentreId)
LEFT JOIN OperationTypes ot
ON ot.ID = s.OperationTypeId
top
IH#Inventories
SELECT l.LocationCode WarehouseCode, l.LocationName WarehouseName, m.MaterialCode, m.MaterialName, i.*
FROM   Inventories i
JOIN   SiteMaterialUsages smu
ON     i.SiteMaterialUsageID = smu.Id
JOIN   Locations l
ON     smu.LocationId = l.Id
JOIN   Materials m
ON     m.Id = smu.MaterialId
top
IH#InventoryProfiles
SELECT l.LocationName, s.SiteName, c.CompanyName, MaterialName, cl.LocationName CustomerName,
ip.* FROM InventoryProfiles ip
JOIN Materials m ON m.Id = ip.MaterialId
LEFT JOIN Locations l ON l.ID = ip.LocationId
LEFT JOIN Locations cl ON cl.ID = ip.ConsignmentLocationId
LEFT JOIN Sites s  ON s.ID = ip.SiteId
LEFT JOIN Companies c ON c.ID = ip.CompanyId
top
IH#Journeys
SELECT j.Id JourneyId,
s.SiteName FromSite,
t.LocationName ToLocationName,
f.LocationName FromLocationName,
m.WorkcentreName FromWorkcentreName,
IsDEfault, isInternal,
QuantityLegs,
TimePeriod
FROM Journeys j
JOIN Sites s ON (s.Id = j.FromSiteId)
JOIN Locations f ON f.Id = j.FromLocationId
JOIN Locations t ON t.Id = j.ToLocationId
JOIN IH#MainWarehouses m ON m.SiteId = s.Id
top
IH#LastDDQLog
SELECT TaskId, ID, RequestId, LogTimeStamp, LogSource, LogText FROM
(
SELECT DENSE_RANK() OVER(ORDER BY TaskId DESC) r, l.* FROM DDQLOg l
)
WHERE r = 1
ORDER BY ID
top
IH#LastForecastLogs
Select Id, Action, Description, Stamp, Stamp - Lag(Stamp) OVER
(ORDER BY Id,Stamp) Diff
from ProcessLogs
Where ProcessId IN (Select Max(Id) from
Processes Where ProcessType = 'Forecast')
Order by Id
top
IH#LastProcessLogs
Select Id, Action, Description, Stamp, Stamp - Lag(Stamp) OVER
(ORDER BY Stamp) Diff
from ProcessLogs
Where ProcessId IN (Select Max(Id) from
Processes)
Order by Id
top
IH#LastReplenishmentLogs
Select Id, Action, Description, Stamp, Stamp - Lag(Stamp) OVER
(ORDER BY Id,Stamp) Diff
from ProcessLogs
Where ProcessId IN (Select Max(Id) from
Processes Where ProcessType = 'Replenishment')
Order by Id
top
IH#LastReplenishmentTraceLogs
Select Id, Action, Description, Stamp, Stamp - Lag(Stamp) OVER
(ORDER BY Id,Stamp) Diff,
(Stamp - First_Value(Stamp) OVer (Order by Id, Stamp))  TotalTime
from ProcessLogs
Where ProcessId IN (Select Max(Id) from
Processes Where ProcessType = 'Replenishment')
AND Action = 'ReplenishmentTrace'
Order by Id
top
IH#LastSupercessions
SELECT * FROM
(
SELECT s.*,  row_number() OVER(PARTITION BY SiteMaterialUsageID ORDER BY StartDate DESC) r
FROM   IH#MaterialSupercessions s
WHERE  Status = 0
AND    EXISTS (SELECT 1
        FROM   SiteMaterialUsages smu
        WHERE  smu.Id = s.OnSiteMaterialUsageId
        AND    smu.Status = 1)
)
WHERE r = 1
top
IH#LatestInventories
WITH inventory AS
(
 SELECT Id, SiteMaterialUsageId, ConsignmentLocationId, stockType, Weight, 
        Datefrom
   FROM Inventories i
  WHERE i.DateFrom = (SELECT MAX(i2.DateFrom) FROM Inventories i2
                       WHERE i2.SiteMaterialUsageId = i.SiteMaterialUsageId 
                         AND NVL(i2.ConsignmentLocationId,0) = NVL(i.ConsignmentLocationId,0) 
                         AND i2.StockType = i.StockType
                         AND i2.DateFrom <= core.GetTruncatedInternalDate
                         )                               
)
SELECT SiteMaterialUsageId, ConsignmentLocationId,
       Standard_Stock AS StandardStock,
       Standard_StockDate AS StandardStockDate,
       Customer_Stock AS CustomerStock, Customer_StockDate AS CustomerStockDate,
       InTransit_Stock AS InTransitStock, InTransit_StockDate AS InTransitStockDate,
       Quarantine_Stock AS QuarantineStock, Quarantine_StockDate AS QuarantineStockDate
FROM   Inventory
PIVOT (MIN(Weight) AS Stock, 
       MIN(DateFrom) AS StockDate
       FOR StockType IN ('Standard' AS STANDARD, 'Customer' AS Customer,
                         'InTransit' AS InTransit, 'Quarantine' AS Quarantine))

top
IH#LatestSupplierInventories
SELECT SiteMaterialUsageId, SupplierType, SUM(Quantity) Quantity
FROM
(
SELECT SiteMaterialUsageId, DateFrom, SupplierId, Quantity, SupplierType,
ROW_NUMBER() OVER(PARTITION BY SiteMaterialUsageId, SupplierId ORDER BY DateFrom DESC) r
FROM Supplierinventories SI
JOIN Suppliers s
ON s.Id = si.SUPPLIERID
WHERE DateFrom <= TRUNC(core.getInternalDate)
)
WHERE r = 1
GROUP BY SiteMaterialUsageId, SupplierType
top
IH#LiveOptimizedRuns
SELECT mr.WorkCentreId, mr.StartDate, mr.FinishDate, mr.TargetStartDate, 
       mb.BlockCode, mr.RunCode, mr.MaterialBlockId, mr.Id,
       mr.MaterialBlockId SequenceNo,
       DENSE_RANK() OVER (PARTITION BY mr.WorkCentreId ORDER BY mr.StartDate, mr.Id) PositionNo, 
       mr.InitialDuration, 
       (mr.FinishDate - GREATEST(NVL(mr.TargetStartDate, mr.StartDate), mr.StartDate)) * 24 * 60 Duration,
       NVL(mr.SwitchoverDuration,0) AS SwitchoverDuration, mr.ProcessRate Rate,
       mrp.GradeId, mrp.GradeCode, 
       MAX(DECODE(mrs.RunStatusCode, 'Open', 0, 1)) 
          OVER (PARTITION BY mr.WorkCentreId ORDER BY mr.StartDate ROWs BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) IsReadOnly, 
       mr.RunType,
       mrs.RunStatusCode,
       DECODE(mr.RunType, 'opportunistic', 1, 0) OppBlock,
       DECODE(mr.RunType, 'floatingShut', 1, 0) FSBlock,
       DECODE(mrs.RunStatusCode, 'Frozen', 1, 0) IsFrozen
  FROM MaterialRuns mr
  JOIN MaterialBlocks mb ON mb.Id = mr.MaterialBlockId
  JOIN MaterialRunStatuses mrs ON mrs.Id = mr.MaterialRunStatusId
  LEFT JOIN (SELECT mrp.MaterialRunId, gp.GradeId, gp.GradeCode,
                    DENSE_RANK() OVER (PARTITION BY mrp.MaterialRunId ORDER BY GradeId) r  
               FROM MaterialRunProducts mrp, GradeProperties gp 
              WHERE mrp.ProductName = gp.GradeCode) mrp ON mrp.MaterialRunId = mr.Id AND mrp.r = 1
 ORDER BY mr.WorkCentreId, mr.StartDate, mr.Id
top
IH#LiveProductionPlans
SELECT WorkcentreName, CycleType, InitialDuration / 60 Hours, p.*
FROM ProductionPlans p
JOIN Workcentres wc
ON wc.Id = p.WorkcentreId
JOIN IH#CycleTypes ct
ON ct.CycleTypeId = p.CycleTypeId
ORDER BY OperatorUserId, WorkcentreId, SourcePeriod, StartDate
top
IH#LocationMasterRoutes
SELECT d.LocationId, mr.Id MasterRouteId, mr.FromSiteId, mr.TimePeriod, wc.Id WorkcentreId, RouteCategory
FROM MasterRoutes mr
JOIN IH#DetailsLocation d
ON (d.DetailId = mr.DetailId)
JOIN Sites s
ON s.Id = mr.FromSiteId
JOIN Locations l ON l.SiteId = s.Id
JOIN Workcentres wc
ON wc.LocationId = l.Id
top
IH#Locations
WITH p AS
 (SELECT * FROM IH#DefaultParameters)
SELECT l.Id, l.LocationName, l.LocationCode, l.LocationCode || ' ' || l.LocationName FullLocationName,
        l.LocationName || ' ' || l.LocationCode FullLocationCode, CompanyName, l.Capacity, l.AllocatedStock, l.DefaultCustomerForecast,
       l.OrderAutoConfirmPeriod, CustomerRankDesc, cl.CalendarName, sm.SafetystockmethodDesc,
       tl.LocationName TransportLocation, sl.LocationName StockLocation, wl.LocationName WarehouseLocation, s.SiteName,
       cur.CurrencyName, l.CustomerRankId, l.SafetyStockMethodId,
       NVL(l.CalendarId, p.DefaultCalendarId) CalendarId,
       l.CompanyId, l.StockLocationId, l.WarehouseLocationId, l.SiteId, l.CurrencyId, l.TransportLocationId,
       l.ForecastRangeId, NVL(l.UseTradingDays, p.UseTradingDays) UseTradingDays,
       rl.ReplacedLocations, rl.ReplacedByLocation,
       (SELECT NVL(MIN(1),0) FROM dual WHERE EXISTS (SELECT 1 FROM Workcentres wc WHERE wc.LocationId = l.Id)) HasWorkcentre,
       HierarchyName1,  HierarchyName2, HierarchyName3, HierarchyName4, HierarchyName5,
        HierarchyName6, HierarchyName7, HierarchyName8, HierarchyName9, HierarchyName10,
        HierarchyName11,  HierarchyName12, HierarchyName13, HierarchyName14, HierarchyName15,
        HierarchyCode1, HierarchyCode2, HierarchyCode3, HierarchyCode4, HierarchyCode5,
        HierarchyCode6, HierarchyCode7, HierarchyCode8, HierarchyCode9, HierarchyCode10,
        HierarchyCode11, HierarchyCode12, HierarchyCode13, HierarchyCode14, HierarchyCode15,
        l.LocationStatus
FROM   Locations l
CROSS  JOIN p
LEFT JOIN ExpandedLocationsSpec es
ON (es.LocationId = l.Id)
LEFT   JOIN CustomerRanks cr
ON     (cr.Id = NVL(l.CustomerRankId, p.DefaultCustomerRankId))
LEFT   JOIN SafetyStockMethods sm
ON     (sm.Id = NVL(l.SafetyStockMethodId, p.DefaultSafetyStockMethodId))
LEFT   JOIN Calendars cl
ON     (cl.Id = NVL(l.CalendarId, p.DefaultCalendarId))
LEFT   JOIN Companies c
ON     (c.Id = l.CompanyId)
LEFT   JOIN Locations tl
ON     (tl.Id = l.TransportLocationId)
LEFT   JOIN Locations sl
ON     (sl.Id = l.StockLocationId)
LEFT   JOIN Locations wl
ON     (wl.Id = l.WarehouseLocationId)
LEFT   JOIN Sites s
ON     (s.Id = l.SiteId)
LEFT   JOIN Currencies cur
ON     (cur.Id = NVL(l.CurrencyId, p.InternalCurrencyId))
LEFT   JOIN IH#ReplacedLocations rl
ON     (rl.ToLocationId = l.Id)
LEFT   JOIN IH#ReplacedByLocation rl
ON     (rl.FromLocationId = l.Id)
top
IH#LocationStockStatus
SELECT r.LocationId,  DateFrom, OverallOpening, OverallClosing, r.SafetyStock, r.SafetyStockPercentWarning,
CASE
                        WHEN DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < 0
                             THEN 1
                        WHEN (SELECT VALUE FROM SystemParameters WHERE ParameterName = 'StockLevelAtZeroWarning') = 'InventoryLessOrEqualZero'
                             AND r.SafetyStock > 0
                             AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) = 0
                             THEN 1
                        WHEN r.SafetyStock > 0 AND r.SafetyStockPercentWarning > 0
                             AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < r.SafetyStock * r.SafetyStockPercentWarning / 100
                             THEN 2
                        WHEN r.SafetyStock > 0 AND OverallOpening < r.SafetyStock
                             THEN 3
                        WHEN r.MaxSafetyStock IS NOT NULL AND OverallOpening > r.MaxSafetyStock
                             THEN 4
                        WHEN wp.Value IN ('Warning', 'Limit') AND r.MaxCapacity > 0 AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) > r.MaxCapacity
                             THEN 5
                        ELSE 9
                    END StockStatus
 FROM  (
 SELECT s.LocationId, s.WorkcentreId, DateFrom, SUM(OverallOpening) OverallOpening,
 SUM(OverallClosing) OverallClosing, SUM(SafetyStock) SafetyStock, SUM(MaxSafetyStock) MaxSafetyStock, MIN(l.Capacity) MaxCapacity,
 MIN(s.SafetyStockPercentWarning) SafetyStockPercentWarning
 FROM  RealInventoryProfiles v JOIN IH#WHSkus s
 ON s.SiteMaterialUsageId = v.SiteMaterialUsageId
 AND NVL(S.ConsignmentLocationId,0) = NVL(v.ConsignmentLocationId,0)
 JOIN Locations l ON l.Id = s.LocationId
 GROUP BY s.LocationId, s.WorkcentreId, DateFrom
 ) r
 JOIN IH#WorkcentrePArameters wp ON wp.ParameterName = 'MaxCapacityBehaviour' AND r.WorkcentreId = wp.WorkcentreID
 CROSS JOIN (SELECT NVL(MIN(VALUE), 'Closing') StockStateField FROM SystemParameters WHERE ParameterName = 'RPStockStateField') p
 
top
IH#MainWarehouses
SELECT *
FROM  (
SELECT s.Id SiteId, wc.Id WorkcentreId, l.Id LocationId, l.LocationCode, l.LocationName, s.SiteCode, s.SiteName,
       wc.WorkcentreCode, wc.WorkcentreName, To_Number(NVL(wp.Value, wpt.DefaultValue)) IsMainWarehouse,
       COUNT(1) over(PARTITION BY siteid) Quantity, ROW_NUMBER() over(PARTITION BY siteid ORDER BY l.Id) ByOrder,
       CASE
           WHEN To_Number(NVL(wp.Value, wpt.DefaultValue)) = 1 THEN
            1
           WHEN COUNT(1) over(PARTITION BY siteid) = 1 THEN
            1
           WHEN ROW_NUMBER() over(PARTITION BY siteid ORDER BY l.Id) = 1
               AND SUM(To_Number(NVL(wp.Value, wpt.DefaultValue))) over(PARTITION BY siteid) = 0 THEN
            1
           ELSE
            0
       END IsMain
FROM   Locations l, Workcentres wc, WorkcentreTypes wct, Sites s, WorkCentreParameters wp, WorkCentreParameterTypes wpt
WHERE  WorkcentreTypeName IN ('Warehouse')
AND    wc.WorkcentreTypeId = wct.Id
AND    wc.LocationId = l.Id
AND    l.SiteId = s.Id
AND    wc.ID = wp.WorkCentreId
AND    wp.ParameterTypeId = wpt.ID
AND    wpt.ParameterName = 'IsMainWarehouse'
         )
WHERE  IsMain = 1

top
IH#MappedCharacteristics
SELECT PropertyViewName ViewName, PropertyViewCode ViewCode,
'Code' || OrderNo FieldCode
FROM Propertiesiplanview
UNION ALL
SELECT HierarchyViewName ViewName, HierarchyViewCode ViewCode,
'HierarchyCode' || OrderNo FieldCode
FROM HierarchyLevelsIPlanView
top
IH#MappedFields
SELECT UPPER(PropertyViewName) AS FieldViewName, UPPER(FieldPropertyValue) FieldName FROM PropertiesIPlanView
UNION ALL
SELECT UPPER(PropertyViewCode), UPPER(FieldPropertyCode) FROM PropertiesIPlanView
UNION ALL
SELECT UPPER(HierarchyViewCode), UPPER(FieldHierarchyCode) FROM Hierarchylevelsiplanview
UNION ALL
SELECT UPPER(HierarchyViewName), UPPER(FieldHierarchyValue) FROM Hierarchylevelsiplanview
UNION ALL
SELECT UPPER(PropertyViewName), UPPER(FieldProperty) FROM EndUsePropertiesIPlanView
UNION ALL
SELECT 'ENDUSEDESCRIPTION', 'ENDUSEDESCRIPTION' FROM dual
UNION ALL
SELECT 'PRODUCTNAME', 'PRODUCTNAME' FROM dual
UNION ALL
SELECT 'LOCATIONNAME', 'LOCATIONNAME' FROM dual
UNION ALL
SELECT 'FULLLOCATIONNAME', 'FULLLOCATIONNAME' FROM dual
UNION ALL
SELECT 'PRODUCTCODE', 'PRODUCTCODE' FROM dual
UNION ALL
SELECT 'LOCATIONCODE', 'LOCATIONCODE' FROM dual
UNION ALL
SELECT 'FULLLOCATIONCODE', 'FULLLOCATIONCODE' FROM dual
UNION ALL
SELECT 'ALTERNATEPRODUCT', 'ALTERNATEPRODUCT' FROM dual
UNION ALL
SELECT 'CURRENCYDESCRIPTION', 'CURRENCYDESCRIPTION' FROM dual
UNION ALL
SELECT 'CURRENCYNAME', 'CURRENCYNAME' FROM dual
UNION ALL
SELECT 'MATERIALTYPENAME', 'MATERIALTYPENAME' FROM dual
UNION ALL
SELECT 'ENDCUSTOMERNAME', 'ENDCUSTOMERNAME' FROM dual
UNION ALL
SELECT 'ENDCUSTOMERCODE', 'ENDCUSTOMERCODE' FROM dual
  
top
IH#MasterRoutes
    
SELECT mr.Id, SiteName, SiteCode, COST, TimePeriod, 
HierarchyCode1, HierarchyCode2, HierarchyCode3, HierarchyCode4, HierarchyCode5,
HierarchyCode6, HierarchyCode7, HierarchyCode8, HierarchyCode9, HierarchyCode10,
HierarchyCode11, HierarchyCode12, HierarchyCode13, HierarchyCode14, HierarchyCode15,
FromSiteId, DetailId
FROM MasterRoutes mr JOIN HierarchyPropertyDetails d ON d.Id = mr.DetailId
JOIN Sites s ON mr.Fromsiteid = s.Id
top
IH#MaterialCharacteristics
SELECT m.MaterialId, d.Id CharacteristicId, m.MaterialTypeId,
d.Characteristic1, d.Characteristic2, d.Characteristic3, d.Characteristic4, d.Characteristic5,
d.Characteristic6, d.Characteristic7, d.Characteristic8, d.Characteristic9, d.Characteristic10
      FROM MaterialPropsSpec m
        JOIN Materials mf ON (mf.Id = m.MaterialId)
        LEFT JOIN Propertycharacteristics d
      ON (
                (d.Code1 IS NULL OR d.Code1 = m.code1)
            AND (d.Code2 IS NULL OR d.Code2 = m.code2)
            AND (d.Code3 IS NULL OR d.Code3 = m.code3)
            AND (d.Code4 IS NULL OR d.Code4 = m.code4)
            AND (d.Code5 IS NULL OR d.Code5 = m.code5)
            AND (d.Code6 IS NULL OR d.Code6 = m.code6)
            AND (d.Code7 IS NULL OR d.Code7 = m.code7)
            AND (d.Code8 IS NULL OR d.Code8 = m.code8)
            AND (d.Code9 IS NULL OR d.Code9 = m.code9)
            AND (d.Code10 IS NULL OR d.Code10 = m.code10)
            AND (d.Code11 IS NULL OR d.Code11 = m.code11)
            AND (d.Code12 IS NULL OR d.Code12 = m.code12)
            AND (d.Code13 IS NULL OR d.Code13 = m.code13)
            AND (d.Code14 IS NULL OR d.Code14 = m.code14)
            AND (d.Code15 IS NULL OR d.Code15 = m.code15)
            AND (d.Code16 IS NULL OR d.Code16 = m.code16)
            AND (d.Code17 IS NULL OR d.Code17 = m.code17)
            AND (d.Code18 IS NULL OR d.Code18 = m.code18)
            AND (d.Code19 IS NULL OR d.Code19 = m.code19)
            AND (d.Code20 IS NULL OR d.Code20 = m.code20)
            AND (d.Code21 IS NULL OR d.Code21 = m.code21)
            AND (d.Code22 IS NULL OR d.Code22 = m.code22)
            AND (d.Code23 IS NULL OR d.Code23 = m.code23)
            AND (d.Code24 IS NULL OR d.Code24 = m.code24)
            AND (d.Code25 IS NULL OR d.Code25 = m.code25)
            AND (d.Code26 IS NULL OR d.Code26 = m.code26)
            AND (d.Code27 IS NULL OR d.Code27 = m.code27)
            AND (d.Code28 IS NULL OR d.Code28 = m.code28)
            AND (d.Code29 IS NULL OR d.Code29 = m.code29)
            AND (d.Code30 IS NULL OR d.Code30 = m.code30)
          )
top
IH#MaterialConfigurations

SELECT MaterialCode, MaterialName, ProductRouteName, pc.SITE,
       core.AsCsv(CAST(COLLECT(to_char(OrderNo) || ':' || OperationTypeName || ' (' || to_char(MultiPlier) || '/' ||
                     to_char(Divider) || ')') AS ParameterArray), ' ') Configuration
FROM   Materials m
JOIN   Productionconfigurations pc
ON     pc.MaterialId = m.Id
JOIN   ProductRouteStages prs
ON     prs.Productrouteid = pc.ProductRouteId
JOIN   OperationTypes ot
ON     ot.Id = prs.Operationtypeid
JOIN   ProductRoutes pr
ON     pr.Id = pc.ProductRouteId
LEFT   JOIN Operationtypeconversions otc
ON     otc.OperationTypeId = prs.OperationTypeId
AND    otc.ProductionConfigurationId = pc.Id
GROUP  BY MaterialCode, MaterialName, ProductRouteName, pc.Site
top
IH#MaterialHashCodes
SELECT em.MaterialId, MaterialName, MaterialCode, MaterialProperties, m.MaterialTypeId,
core.AsCsv(CAST(COLLECT(pv.PropertyValueCode ORDER BY p.OrderNo) AS ParameterArray), ' | ') MaterialHashCode
FROM Expandedmaterials em
JOIN PropertyValues pv ON pv.Id = em.Propertyvalueid
JOIN Propertiesiplanview p ON p.Id = pv.PropertyId
JOIN MAterials m ON m.Id = em.MaterialId
GROUP BY em.MaterialId, MaterialName, MaterialCode, MaterialProperties, m.MaterialTypeId
top
IH#MaterialRunCapacities
SELECT mr.Id, RunCode, BlockRunCode, wc.Workcentreid, WorkcentreCode, WorkcentreName, SiteCode, SiteName,
       wc.SiteId, StartDate, FinishDate,
       TRUNC(FinishDate, 'IW') FinishWeek,
       TRUNC(FinishDate, 'month') FinishMonth,
       mr.NominalCapacity,
       Quantity Capacity,
       NVL(FirmOrdersWeight, 0) FirmOrdersWeight, NVL(TentativeOrdersWeight, 0) TentativeOrdersWeight,
       Quantity - NVL(FirmOrdersWeight, 0) FreeFirmCapacity,
       Quantity - NVL(FirmOrdersWeight, 0) - NVL(TentativeOrdersWeight, 0) FreeCapacity
FROM   MaterialRuns mr
LEFT   JOIN (SELECT oo.MaterialRunId,
                    SUM(CASE
                            WHEN ols.OrderLineStatusCode IN ('Firm', 'Completed') THEN
                             GREATEST(0, oo.Quantity - oo.QuantityComplete)
                            ELSE
                             0
                        END) FirmOrdersWeight,
                    SUM(CASE
                            WHEN ols.OrderLineStatusCode IN ('System') THEN
                             GREATEST(0, oo.Quantity - oo.QuantityComplete)
                            ELSE
                             0
                        END) TentativeOrdersWeight
             FROM   OrderOperations oo
             JOIN   OrderLines ol
             ON     ol.Id = oo.OrderLineId
             JOIN   Orderlinestatuses ols
             ON     ols.Id = ol.OrderLineStatusId
             WHERE  oo.MaterialRunId IS NOT NULL
             GROUP  BY oo.MaterialRunId) r
ON     mr.Id = r.MaterialRunId
JOIN   IH#WorkCentres wc
ON     wc.WorkcentreId = mr.WorkcentreId
top
IH#MaterialRunDurations
SELECT mr.Id, RunCode, BlockRunCode, wc.Workcentreid, WorkcentreCode, WorkcentreName, SiteCode, SiteName,
       wc.SiteId, StartDate, FinishDate,
       TRUNC(FinishDate, 'IW') FinishWeek,
       TRUNC(FinishDate, 'month') FinishMonth,
       ProcessRate,
       NVL(r.Quantity,0) OrderOperationQuantity,
       mr.InitialDuration - NVL(r.DurationInMinutes,0) FreeDuration,
       mr.NominalCapacity,
       mr.Quantity,
       DECODE(ProcessRate, 0, 0, NVL(r.Quantity,0) + (mr.InitialDuration - NVL(r.DurationInMinutes,0)) * ProcessRate/60) Capacity,
       DECODE(ProcessRate, 0, 0, (mr.InitialDuration - NVL(r.DurationInMinutes,0)) * ProcessRate/60) FreeCapacity
  FROM MaterialRuns mr
  JOIN MaterialRunStatuses mrs ON mrs.Id = mr.MaterialRunStatusId
  JOIN IH#Workcentres wc ON mr.WorkcentreId = wc.workcentreId
  LEFT JOIN 
  (
     SELECT oo.MaterialRunId, 
            SUM(DECODE(r.Rate, 0, DECODE(oo.Rate, 0, 0, oo.Quantity / oo.Rate * 60), oo.Quantity / r.Rate * 60)) DurationInMinutes, 
            SUM(oo.Quantity) Quantity
       FROM OrderOperations oo
       JOIN OrderLines ol ON ol.Id = oo.OrderLineId
       JOIN OrderlineStatuses ols ON ols.Id = ol.OrderLineStatusId
        AND ols.OrderLineStatusCode != 'Cancelled'
       JOIN IVBS#ActualProductionRates r ON r.MaterialId = ol.MaterialId
        AND r.WorkcentreId = oo.Workcentreid
       JOIN MaterialRuns mr ON mr.Id = oo.MaterialRunId
       JOIN MaterialRunStatuses mrs ON mrs.Id = mr.MaterialRunStatusId  
      WHERE mrs.RunStatusCode NOT IN ('NonValid', 'Complete', 'Started')
      GROUP BY oo.MaterialRunId
  ) r ON r.MaterialRunId = mr.Id
 WHERE mrs.RunStatusCode NOT IN ('NonValid', 'Complete', 'Started')
top
IH#MaterialRuns
 SELECT mr.Id,
       w.WorkcentreCode,
       w.WorkcentreName,
       mb.BlockCode,
       mr.RunCode,
       mrs.RunStatusName,
       mrs.RunStatusCode,
       mr.RunType,
       mr.NominalCapacity,
       mr.Quantity,
       mr.WasteTime,
       mr.ProcessRate,
       mr.StartDate,
       mr.FinishDate,
       DECODE(NVL(wp.Value,100), 100, mr.FinishDate, GreaTest(mr.StartDate, NVL(mr.TargetStartDate, mr.StartDate)) + NVL(wp.Value,100) * mr.InitialDuration / 1440 / 100) CalculatedFinishDate,
       mr.InitialDuration,
       mr.SwitchoverDuration,
       mr.FPReleaseDate,
       mr.MaterialBlockId,
       mr.SpecificWeight,
       mr.InsertUserId,
       mr.InsertDate,
       mr.UpdateUserId,
       mr.UpdateDate,

       mr.MaterialRunStatusId,
       mr.WorkCentreId,
       mr.TargetStartDate,
       mr.UpdateOrderDates,
       mr.BlockRunCode,
       mr.IsChanged,
       MIN(mr.StartDate) OVER (PARTITION BY mr.MaterialBlockId) BlockStartDate,
       MAX(mr.FinishDate) OVER (PARTITION BY mr.MaterialBlockId) BlockFinishDate,
       CASE WHEN w.DDQLocked = 1 AND mr.StartDate >= wrp.FrozenPeriodEnd THEN 1 ELSE 0 END AS DDQLocked,
       QuantityComplete,
       CASE
           WHEN ProcessRate = 0 THEN
            0
           ELSE
            CASE
                WHEN QuantityComplete / (ProcessRate / 60) > InitialDuration THEN
                 InitialDuration
                ELSE
                 QuantityComplete / (ProcessRate / 60)
            END
       END CompletedDuration,
       CASE
           WHEN ProcessRate = 0 THEN
            InitialDuration
           ELSE
            GREATEST(0, InitialDuration - (QuantityComplete / (ProcessRate / 60)))
       END RemainingDuration,
       ProductionUpdateTimeStamp,
	  LEAD(mrs.RunStatusCode, 1) OVER (PARTITION BY mr.WorkcentreId ORDER BY mr.StartDate, mr.FinishDate) NextRunStatusCode
  FROM MaterialRuns mr
  JOIN MaterialBlocks mb
  ON mb.Id = mr.MaterialBlockId
  JOIN WorkCentres w ON w.Id = mr.WorkCentreId
  JOIN MaterialRunStatuses mrs on mrs.ID = mr.MaterialRunStatusId
  JOIN (SELECT wp.WorkCentreId,
               NVL(wp.Value, wpt.DefaultValue) AS Value
          FROM WorkCentreParameters wp, WorkCentreParameterTypes wpt
         WHERE wp.parametertypeid = wpt.ID
           AND wpt.parametername = 'RunOutputDelay') wp ON mr.WorkCentreId = wp.WorkCentreId
  LEFT JOIN WorkCentreROParameters wrp ON wrp.WorkCentreId = w.Id
top
IH#Materials
SELECT m.Id, m.MaterialName, m.MaterialCode, mt.MaterialTypeName, sm.MaterialName SourceMaterialName,
       smt.MaterialTypeName SourceMaterialTypeName, m.ForecastStartDate, m.ForecastFinishDate,
       m.ReplenishmentStartDate, m.ReplenishmentFinishDate, 
       em.Value1, em.Value2, em.Value3, em.Value4, em.Value5, em.Value6, em.Value7, em.Value8, em.Value9, em.Value10, 
       em.Value11, em.Value12, em.Value13, em.Value14, em.Value15, em.Value16, em.Value17, em.Value18, em.Value19, em.Value20,
       em.Value21, em.Value22, em.Value23, em.Value24, em.Value25, em.Value26, em.Value27, em.Value28, em.Value29, em.Value30,
       em.Code1, em.Code2, em.Code3, em.Code4, em.Code5, em.Code6, em.Code7, em.Code8, em.Code9, em.Code10,
       em.Code11, em.Code12, em.Code13, em.Code14, em.Code15, em.Code16, em.Code17, em.Code18, em.Code19, em.Code20,
       em.Code21, em.Code22, em.Code23, em.Code24, em.Code25, em.Code26, em.Code27, em.Code28, em.Code29, em.Code30,
       em.Characteristic1, em.Characteristic2, em.Characteristic3, em.Characteristic4, em.Characteristic5,
       em.Characteristic6, em.Characteristic7, em.Characteristic8, em.Characteristic9, em.Characteristic10,
       m.MaterialTypeId, m.SourceMaterialId, m.SiteId, ProductRoutes

FROM   Materials m
JOIN   MaterialPropsSpec em
ON     (em.MaterialId = m.Id)
JOIN   MaterialTYpes mt
ON     (mt.Id = m.MaterialTypeId)
LEFT   JOIN Materials sm
ON     (sm.Id = m.SourceMaterialId)
LEFT   JOIN MaterialTypes smt
ON     (smt.Id = sm.MaterialTypeId)
LEFT   JOIN Sites s
ON     (s.Id = m.SiteId)
LEFT JOIN (SELECT MaterialId, core.AsCsv(CAST(COLLECT(DISTINCT ProductRouteName) AS ParameterArray)) ProductRoutes
           FROM   IH#ProductionConfigurations mpr
           JOIN   ProductRoutes pr
           ON     pr.Id = mpr.ProductRouteId
           GROUP  BY Materialid) r ON r.MaterialId = m.Id
top
IH#MaterialSubstitutions
SELECT ms.*,
euf.LocationId,
eut.LocationId ToLocationId,
l.LocationName,
l.LocationCode,
fm.MaterialName FromMaterialName,
fm.MaterialCode FromMaterialCode,
tm.MaterialName ToMaterialName,
tm.MaterialCode ToMaterialCode,
fm.Id FromMaterialId,
tm.Id ToMaterialId
FROM MaterialSupercessions ms
JOIN SiteMaterialUsages euf ON (ms.SiteMaterialUsageId = euf.Id)
JOIN SiteMaterialUsages eut ON (ms.OnSiteMaterialUsageId = eut.Id)
JOIN Locations l on l.Id = euf.LocationId
JOIN Materials fm ON (fm.Id = euf.MaterialId)
JOIN Materials tm ON (tm.Id = eut.MaterialId)
WHERE Type IN ('Substitution', 'Both')
top
IH#MaterialSupercessions
SELECT *
from IH#AllMaterialSupercessions
WHERE Type IN ('Supersession', 'Both', 'ReplaceLocation')
top
IH#MaterialTypeRoundingUnits
SELECT mt.Id MaterialTypeId, MaterialTypeName,
u.Id MaterialTypeUnitId, u.UnitDescription MaterialTypeUnitDesc,
qumt.UnitId QuantityMAterialTypeUnitId, qumt.UnitDescription QuantityMAterialTypeUnitDesc,
qu.UnitId DefaultQuantityUnitId, qu.UnitDescription DefaultQuantityUnitDesc,
wu.UnitId DefaultWeightUnitId,  wu.UnitDescription DefaultWeightUnitDesc,
COALESCE(u.Id, qumt.UnitId, qu.UnitId, wu.UnitId) UnitId,
'Precendences: MaterialTypeUnitDesc --> QuantityMAterialTypeUnitDesc --> DefaultQuantityUnitDesc --> DefaultWeightUnitDesc ' Precendences
FROM MaterialTYpes mt
LEFT JOIN Units u
ON u.Id = mt.RoundingUnitId
LEFT JOIN IH#BaseUnits wu
ON wu.UnitTypeName = 'Weight'
LEFT JOIN IH#BaseUnits qumt
ON qumt.UnitTypeName = 'Quantity'
AND qumt.MaterialTypeId = mt.Id
LEFT JOIN IH#BaseUnits qu
ON qu.UnitTypeName = 'Quantity'
AND qu.MAterialTypeId IS NULL
top
IH#ModelCharacteristics

	SELECT HierarchyName NAME, HierarchyDesc Description, HierarchyViewName FieldViewName, HierarchyViewCode FieldViewCode,
	FieldHierarchyCode FieldCode, FieldHierarchyValue FieldValue, 'Hierarchy' TYPE, HierarchyDesc OriginalName,
	100 + OrderNo OrderNo, HierarchyLevelNo, 1 IsConfigured, 'HierarchyCode' EntityType
	FROM   HierarchyLevelsIPlanView
	UNION ALL
	SELECT 'LocationCode' NAME, 'Location' Description, 'LocationName' FieldViewName, 'LocationCode' FieldViewCode,
	'LocationCode' FieldCode, 'LocationName' FieldValue, 'Location' TYPE, 'Location' OriginalName, 200 OrderNo,
	0 HierarchyLevelNo, 1 IsConfigured, 'LocationCode' EntityType
	FROM   dual
	UNION ALL
	SELECT PropertyName NAME, PropertyDesc Description, PropertyViewName FieldViewName, PropertyViewCode FieldViewCode,
	FieldPropertyCode FieldCode, FieldPropertyValue FieldValue, 'Property' TYPE, OriginalPropertyName OriginalName,
	300 + OrderNo OrderNo, OrderNo HierarchyLevelNo, NVL(mtp.PropertyId, 0) IsConfigured, 'PropertyCode' EntityType
	FROM   PropertiesIPlanView p
	LEFT JOIN (SELECT DISTINCT PropertyId FROM MaterialTypeProperties) mtp
	ON mtp.PropertyId = p.Id
	UNION ALL
	SELECT 'ProductCode' NAME, 'Product' Description, 'ProductName' FieldViewName, 'ProductCode' FieldViewCode,
	'ProductCode' FieldCode, 'ProductName' FieldValue, 'Product' TYPE, 'Material' OriginalName, 400 OrderNo,
	0 HierarchyLevelNo, 1 IsConfigured, 'ProductCode' EntityType
	FROM   dual
	UNION ALL
	SELECT PropertyName NAME, PropertyDesc Description, PropertyViewName FieldViewName, PropertyViewName FieldViewCode,
	FieldProperty FieldCode, FieldProperty FieldValue, 'EndUseProperty' TYPE, PropertyDesc OriginalName,
	500 + OrderNo OrderNo, OrderNo HierarchyLevelNo, 1 IsConfigured, 'EndUseCode' EntityType
	FROM   EndUsePropertiesIPlanView
	UNION ALL
	SELECT 'EndUseCode' NAME, 'Product' Description, 'EndUseDescription' FieldViewName, 'EndUseCode' FieldViewCode,
	'EndUseCode' FieldCode, 'EndUseDescription' FieldValue, 'EndUse' TYPE, 'EndUse' OriginalName,
	500 OrderNo,
	0 HierarchyLevelNo, 1 IsConfigured, 'EndUseCode' EntityType
	FROM   dual
	UNION ALL
	SELECT 'EndCustomerCode' NAME, 'EndCustomer' Description, 'EndCustomerName' FieldViewName,
	'EndCustomerCode' FieldViewCode, 'EndCustomerCode' FieldCode, 'EndCustomerName' FieldValue, 'EndCustomer' TYPE,
	'EndCustomer' OriginalName,
	600 OrderNo, 0 HierarchyLevelNo, 1 IsConfigured, 'EndCustomerCode' EntityType
	FROM   dual
	UNION ALL
	SELECT PropertyName NAME, PropertyDesc Description, PropertyViewName FieldViewName, PropertyViewName FieldViewCode,
	FieldProperty FieldCode, FieldProperty FieldValue, 'SkuProperty' TYPE, PropertyDesc OriginalName,
	700 + OrderNo OrderNo, OrderNo HierarchyLevelNo, 1 IsConfigured, 'SkuProperty' EntityType
	FROM   SkuPropertiesIPlanView
	UNION ALL
	SELECT PropertyName NAME, PropertyDesc Description, PropertyViewName FieldViewName, PropertyViewName FieldViewCode,
	FieldProperty FieldCode, FieldProperty FieldValue, 'ProductCharacteristic' TYPE, PropertyDesc OriginalName,
	800 + OrderNo OrderNo, OrderNo HierarchyLevelNo, 1 IsConfigured, 'ProductCharacteristic' EntityType
	FROM   IH#ProductCharacteristics
	UNION ALL
	SELECT HierarchyName NAME, HierarchyDesc Description, HierarchyViewName FieldViewName, HierarchyViewCode FieldViewCode,
	FieldHierarchyCode FieldCode, FieldHierarchyValue FieldValue, 'EndCustomerHierarchy' TYPE, HierarchyDesc OriginalName,
	900 + OrderNo OrderNo, HierarchyLevelNo, 1 IsConfigured, 'EndCustomerCode' EntityType
	FROM   EndCustomerLevelsIPlanView
	UNION ALL
	SELECT PropertyName NAME, PropertyDesc Description, PropertyViewName FieldViewName, PropertyViewName FieldViewCode,
	FieldProperty FieldCode, FieldProperty FieldValue, 'DerivedCharacteristic' TYPE, PropertyDesc OriginalName,
	1000 + OrderNo OrderNo, OrderNo HierarchyLevelNo, 1 IsConfigured, 'DerivedCharacteristic' EntityType
	FROM   IH#DerivedCharacteristics
	UNION ALL
	SELECT PropertyName NAME, PropertyDesc Description, PropertyViewName FieldViewName, PropertyViewName FieldViewCode,
	FieldProperty FieldCode, FieldProperty FieldValue, 'SiteProperty' TYPE, PropertyDesc OriginalName,
	1100 + OrderNo OrderNo, OrderNo HierarchyLevelNo, 1 IsConfigured, 'SiteProperty' EntityType
	FROM   SitePropertiesIPlanView
top
IH#MonthlyAllSupersededHistory
SELECT NVL(OnSiteMaterialUsageId, uh.siteMaterialUsageId) SiteMaterialUsageId, uh.DateFrom,
SUM(AdjustedHistoryWeight * NVL(ms.PERCENTAGE,100) / 100)  AllSupersededHistory
 FROM IH#MonthlyUsageHistories uh
LEFT JOIN IH#AllMaterialSupercessions ms
ON ms.SiteMaterialUsageId = uh.SiteMaterialUsageId
 GROUP BY NVL(ms.OnSiteMaterialUsageId, uh.SiteMaterialUsageId), DateFrom
top
IH#MonthlyExchangeRates
SELECT cf.CurrencyName FromCurrency, ct.CurrencyName ToCurrency, v.*
FROM MonthlyExchangeRates v
JOIN Currencies cf ON (cf.Id = v.FromCurrencyId)
JOIN Currencies ct ON (ct.Id = v.ToCurrencyId)
top
IH#MonthlyPrices
SELECT siteMaterialUsageId, CurrencyId,
TRUNC(DateFrom, 'month') MonthFrom,
DECODE(DateTo, TO_DATE('01-01-2050', 'DD-MM-YYYY'), DateTo,
  add_months(
    TRUNC(NVL(LEAD(DateFrom, 1) OVER(PARTITION BY SITEMaterialUsageId, CurrencyId ORDER BY DateFrom), DateTo), 'Month'), -1)) MonthTo,
Price
FROM   (SELECT siteMaterialUsageId, CurrencyId, DateFrom, DateTo,
ROW_NUMBER() OVER(PARTITION BY SITEMaterialUsageId, CurrencyId, TRUNC(DAteFrom, 'month') ORDER BY DateFrom DESC) r,
Price
FROM   IH#ExpandedPrices)
WHERE  r = 1
top
IH#MonthlySupersededHistory
SELECT NVL(ms.OnSiteMaterialUsageId, uh.SiteMaterialUsageId) SiteMaterialUSageID, DateFrom,
       SUM(CASE WHEN ms.StartDate IS NULL THEN Weight
            WHEN DateFrom <= ms.Startdate OR ms2.StartDate IS NULL THEN Weight * ms.PERCENTAGE / 100
            ELSE 0 END)  SupersededHistory,
       SUM(CASE WHEN ms.StartDate IS NULL THEN mtdHistory
            WHEN DateFrom <= ms.Startdate OR ms2.StartDate IS NULL THEN mtdHistory * ms.PERCENTAGE / 100
            ELSE 0 END)  mtdSupersededHistory,
       SUM(CASE WHEN ms.StartDate IS NULL THEN AdjustedHistoryWeight
            WHEN DateFrom <= ms.Startdate OR ms2.StartDate IS NULL THEN AdjustedHistoryWeight * ms.PERCENTAGE / 100
            ELSE 0 END)  AdjustedSupersededHistory
  FROM IH#MonthlyUsageHistories uh
  LEFT JOIN Ih#Allmaterialsupercessions ms
    ON ms.SITEMATERIALUSAGEID = uh.SiteMaterialUsageId
   AND ms.StartDate <= uh.DateFrom
  LEFT JOIN (SELECT SiteMaterialusageId, Min(StartDate) StartDate
               FROM Ih#Allmaterialsupercessions
              GROUP BY SiteMAterialUsageId) ms2
    ON ms2.SITEMATERIALUSAGEID = NVL(ms.OnSiteMaterialUsageId, uh.SiteMaterialUsageId)
 GROUP BY NVL(ms.OnSiteMaterialUsageId, uh.SiteMaterialUsageId), DateFrom
 ORDER BY 1,2
top
IH#MonthlyUsageHistories
SELECT hd.SiteMaterialUSageId, HistoryDate HistoryStartDate, TRUNC(DateFrom, 'month') DateFrom,
       NVL(SUM(Weight),0) Weight,
       NVL(SUM(DECODE(SIGN(dateFrom - i.internalDate), -1, weight, 0)), 0) mtdHistory,
       NVL(SUM(AdjustedWeight),0) OriginalAdjustedWeight,
       GREATEST(0, SUM(NVL(AdjustedWeight, Weight))) HistoryWeight,
       SUM(NVL(AdjustedWeight, Weight)) AdjustedHistoryWeight
FROM   UsageHistories hd
JOIN IVDP#HistoryStartDate smu
ON smu.SiteMaterialUSageId = hd.SiteMaterialUSageId
CROSS JOIN (SELECT MIN(TRUNC(core.getInternalDate)) internalDate FROM DUAL) i
GROUP  BY hd.SiteMaterialUSageId, HistoryDate, TRUNC(DateFrom, 'month')
top
IH#NavigationTasks
    SELECT TaskName, ds.Id DataSourceId, nt.IsUnrestricted, nt.Source, nt.IsSystem
    FROM NavigationTasks nt
    JOIN DataSources ds ON (UPPER(ds.Name) = UPPER(nt.Source))
top
IH#NegativeDemandCalendarDays


WITH c AS
               (
                   SELECT r.SourceSiteMaterialUsageId,
                          a.SiteMaterialUsageId,
                          Trunc(a.DateFrom - r.TimePeriod) DateFrom,
                          LAST_VALUE(DECODE(a.Consumption, 0, NULL, a.Consumption) IGNORE NULLS)
                           OVER (PARTITION BY a.SiteMaterialUsageId
                                     ORDER BY a.DateFrom
                                      ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) Consumption,
                          r.Portion
                     FROM ReplenishedCustomerDemands a, ReplenishedCustomerSKU r
                    WHERE a.SiteMaterialUsageId = r.SiteMaterialUsageId
                      AND a.DateFrom >= TRUNC(SYSDATE) - r.TimePeriod
                      AND a.DateFrom BETWEEN r.DateFrom AND r.DateTo
               ),
               cc AS
               (SELECT SourceSiteMaterialUsageId, SiteMaterialUSageId, DateFrom, Portion,
        							 IgnoreNegativeInventoryDays,
							         Consumption DailyConsumption,
                       SUM(Consumption)
                        OVER (PARTITION BY SiteMaterialUsageId
                                  ORDER BY DateFrom
                                   ROWS BETWEEN CURRENT ROW AND w.IgnoreNegativeInventoryDays - 1 FOLLOWING) Consumption
                 FROM c JOIN SiteMaterialUSages smu ON smu.Id = c.SourceSiteMaterialUsageID
								 JOIN IH#NegativeDemandWarehouses w ON w.LocationId = smu.LocationId
								 WHERE 1=1
								 AND w.IgnoreNegativeInventory = 1
								 AND w.IgnoreNegativeInventoryMethod = 'WorkingDays'

               )
               SELECT LocationName, MaterialName, DateFrom, IgnoreNegativeInventoryDays, NVL(SUM(DailyConsumption * Portion / 100),0) DailyConsumption,
               NVL(SUM(Consumption * Portion / 100),0) Consumption
                 FROM cc JOIN EV#SiteMaterialUsages smu ON smu.ID = cc.SourceSiteMAterialUsageID
                GROUP BY  LocationName, MaterialName,  DateFrom, IgnoreNegativeInventoryDays, Portion
								ORDER BY 1,2,3
top
IH#NegativeDemandWarehouses
SELECT * FROM
(
SELECT w.LocationName, w.LocationCode, w.LocationId, ParameterName, VALUE
FROM   Ih#warehouses w
JOIN   IH#WorkcentreParameters p
ON     p.WorkcentreId = w.WorkcentreID
WHERE ParameterName IN ('IgnoreNegativeInventory', 'IgnoreNegativeInventoryDays', 'IgnoreNegativeInventoryMethod')
)
pivot
       ( MIN(VALUE)
         for ParameterName IN ('IgnoreNegativeInventory' AS IgnoreNegativeInventory, 'IgnoreNegativeInventoryDays' AS IgnoreNegativeInventoryDays,
					'IgnoreNegativeInventoryMethod' as IgnoreNegativeInventoryMethod	)
       )
top
IH#NegativeDemandWorkingDays
SELECT LocationName, MaterialName, DateFrom, IsWorkingDay, SumIsWorking, IgnoreNegativeInventoryDays, DailyConsumption, SumConsumption,
CASE WHEN SumIsWorking = t.IgnoreNegativeInventoryDays AND    IsWorkingDay = 1 THEN SumConsumption ELSE NULL END Consumption
FROM   (
SELECT ip.SourceSiteMaterialUSageID, ip.IgnoreNegativeInventoryDays, ip.DateFrom,
                a.Consumption DailyConsumption,
                SUM(a.Consumption * p.Portion / 100) OVER(PARTITION BY ip.DateFrom, ip.SourceSiteMaterialUSageID, a.Sitematerialusageid ORDER BY a.Datefrom) SumConsumption,
                a.IsWorkingDay,
                SUM(a.IsWorkingDay) OVER(PARTITION BY ip.DateFrom, ip.SourceSiteMaterialUSageID, a.Sitematerialusageid ORDER BY a.Datefrom) SumIsWorking
         FROM   (SELECT DISTINCT ip.SiteMaterialUsageId SourceSiteMaterialUsageID, DateFrom, IgnoreNegativeInventoryDays
				 FROM InventoryProfiles ip
				 JOIN  IH#NegativeDemandWarehouses w ON w.LocationId = ip.LocationId
				 WHERE  w.IgnoreNegativeInventory = 1
								 AND w.IgnoreNegativeInventoryMethod = 'WorkingDays' ) ip
         JOIN   ReplenishedCustomerSKU p
         ON     p.SourceSiteMaterialUsageId = ip.SourceSiteMaterialUsageId
         JOIN   ReplenishedCustomerDemands a
         ON     a.SiteMaterialUsageId = p.Sitematerialusageid
         AND    a.DateFrom >= p.DateFrom - p.TimePeriod
         AND    a.DateFrom>= ip.DateFrom
				 ORDER BY 1,3,7


				 ) t JOIN EV#SiteMAterialUSages smu ON smu.ID = t.SourceSiteMaterialUSageID
WHERE  SumIsWorking <= t.IgnoreNegativeInventoryDays
ORDER BY 1,2,3
top
IH#NominalCosts
SELECT ec.SiteMaterialUsageId, s.LocationName, s.MaterialName, s.Enduse, s.EndCustomer, ec.Datefrom, ec.Cost, c.CurrencyName
FROM ExpandedNominalCosts ec
JOIN IH#Sku s ON s.Id = ec.SiteMaterialUsageId
CROSS  JOIN IH#DefaultParameters p
LEFT   JOIN Currencies c ON c.Id = NVL(ec.CurrencyId, p.InternalCurrencyId)
top
IH#NormalSkuStockStatus
SELECT r.SiteMaterialUsageId, r.ConsignmentLocationId, DateFrom, OverallOpening, OverallClosing, r.SafetyStock,
       s.SafetyStockPercentWarning, r.MaxSafetyStock, s.MaxCapacity, 0 Superseded,
       CASE
           WHEN DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < 0 THEN
            1
           WHEN (SELECT VALUE FROM SystemParameters WHERE ParameterName = 'StockLevelAtZeroWarning') =
                'InventoryLessOrEqualZero' AND r.SafetyStock > 0 AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) = 0 THEN
            1
           WHEN r.SafetyStock > 0 AND s.SafetyStockPercentWarning > 0 AND
                DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < r.SafetyStock * s.SafetyStockPercentWarning / 100 THEN
            2
           WHEN r.SafetyStock > 0 AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < r.SafetyStock THEN
            3
           WHEN s.MaxCapacityBehaviour IN ('Warning', 'Limit') AND s.MaxCapacity > 0 AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) > s.MaxCapacity THEN
            4
           WHEN r.MaxSafetyStock IS NOT NULL AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) > r.MaxSafetyStock THEN
            5
           ELSE
            9
       END StockStatus
FROM   RealInventoryProfilesIPlanView r
JOIN   IH#WHStockMonitoring s
ON     s.SiteMaterialUsageId = r.SiteMaterialUsageId
AND    NVL(S.ConsignmentLocationId, 0) = NVL(r.ConsignmentLocationId, 0)
CROSS JOIN (SELECT NVL(MIN(VALUE), 'Closing') StockStateField FROM SystemPArameters WHERE ParameterName = 'RPStockStateField') p
top
IH#OpeningRealProfiles View for calculation opening/closing values in real inventory profiles
SELECT SiteMaterialUSageID, ConsignmentLocationId,
              DateFrom,
              First_value(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(OrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0)
              - NVL(SUM(OrdersOut) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) Opening,
              First_value(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(OrdersIn + TentativeOrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0)
              - NVL(SUM(OrdersOut + Consumption + TentativeOrdersOut) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) OverAllOpening,
              OrdersIn, TentativeOrdersIn,
              OrdersOut, TentativeOrdersOut,
							Consumption,
              First_value(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(OrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND p.ClosingMethod PRECEDING),0)
              - NVL(SUM(OrdersOut) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING),0) Closing,
              First_value(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(OrdersIn + TentativeOrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND p.ClosingMethod PRECEDING),0)
              - NVL(SUM(OrdersOut + Consumption + TentativeOrdersOut) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING),0) OverallClosing,
              SafetyStock
             FROM RealInventoryProfiles ip
             CROSS JOIN (SELECT UseTentativeOrders, DECODE(RPClosingCalculationMethod, 'AfterDeliveryDate', 1, 0) ClosingMethod FROM IH#ReplenishmentParameters) p
             ORDER BY 1,2,3
top
IH#OrderDuration
SELECT oo.MaterialRunId, 
       ol.Id AS OrderLineId, 
       oo.WorkCentreId,
       ol.SourceMaterialId,
       oo.OrderOperationStatusId,
       ol.SourceWeight, 
       oo.Quantity,
       NVL(oo.QuantityComplete,0) AS QuantityComplete,
       mrs.RunStatusCode,   
       oos.OrderOperationStatusCode,      
       CASE WHEN mrs.RunStatusCode IN ('Complete', 'Started') THEN oo.Quantity 
            WHEN oos.OrderOperationStatusCode = 'Completed' THEN 0
            ELSE GREATEST(0, oo.Quantity - NVL(oo.QuantityComplete,0))                
       END AS RemainingQuantity,
       oo.OperationDuration AS Duration,
       oo.OperationCompletedDuration AS CompletedDuration,
       CASE WHEN mrs.RunStatusCode IN ('Complete', 'Started') THEN oo.OperationDuration
            WHEN oos.OrderOperationStatusCode = 'Completed' THEN 0 
            ELSE GREATEST(0, oo.OperationDuration - NVL(oo.OperationCompletedDuration,0))
       END AS RemainingDuration
  FROM OrderLines ol
  JOIN OrderOperations oo ON oo.OrderLineId = ol.Id
  JOIN OrderOperationStatuses oos ON oos.Id = oo.OrderOperationStatusId
  JOIN WorkCentres w ON w.Id = oo.WorkCentreId
  JOIN WorkCentreTypes wt ON wt.Id = w.WorkCentreTypeId AND wt.IsProductionSource = 1
  LEFT JOIN MaterialRuns mr ON mr.Id = oo.MaterialRunId
  LEFT JOIN MaterialRunStatuses mrs ON mrs.Id = mr.MaterialRunStatusId
 WHERE oos.OrderOperationStatusCode != 'Cancelled'
top
IH#OrderInformationCategories
SELECT CategoryInfo, ItemType, IsSelected, IsEditable
FROM OrderInformationCategories
UNION ALL
SELECT DISTINCT i.Type CategoryInfo, d.Type ItemType, 0 IsSelected, 0 IsEditable
FROM   Orderinformation i
JOIN   OrderInformationItems d
ON     d.OrderInformationId = i.Id
WHERE NOT EXISTS (SELECT 1 FROM OrderInformationCategories c where c.CategoryInfo = i.Type and c.ItemType = d.Type)

top
IH#OrderInformationConfig
SELECT CategoryInfo || '.' || ItemType DictionaryKey, IsSelected, IsEditable
FROM OrderInformationCategories
WHERE IsSelected + IsEditable > 0
top
IH#OrderInquiryPrices
SELECT smu.Id SiteMaterialUsageId, DECODE(smu.Status, 1, fp.DateFrom, ep.DateFrom) DateFrom,
DECODE(smu.Status, 1, fp.DateTo, ep.DateTo) DateTo,
DECODE(smu.Status, 1, fp.PriceCurrencyId, ep.CurrencyId) CurrencyId,
DECODE(smu.Status, 1, fp.ForecastedPrice, ep.Price) Price
  FROM SiteMaterialUsages smu
LEFT JOIN IH#ForecastedPrices fp ON fp.SiteMaterialUsageId = smu.id AND smu.Status = 1
LEFT JOIN IH#ExpandedPrices ep ON ep.SiteMaterialUsageId = smu.id AND smu.Status = 0
WHERE NOT EXISTS (SELECT 1 FROM Workcentres wc WHERE wc.LocationId = smu.LocationId)
AND DECODE(smu.Status, 1, fp.ForecastedPrice, ep.Price) IS NOT NULL
top
IH#OrderLineDeliveryWeights

SELECT OrderLineId, SUM(CASE WHEN ds.DeliveryStatusCode IN ('InTransit', 'Delivered', 'SeparatedDelivered') THEN Weight ELSE 0 END) DispatchedWeight,
SUM(CASE WHEN ds.DeliveryStatusCode IN  ('Delivered', 'SeparatedDelivered') THEN Weight ELSE 0 END) DeliveredWeight
FROM Deliveries  d
JOIN DeliveryStatuses ds
ON ds.Id = d.DeliveryStatusId
GROUP BY OrderLineId

top
IH#OrderLineReasons
SELECT * from Reasons Where ReasonType = 'OrderLine'
top
IH#OrderLines
SELECT OrderCode, ol.*
FROM OrderLines ol
JOIN OrderBooks ob
ON ob.Id = ol.OrderBookId
top
IH#OrderOperationDuration
SELECT oo.OrderLineId, 
       oo.Id AS OrderOperationId, 
       oo.WorkCentreId, 
       oo.MaterialRunId, 
       oo.StartTime StartDate,
       oo.FinishTime FinishDate,
       oo.Quantity,
       oo.QuantityComplete,
       oo.OperationDuration AS Duration,
       CASE WHEN oo.QuantityComplete = 0 then 0 ELSE oo.QuantityComplete / oo.Rate * 60 END AS DurationComplete
  FROM OrderOperations oo
  JOIN OrderOperationStatuses ols on ols.Id = oo.OrderOperationStatusId
 WHERE ols.OrderOperationStatusCode != 'Cancelled'
 AND Rate > 0
 AND MaterialRunId IS NOT NULL

top
IH#OrderOperationMovements
SELECT smu.Id SiteMaterialUSageId, smu.MaterialId, NVL(oo.DueDate, ol.DespatchDate) DueDate, m.Quantity, ol.Id OrderLineId, oo.Id OrderOperationId,
smu.Id || '-0' SkuKey
FROM OrderOperationMaterials m
JOIN OrderOperations oo
ON oo.Id = m.Orderoperationid
JOIN IH#Workcentres wc
ON wc.WorkcentreId = oo.WorkcentreId
JOIN Ih#mainwarehouses w
ON w.SiteId = wc.SiteId
JOIN SiteMaterialUsages smu
ON smu.LocationId = w.LocationId
AND smu.MaterialId = m.MaterialId
JOIN OrderLines ol
ON ol.ID =oo.ordeRLineId
top
IH#OrderOperations

SELECT OrderCode, LineNoCode, OperationNo,
WorkcentreName, WorkcentreCode,
BlockCode,
RunCode,
OrderOperationStatusCode, OrderOperationStatusName,
OrderLineStatusCode, OrderLineStatusName, OperationTypeName,
OrderBookId, OrderLineId, oo.Id  OrderOperationId, oo.WorkcentreId,
OrderLineStatusId, OrderOperationStatusId, oo.UnitId, OperationTypeId,
oo.Quantity, oo.QuantityComplete,
oo.OperationDuration, oo.OperationCompletedDuration,
oo.StartTime, oo.FinishTime, oo.Rate, oo.ProcessDuration
from OrderOperations oo
JOIN OrderLines ol
ON ol.Id = oo.OrderLineId
JOIN OrderBooks ob
ON ob.Id = ol.OrderBookId
JOIN Workcentres wc ON (wc.Id = oo.WorkcentreId)
JOIN OrderOperationStatuses oos ON (oos.Id = oo.OrderOperationStatusId)
JOIN OrderLineStatuses ols ON (ols.Id = ol.OrderLineStatusId)
JOIN OperationTypes ot ON ot.Id = oo.OperationTypeId
LEFT JOIN MaterialRuns mr ON (mr.Id = oo.MaterialRunId)
LEFT JOIN MaterialBlocks mb ON (mb.Id = mr.MaterialBlockId)
top
IH#OrdersForExternalSystem
SELECT e.*
FROM Entitiesforexternalsystem e
LEFT JOIN OrderOperations oo
ON oo.OrderLineId = e.EntityId
LEFT JOIN Ih#workcentreparameters wp
ON wp.WorkcentreId = oo.WorkcentreId
AND ParameterName = 'SuspendOrderStatusMessages'
WHERE EntityType = 'OrderLine'
AND NVL(wp.Value,0) = 0
top
IH#OverrideWorkCentres
SELECT wc.Id WorkcentreId, wc.WorkcentreName, wc.WorkcentreCode, mwh.WorkcentreId MainWarehouseId, wp.Value,
NVL(owc.Id, mwh.WorkcentreId) OverrideWarehouseId,
NVL(owc.WorkcentreName, mwh.WorkcentreName) OverrideWarehouseCode,
NVL(owc.WorkcentreCode,mwh.WorkcentreName) OverrideWarehouseName,
NVL(owc.LocationId, mwh.LocationId) OverrideWarehouseLocationId,
l.SiteId
FROM Workcentres wc
JOIN WorkcentreTypes wct
on wct.Id = wc.WorkcentreTypeId
JOIN Locations l ON l.Id = wc.LocationId
JOIN IH#MAINWAREHOUSES mwh
ON mwh.SiteId = l.SiteId
LEFT JOIN IH#WorkcentreParameters wp ON wp.WorkcentreId = wc.Id AND ParameterName = 'PMOverrideWarehouse' AND VALUE != 'undefined'
LEFT JOIN Workcentres owc ON owc.Workcentrecode = wp.Value
WHERE wct.IsProductionSource = 1
top
IH#PageParameters

SELECT pp.Id, PageId, PageName, pp.ParameterName, pp.ParameterDescription, ParameterType, DataType, MINVALUE, MAXVALUE, DependOn, 
       DependBehaviour, DependValues, pp.OrderNo, GroupName, Separator, DECODE(COALESCE(pp.Value, pp.DefaultValue),
        '{SYSDATE}', to_char(Trunc(core.getInternalDate, 'month'), 'YYYY-MM-DD'),
         COALESCE(pp.Value, pp.DefaultValue))  AS VALUE, pp.ParameterHint, pp.ActionId, pp.BundleId, pp.IsDevMode
FROM   PageParameters pp
JOIN PAges p ON (pp.PageId = p.Id)
top
IH#PaperMachines
SELECT wc.*
FROM   IH#Workcentres wc
WHERE  wc.IsProductionSource = 1
top
IH#PriceParameters

SELECT PriceRuleType, HistoryPricePeriods, OrdersPricePeriods, OrdersPriceFuturePeriods, PriceWeighting,
       PriceWeighting OrdersWeighting, 100 - PriceWeighting HistoryWeighting,
       add_months(TRUNC(core.getTruncatedInternalDate, 'month'), -HistoryPricePeriods) HistoryStartMonth,
       add_months(TRUNC(core.getTruncatedInternalDate, 'month'), -1) HistoryFinishMonth,
       add_months(TRUNC(core.getTruncatedInternalDate, 'month'), -OrdersPricePeriods) OrdersStartMonth,
       DECODE(OrdersPriceFuturePeriods, 0, DATE '2050-01-01',
              add_months(TRUNC(core.getTruncatedInternalDate, 'month'), OrdersPriceFuturePeriods)) OrdersFinishMonth

FROM   (SELECT ParameterName, VALUE FROM systemparameters)
pivot(MIN(VALUE)
FOR    parametername IN('OrdersPricePeriods' OrdersPricePeriods, 'OrdersPriceFuturePeriods' OrdersPriceFuturePeriods,
                        'HistoryPricePeriods' HistoryPricePeriods, 'PriceRuleType' PriceRuleType,
                        'PriceWeightingForOrdersAndHistory' PriceWeighting
                        ))

top
IH#Prices
SELECT es.SiteMaterialUsageId, s.LocationName, s.MaterialName, s.EndUse, s.EndCustomer, es.Datefrom, es.Price, c.CurrencyName,
NVL(LEAD(DateFrom) OVER(PARTITION BY es.SiteMaterialUsageId ORDER BY es.DateFrom) - 1,
            to_date('2100-01-01', 'YYYY-MM-DD')) DateTo,
CASE WHEN TRUNC(core.getInternalDate) BETWEEN DateFrom AND NVL(LEAD(DateFrom) OVER(PARTITION BY es.SiteMaterialUsageId ORDER BY es.DateFrom),
            to_date('2100-01-01', 'YYYY-MM-DD')) THEN 1 ELSE 0 END IsActive
FROM IH#ExpandedPrices es
JOIN IH#Sku s ON (s.Id = es.SiteMaterialUsageId)
CROSS  JOIN IH#DefaultParameters p
LEFT   JOIN Currencies c
ON     (c.Id = NVL(es.CurrencyId, p.InternalCurrencyId))
top
IH#ProcessLogs
SELECT PRocessName, ProcessType, p.userId, l.*, Stamp - Lag(Stamp) OVER(PARTITION BY ProcessId ORDER BY Stamp) Diff
FROM   Processes p
LEFT   JOIN ProcessLogs l
ON     l.ProcessId = p.Id
ORDER  BY l.Stamp, l.ID
top
IH#ProductCharacteristics
SELECT Id,
       CharacteristicName AS PropertyName,
       CharacteristicName AS PropertyDesc,
       UPPER('PC_' || REGEXP_REPLACE(CharacteristicName, '[^[:alnum:]_]', '')) PropertyViewName,
       'Characteristic' || ROW_NUMBER() Over(ORDER BY Id) FieldProperty,
       HierarchyLevelNO OrderNo
  FROM ProductCharacteristics
top
IH#ProductCosts
SELECT MaterialId, WorkcentreId, SiteId, Effective,
NVL(LEAD(Effective - 1) OVER (PARTITION BY MaterialId, WorkcentreId ORDER BY Effective), to_date('01-01-2050', 'DD-MM-RRRR')) NextEffective,
COST
 FROM COSTRULES cr
JOIN Ih#detailsmaterial d
ON cr.DetailId = d.DetailId
JOIN Workcentres wc
ON wc.Id = cr.WorkcentreId
JOIN Locations l
ON l.Id = wc.LocationId
top
IH#ProductionConfigurations
SELECT 0 AS Id, 0 ProductRouteId, m.Id MaterialId, m.MaterialName, m.MaterialCode, '' Site, 1 Preferred, NULL BomId
  FROM Materials m
 WHERE NOT EXISTS(SELECT 1 FROM ProductionConfigurations pc Where pc.MaterialId = m.Id)
 UNION ALL
SELECT pc.Id, pc.ProductRouteId, pc.MaterialId, m.MaterialName, m.MaterialCode, pc.site, pc.Preferred, pc.BomId
FROM ProductionConfigurations pc
JOIN Materials m
ON m.Id = pc.MaterialId
Order By 1
top
IH#ProductionPlan
WITH q AS
(
  SELECT mr.WorkCentreId, TRUNC(mr.StartDate, 'IW') SourcePeriod,
         ct.CycleTypeId, ct.CycleType, ct.Priority,
         SUM(mr.AvailableDuration) AllocationMinutes,
         SUM(mr.OrdersDuration) OrdersMinutes,
         SUM(mr.InitialDuration) DurationInMinutes
    FROM IH#RunAvailableDuration mr
    JOIN MaterialRunProducts mrp
      ON mrp.MaterialRunId = mr.Id
    JOIN IH#CycleTypes ct
      ON ct.DetailId = mrp.DetailId
   GROUP BY mr.WorkCentreId, TRUNC(mr.StartDate, 'IW'), ct.CycleTypeId, ct.CycleType, ct.Priority
  HAVING SUM(mr.AvailableDuration) + SUM(mr.OrdersDuration) > 0
)
SELECT ROW_NUMBER() OVER(ORDER By WorkCentreId, SourcePeriod, Priority, RowNum) Id,
       WorkCentreId,
       CycleTypeId,
       CycleType,
       Priority,
       SourcePeriod,
       DurationInMinutes,
       OrdersMinutes,
       AllocationMinutes,
       SourcePeriod + SUM(DurationInMinutes)
                      OVER(PARTITION BY WorkCentreId, SourcePeriod
                               ORDER BY Priority, ROWNUM) / 24 / 60 - (DurationInMinutes / 24 / 60) StartDate,
       SourcePeriod + SUM(DurationInMinutes)
                      OVER(PARTITION BY WorkCentreId, SourcePeriod ORDER BY Priority, ROWNUM) / 24 / 60 FinishDate
  FROM q
 ORDER BY WorkCentreId, SourcePeriod, Priority
top
IH#ProductionRates

SELECT r.Id ProductionRateId, d.MaterialId
FROM   ProductionRates r
JOIN   IH#DetailsMaterial d
ON     (d.DetailId = r.DetailId)

top
IH#ProductionUtilisation
WITH q AS
(
  SELECT mi.OperatorUserId, OrderNo, wc.WorkcentreTypeId, WorkcentreTypeDesc, mi.WorkcentreId, 
         DateFrom, TimePeriod, PeriodLength * 24 PeriodHours,
         SUM(NominalCapacityHours + ShutHours) TotalHours, SUM(ShutHours) ShutHours, 
         SUM(OrdersHours) OrdersHours,
         SUM(TentativeOrdersHours) TentativeOrdersHours, 
         SUM(FixedCapacityHours) FixedHours, 
         SUM(UnusedRunHours) UnusedRunHours,
         SUM(GREATEST(0, CapacityHours - FixedCapacityHours)) FreeCapacityHours
    FROM ProductionInformationData mi
    JOIN IH#Workcentres wc
      ON wc.WorkcentreId = mi.workcentreId
    JOIN IH#CycleProductionPeriods p ON p.startperiod = mi.DateFrom
   WHERE wc.IsProductionSource = 1
   GROUP BY mi.OperatorUserId, OrderNo, wc.WorkcentreTypeId, WorkcentreTypeDesc, 
            DateFrom, TimePeriod, PeriodLength, CUBE(mi.WorkcentreId)
)
SELECT OperatorUserId, q.WorkcentreTypeId, q.WorkcentreTypeDesc, q.WorkcentreId, WorkcentreName, WorkcentreCode, SiteCode,
       SiteName, DateFrom, TimePeriod, PeriodHours, TotalHours, ShutHours, OrdersHours, TentativeOrdersHours, 
       FixedHours, UnusedRunHours, FreeCapacityHours,
       CASE WHEN UnusedRunHours + ShutHours + OrdersHours + TentativeOrdersHours > TotalHours THEN 1 ELSE 0 END IsOverbooked,
       CASE WHEN UnusedRunHours + ShutHours + OrdersHours + TentativeOrdersHours = TotalHours THEN 1 ELSE 0 END IsBottleneck
  FROM q
  LEFT JOIN IH#Workcentres wc
    ON wc.WorkcentreId = q.WorkcentreId
 ORDER BY OperatorUserId, q.OrderNo,  
          DateFrom, TimePeriod, WorkcentreName NULLS FIRST, WorkcentreCode NULLS FIRST
top
IH#ProductionWorkcentres
SELECT WorkcentreCode, SiteCode, WorkcentreName, SiteName, WorkcentreTypeName, WorkcentreTypeDesc, wct.OrderNo WorkcentreTypeOrderNo,
wc.Id WorkcentreId, SiteId, wct.HasInventory, wc.LocationId
FROM Workcentres wc
JOIN Locations l
ON l.id = wc.LocationId
JOIN Sites s
ON s.Id = l.SiteId
JOIN WorkcentreTypes wct
ON wct.Id = wc.WorkcentreTypeId
WHERE wct.IsProductionSource = 1
top
IH#ProductRoutes
 SELECT 0 AS Id, 'Default' ProductRouteName
  FROM WorkCentreTypes wct
	JOIN OperationTypes ot
	ON ot.WorkCentreTypeId = wct.Id
 WHERE WorkCentreTypeName = 'Paper Machine'
   AND NOT EXISTS(SELECT 1 FROM ProductRoutes)
 UNION ALL
SELECT pr.Id, pr.ProductRouteName
  FROM ProductRoutes pr
top
IH#ProductRouteStages
 SELECT 0 AS ProductRouteId, 0 ProductRouteStageId,  'Default' ProductRouteName, 1 StageNo, WorkCentreTypeId, WorkCentreTypeName,
       1 IsLastStage, 1 CreateCampaign, '1' StageCode, 'Default' OperationTypeName, ot.Id OperationTypeId,
       1 OrderNo
  FROM WorkcentreTypes wct
	JOIN OperationTypes ot
	ON ot.WorkcentreTypeId = wct.Id
 WHERE WorkcentreTypeName = 'Paper Machine'
   AND NOT EXISTS(SELECT 1 FROM ProductRoutes)
 UNION ALL
SELECT pr.Id ProductRouteId, prs.Id ProductRouteStageId, pr.ProductRouteName, prs.OrderNo, ot.WorkCentreTypeId, wt.WorkCentreTypeName,
       NVL(Lead(0) OVER (PARTITION BY prs.ProductRouteId ORDER BY prs.OrderNo),1) IsLastStage, CreateCampaign, StageCode,
       ot.OperationTypeName, prs.OperationTypeId, prs.OrderNo
  FROM ProductRoutes pr
  JOIN ProductRouteStages prs ON prs.ProductRouteId = pr.Id
  LEFT JOIN OperationTypes ot ON ot.Id = prs.OperationTypeId
  JOIN WorkCentreTypes wt ON wt.Id = ot.WorkCentreTypeId
 ORDER BY 1, StageNo
top
IH#ProductSiteCosts

WITH c AS (
SELECT MaterialId, SiteId, Effective, AVG(COST) COST
 FROM COSTRULES cr
JOIN Ih#detailsmaterial d
ON cr.DetailId = d.DetailId
JOIN Workcentres wc
ON wc.Id = cr.WorkcentreId
JOIN Locations l
ON l.Id = wc.LocationId
GROUP BY MaterialId, SiteId, Effective
)
SELECT MaterialId, SiteId, Effective,
NVL(LEAD(Effective - 1) OVER (PARTITION BY MaterialId, SiteId ORDER BY Effective), to_date('01-01-2050', 'DD-MM-RRRR')) NextEffective,
COST
FROM c
top
IH#PublishedReports
SELECT ds.ID, ds.Description || ' (' || u.UserName || ')' Description, ds.Title Title, ds.UserId, u.UserName,
DECODE(ds.Type, 'system', 'Data sources', 'quickreport', 'Quick Reports', 'user', 'Reports', 'Unknown') GroupDescription,
DECODE(ds.Type, 'system', 'Data sources', 'quickreport', 'Quick Reports', 'user', 'Reports', 'Unknown') GroupTitle,
1 IsCheckBox
FROM  DataSources ds JOIN Users u ON (u.Id = ds.UserId)
WHERE (type = 'user' and ds.IsPublished = 1)
ORDER By ds.Description
top
IH#RebalancedOrderLines

SELECT rol.ProcessId, rol.OrderLineId, ob.OrderCode, ol.LineNoCode, mm.MaterialCode,
ROUND(rol.NewAllocatedStockWeight + rol.DispatchedWeight,3) AllocatedStockWeight,
ww.WorkcentreCode, rol.Comments, rol.TimeStamp,
rol.NewAllocatedStockWeight  - rol.AllocatedStockWeight Difference,
rol.SiteMaterialUsageId
FROM Rebalancedorderlines rol
JOIN OrderLines ol ON ol.Id = rol.OrderLineId
JOIN OrderBooks ob ON ob.Id = ol.OrderBookId
JOIN Materials mm ON mm.Id = ol.MaterialId
LEFT JOIN workcentres ww ON NVL(ol.workcentreid, ol.stockworkcentreid) = ww.id
WHERE rol.NewAllocatedStockWeight IS NOT NULL
ANd rol.IsSent = 0


top
IH#ReplacedByLocation
SELECT r.FromLocationId, l.LocationCode ReplacedByLocation
FROM Replacedlocations r JOIN locations l ON r.ToLocationId = l.id

top
IH#ReplacedLocations
SELECT r.toLocationID, listagg(l.LocationName,', ') within group(order by l.LocationCode) ReplacedLocations
FROM Replacedlocations r JOIN locations l ON r.FromLocationId = l.id
GROUP BY r.Tolocationid
top
IH#ReplenishedCustomerDemands
SELECT l.LocationName, l.LocationCode, m.MaterialName ProductName, M.MaterialCode ProductCode,
A.*
FROM ReplenishedCustomerDemands a JOIN SiteMaterialUsages smu ON smu.ID = a.SiteMaterialUsageId
JOIN Locations l ON smu.LocationId = l.Id
JOIN Materials m ON smu.MaterialId = m.Id
ORDER BY SiteMaterialUsageId, dateFrom
top
IH#ReplenishedCustomerSku
SELECT l.LocationName, l.LocationCode,
dm.MaterialName DestinationMaterialName,
dm.MaterialCode DestinationMaterialCode,
sm.MaterialName SourceMaterialName,
sm.MaterialCode SourceMaterialCode,
wc.WorkcentreCode,
sl.LocationCode SourceLocationCode,
sl.LocationName SourceLocationName,
sl.Id SourceLocationId,
sl.SiteId SourceSiteId,
r.*
FROM ReplenishedCustomerSKU r
JOIN Materials dm ON dm.Id = r.MAterialId
JOIN Materials sm ON sm.Id = r.SourceMAterialId
JOIN Locations l ON l.ID = r.LocationId
JOIN Workcentres wc ON wc.Id = r.WorkcentreId
JOIN Locations sl ON sl.ID = wc.LocationId
top
IH#ReplenishedPoints
SELECT MaterialName ProductName, MaterialCode ProductCode, l.LocationName, l.LocationCode,
cl.LocationName ConsignmentLocationName, cl.LocationCode ConsignmentLocationCode, rp.*
FROM   Replenishedpoints rp
JOIN   Materials m
ON     m.Id = rp.MaterialId
JOIN   Locations l
ON     l.Id = rp.Locationid
LEFT   JOIN Locations cl
ON     cl.Id = rp.ConsignmentLocationid
top
IH#ReplenishedSku
SELECT d.LocationName LocationName,
dm.MaterialName ProductName,
s.LocationName SourceLocation,
sm.MaterialName SourceProduct,
wc.WorkcentreName SourceWorkcentre,
j.JourneyCode, j.TimePeriod,
twc.WorkcentreName TransportWorkcentreName,
c.CalendarName, DECODE(levelNo, 1, rp.Chainstartdate, NULL) ChainStartDate,
fs.Sitename FromSite,
ts.Sitename ToSite,
rs.*
FROM ReplenishedSku rs JOIN ReplenishedPoints rp ON rp.Id = rs.PointId
JOIN Locations d ON rs.LocationId = d.Id
JOIN Materials dm ON dm.Id = rs.Materialid
LEFT JOIN Materials sm ON sm.Id = rs.SourceMaterialid
LEFT JOIN Locations s ON s.Id = FromLocationId
LEFT JOIN Workcentres wc ON wc.Id = FromWorkcentreId
LEFT JOIN Journeys j ON j.Id = rs.JourneyId
LEFT JOIN Calendars c ON c.ID = rs.CalendarId
LEFT JOIN Workcentres twc ON twc.Id = TransportWorkcentreId
LEFT JOIN Sites fs ON fs.Id = rs.FromSiteId
LEFT JOIN Sites ts ON ts.Id = rs.ToSiteId
ORDER BY rs.PointId, rs.ChainNo, rs.LevelNo



top
IH#Replenishedsubstitutedsku
        SELECT fl.LocationCode WarehouseCode, fl.LocationName WarehouseName,
        fm.MaterialCode FromMaterialCode, fm.MaterialName FromMaterialName,
        tm.MaterialCode ToMaterialCode, tm.MaterialName ToMaterialName,
        fm.Id FromMaterialId,
        tm.Id ToMaterialId,
        rs.*
        FROM Replenishedsubstitutedsku rs
        JOIN SiteMaterialUsages fsmu ON rs.SiteMaterialUsageID = fsmu.Id
        JOIN Locations fl ON fsmu.LocationId = fl.Id
        JOIN SiteMaterialUsages tsmu ON rs.OnSiteMaterialUsageID = tsmu.Id
        JOIN Materials fm ON fm.Id = fsmu.MaterialId
        JOIN Materials tm ON tm.Id = tsmu.MaterialId
top
IH#ReplenishmentHorizonSKU
SELECT * FROM
(
SELECT d.SiteMaterialUsageId, ReplenishmentHorizon, RuleWeighting,
row_number() OVER (PARTITION BY d.SiteMaterialUsageId ORDER BY RuleWeighting DESC) r
FROM ReplenishmentHorizonRules r
JOIN IH#DetailsSku d
ON d.DetailId = r.DetailId
)
WHERE r = 1
top
IH#ReplenishmentParameters
SELECT RPClosingCalculationMethod, UseTentativeOrders, UseSupercessions
FROM
(
select ParameterName, VALUE from systemparameters
)
pivot
(
  MIN(VALUE) for parametername in
  ('RPClosingCalculationMethod' RPClosingCalculationMethod,
  'AllowDDQToUseTentativeOrders' UseTentativeOrders,
  'UseSupercessionsInReplenishment' UseSupercessions
  )
)

top
IH#ReplenishmentTrace
SELECT Id, Action, Description, Stamp, extract(SECOND FROM(Stamp - Lag(Stamp) OVER(ORDER BY Id, Stamp))) Diff
FROM   ProcessLogs
WHERE  ProcessId IN (SELECT MAX(Id) FROM Processes WHERE ProcessType = 'Replenishment')
AND    Action = 'ReplenishmentTrace'
ORDER  BY Id
top
IH#ReplenishmentTraceLog
Select Id, ProcessId, Action, Description, Stamp, Stamp - Lag(Stamp) OVER
(partition by ProcessId ORDER BY Id,Stamp) Diff,
(Stamp - First_Value(Stamp) OVer (partition by ProcessId Order by Id, Stamp))  TotalTime
from ProcessLogs
Where ProcessId IN (Select Id from
Processes Where ProcessType = 'Replenishment')
AND Action = 'ReplenishmentTrace'
Order by Id
top
IH#ReplenishmentTraceLogs
Select Id, ProcessId, Action, Description, Stamp, Stamp - Lag(Stamp) OVER
(ORDER BY Id,Stamp) Diff,
(Stamp - First_Value(Stamp) OVer (Order by Id, Stamp))  TotalTime
from ProcessLogs
Where ProcessId IN (Select Id from
Processes Where ProcessType = 'Replenishment')
AND Action = 'ReplenishmentTrace'
Order by Id
top
IH#ReportFilterEntries
WITH fields
AS (
		SELECT FieldViewName FieldName, OriginalName
		FROM IH#modelCharacteristics
		UNION ALL
		SELECT FieldViewCode, OriginalName || ' Code'
		FROM IH#modelCharacteristics
)
SELECT e.ReportFilterId, core.asCsv(CAST(COLLECT(OriginalName || ' ' ||  Operation || ' ' || to_char(FilterValues)) AS ParameterArray), ' ') FilterValues
FROM ReportFilterEntries e
JOIN fields f
ON f.FieldName = e.FieldName
GROUP BY e.REportFilterId

top
IH#RequestedDateProfile
SELECT ip.SiteMaterialUsageId, ip.ConsignmentLocationId, ip.DateFrom, RequestedOrdersIn, NVL(FinalWeight, 0) FinalWeight,
NVL(DeliveryWeight, 0) DeliveryWeight, ol.RequestedDate,
SUM(NVL(FinalWeight, 0)) OVER(PARTITION BY ip.SiteMaterialUsageId, ip.ConsignmentLocationId ORDER BY DateFrom) TotalFinalWeight,
SUM(NVL(RequestedOrdersIn, 0)) OVER(PARTITION BY ip.SiteMaterialUsageId, ip.ConsignmentLocationId ORDER BY DateFrom) TotalRequestedOrdersIn
FROM   InventoryProfiles ip
LEFT   JOIN (SELECT SiteMaterialUsageId, ToConsignmentLocationId, RequestedDate, SUM(FinalWeight) FinalWeight
FROM   OrderLines
WHERE  OrderLineStatusId = 1
GROUP  BY SiteMaterialUsageId, ToConsignmentLocationId, RequestedDate) ol
ON     (ol.Sitematerialusageid = ip.SiteMaterialUsageID AND
NVL(ip.ConsignmentLocationId, 0) = NVL(ol.ToConsignmentLocationId, 0) AND ip.DateFrom = ol.RequestedDate)
LEFT   JOIN (SELECT SiteMaterialUsageId, ToConsignmentLocationId, DeliveryDate, SUM(FinalWeight) DeliveryWeight
FROM   OrderLines
WHERE  OrderLineStatusId = 1
GROUP  BY SiteMaterialUsageId, ToConsignmentLocationId, DeliveryDate) dl
ON     (dl.Sitematerialusageid = ip.SiteMaterialUsageID AND
NVL(ip.ConsignmentLocationId, 0) = NVL(dl.ToConsignmentLocationId, 0) AND ip.DateFrom = dl.DeliveryDate)
ORDER  BY 1, 2, 3
top
IH#RunAvailableCapacities

SELECT mr.*, Quantity - NVL(FirmWeight,0) FirmAvailableCapacity, Quantity - NVL(TotalWeight,0) AvailableCapacity
FROM   MaterialRuns mr
JOIN   MaterialRunStatuses mrs
ON     mr.MaterialRunStatusId = mrs.Id
LEFT JOIN   (SELECT MaterialRunId,
               SUM(CASE
                       WHEN ols.OrderOperationStatusCode IN ('Firm', 'Completed') THEN
                        oo.Quantity - oo.QuantityComplete
                       ELSE
                        0
                   END) FirmWeight,
               SUM(CASE
                       WHEN ols.OrderOperationStatusCode IN ('System', 'Firm', 'Completed') THEN
                        oo.Quantity - oo.QuantityComplete
                       ELSE
                        0
                   END) TotalWeight
        FROM   OrderOperations oo
        JOIN   OrderOperationStatuses ols
        ON     ols.Id = oo.OrderOperationStatusId
        GROUP  BY MaterialRunId) orders
ON     orders.MaterialRunID = mr.Id
top
IH#RunAvailableDuration
WITH operations AS
(
     SELECT oo.WorkcentreId, ol.SourceMaterialId, MaterialRunId, 
            CASE WHEN ols.OrderOperationStatusCode = 'System' THEN 0 ELSE 1 END IsFirm,
            oo.StartTime,
            oo.FinishTime,  
            oo.Quantity,
            oo.OperationDuration
       FROM OrderOperations oo
       JOIN OrderLines ol
         ON ol.Id = oo.OrderLineId
       JOIN OrderOperationStatuses ols
         ON ols.Id = oo.OrderOperationStatusId
      WHERE ols.OrderOperationStatusCode IN ('System', 'Firm', 'Completed')
),
durations AS
(
    SELECT oo.WorkcentreId, MaterialRunId, 
           CASE WHEN oo.IsFirm = 0 THEN 0 ELSE OperationDuration END AS OrdersMinutes,
           CASE WHEN oo.IsFirm = 1 THEN 0 ELSE OperationDuration END AS TentativeOrdersMinutes
      FROM operations oo
),
total AS 
(
   SELECT WorkcentreId, MaterialRunId, 
          SUM(OrdersMinutes) OrdersMinutes, 
          SUM(TentativeOrdersMinutes) TentativeOrdersMinutes
     FROM durations
    GROUP BY WorkcentreId, MaterialRunId   
)
SELECT mr.*,
       mr.InitialDuration - NVL(o.OrdersMinutes,0) AvailableDuration,
       NVL(o.OrdersMinutes,0) OrdersDuration,
       NVL(o.TentativeOrdersMinutes,0) TentativeOrdersDuration
  FROM MaterialRuns mr
  LEFT JOIN total o
    ON o.MaterialRunId = mr.Id
top
IH#RunCapacityByPeriods
WITH runs AS
(
    SELECT mr.Id, mr.BlockRunCode, mr.RunCode, mr.IsFixed, mr.WorkCentreId, d.DateFrom, DateWeek, DateMonth, mr.StartDate, NVL(mr.TargetStartDate, mr.StartDate) + 1/1440*ra.OrdersDuration FreeStartDate,
		       mr.FinishDate, mr.TargetStartDate,

           (
              (CASE WHEN mr.FinishDate <= d.DateFrom + 1 THEN mr.FinishDate ELSE d.DateFrom + 1 END)
               -
              (CASE WHEN NVL(mr.TargetStartDate, mr.StartDate) + 1/1440*ra.OrdersDuration >= d.DateFrom THEN NVL(mr.TargetStartDate, mr.StartDate) + 1/1440*ra.OrdersDuration ELSE d.DateFrom END)
           ) * 24*60 / mr.InitialDuration AS InitialDuration,

           GREATEST(0, (
              (CASE WHEN mr.FinishDate <= d.DateFrom + 1 THEN mr.FinishDate ELSE d.DateFrom + 1 END)
               -
              (CASE WHEN NVL(mr.TargetStartDate, mr.StartDate) + 1/1440*ra.OrdersDuration >= d.DateFrom THEN NVL(mr.TargetStartDate, mr.StartDate) + 1/1440*ra.OrdersDuration ELSE d.DateFrom END)
           )) * 24*60 DayDuration,
           OrdersDuration,
					 (CASE WHEN mr.FinishDate <= d.DateFrom + 1 THEN mr.FinishDate ELSE d.DateFrom + 1 END) x1,
					 (CASE WHEN NVL(mr.TargetStartDate, mr.StartDate) + 1/1440*ra.OrdersDuration >= d.DateFrom THEN NVL(mr.TargetStartDate, mr.StartDate) + 1/1440*ra.OrdersDuration ELSE d.DateFrom END) x2,
           mr.Quantity OriginalQuantity,
           mr.NominalCapacity,
           mr.InitialDuration AS OriginalInitialDuration,
           mrp.ProductName as RunProperties
     FROM MaterialRuns mr
     JOIN MaterialRunProducts mrp ON mrp.MaterialRunId = mr.Id
     JOIN IH#DailyRange d ON d.DateFrom BETWEEN TRUNC(mr.StartDate) AND TRUNC(mr.FinishDate)
     JOIN Ih#runavailableduration ra ON ra.Id = mr.Id
    WHERE mr.InitialDuration > 0
      AND mr.RunType = 'production'
)
SELECT r.*, SiteId, r.InitialDuration * r.OriginalQuantity RunCapacity
FROM runs r
join IH#Workcentres wc on wc.WorkcentreID = r.WorkcentreId
ORDER BY r.WorkCentreId, r.DateMonth, r.DateWeek, r.StartDate

top
IH#RunDurationByPeriod
WITH shuts
AS
(
 SELECT ws.WorkcentreId,  ws.StartDate, ws.FinishDate, d.DateFrom,
         (CASE
             WHEN Trunc(ws.FinishDate) <= d.DateFrom THEN
              ws.FinishDate
             ELSE
              d.DateFrom + 1
         END - CASE
             WHEN ws.StartDate >= d.DateFrom THEN
              ws.StartDate
             ELSE
              d.DateFrom
         END) * 24 * 60 duration
  FROM   WorkcentreShuts ws
  JOIN   IH#DailyRange d
  ON     (d.DateFrom BETWEEN TRUNC(ws.StartDate) AND TRUNC(ws.FinishDate))

),
runs AS
(
SELECT mr.Id, Workcentreid, BlockRunCode, mr.StartDate, mr.FinishDate, d.Datefrom, d.DateWeek, d.DateMonth,

       (CASE
           WHEN Trunc(mr.FinishDate) <= d.DateFrom THEN
            mr.FinishDate
           ELSE
            d.DateFrom + 1
       END - CASE
           WHEN mr.StartDate >= d.DateFrom THEN
            mr.StartDate
           ELSE
            d.DateFrom
       END) * 24 * 60 Duration
FROM   MaterialRuns mr
JOIN   IH#DailyRange d
ON     (d.DateFrom BETWEEN TRUNC(mr.StartDate) AND TRUNC(mr.FinishDate))
),
dailyruns AS
(
SELECT r.Id, r.WorkcentreId, BlockRunCode, r.StartDate, r.DateFrom, r.DateWeek, r.DateMonth,
r.Duration RunDuration,
NVL(s.Duration,0) ShutDuration,
CASE WHEN s.Duration = 1440 THEN 0
	   WHEN  r.Duration > 1440 - NVL(s.Duration,0) THEN 1440 - NVL(s.Duration,0)
		 ELSE r.Duration END Duration,

CASE WHEN s.Duration = 1440 THEN 1
	   WHEN  r.Duration > 1440 - NVL(s.Duration,0) THEN 2
		 ELSE 3 END case1,
SUM(CASE WHEN s.Duration = 1440 THEN 0
	   WHEN  r.Duration > 1440 - NVL(s.Duration,0) THEN 1440 - NVL(s.Duration,0)
		 ELSE r.Duration END) OVER (PARTITION BY r.WorkcentreId, r.Id ORDER BY r.StartDate, r.Datefrom) TotalDuration,
NVL(SUM(CASE WHEN s.Duration = 1440 THEN 0
	   WHEN  r.Duration > 1440 - NVL(s.Duration,0) THEN 1440 - NVL(s.Duration,0)
		 ELSE r.Duration END) OVER (PARTITION BY r.WorkcentreId, r.Id ORDER BY r.StartDate, r.Datefrom rows between unbounded preceding and 1 preceding),0) TotalDuration2
FROM runs r
LEFT JOIN shuts s ON r.WorkcentreId = s.WorkcentreId AND r.DateFrom = s.DateFrom
WHERE 1=1
--AND r.ID = 127
)
SELECT r.Id, r.WorkcentreId, r.BlockRunCode,
r.StartDate,r.DateFrom, r.DateWeek, r.DateMonth, r.RunDuration,
r.ShutDuration,
r.Duration,
a.OrdersDuration,
r.Duration - (
CASE WHEN r.TotalDuration > a.OrdersDuration THEN a.OrdersDuration
ELSE r.TotalDuration
  END
  -
  CASE WHEN r.TotalDuration2 > a.OrdersDuration THEN a.OrdersDuration
    ELSE  r.TotalDuration2  END)
                 AvailableDuration
FROM DailyRuns r JOIN
Ih#runavailableduration a ON a.Id = r.Id
ORDER BY WorkcentreId, StartDate, DateFrom
top
IH#RunInventoryProfiles
SELECT OperatorUserId, GradeCode, DateFrom, Safetystock
FROM Runinventoryprofiles rp
JOIN Gradeproperties gp ON gp.GradeId = rp.GradeId
top
IH#RunMaterials

SELECT mrp.MaterialRunId, mr.WorkcentreId, w.SiteId, d.Materialid
  FROM MaterialRuns mr
  JOIN Materialrunproducts mrp
    ON mrp.MaterialRunId = mr.Id
  JOIN IH#DetailsMaterial d  
    ON d.DetailId = mrp.DetailId
  JOIN IH#Workcentres w 
    ON w.WorkcentreID = mr.WorkcentreID

top
IH#RunProperties

SELECT MaterialRunId, core.AsCsv(CAST(COLLECT(Properties) AS PArameterArray), '; ') Properties
  FROM (SELECT RunProductId,
               core.AsCsv(CAST(COLLECT(PropertyDesc || ': ' || PropertyValueCode ORDER BY rp.OrderNo) AS ParameterArray), ' ') Properties
          FROM MaterialRunProperties mrp
          JOIN (SELECT DISTINCT p.Id PropertyId, PropertyName, PropertyDesc, NVL(n.LevelNo, m.HierarchyLevelNo * 10) OrderNO
                  FROM PropertiesIPlanView p
                  JOIN IH#ModelCharacteristics m
                    ON m.FieldViewCode = p.PropertyViewCode
                  LEFT JOIN NAvigations n
                    ON p.PropertyViewCode = n.LevelName
                   AND TaskName = 'ProductionRatePicker') rp
            ON rp.PropertyId = mrp.Propertyid
         GROUP BY RunProductId) t
  JOIN MaterialRunProducts mr
    ON mr.Id = t.RunProductId
 GROUP BY MaterialRunId

top
IH#SAGradePropertyMap
SELECT gm.GradeId, MIN(m.PropertyValueID) PropertyValueId
FROM Gradematerials gm
JOIN Expandedmaterials m ON m.MAterialId = gm.MaterialId
JOIN PropertyValues pv ON m.PropertyValueID = pv.Id
WHERE pv.PropertyId IN (   SELECT p.Id
FROM   Properties p, SystemParameters sp
WHERE  sp.ParameterName = 'MasterPlanningFinishingProduct'
AND    sp.Value = p.PropertyName)
GROUP BY gm.GradeId
top
IH#SAInitialSources
SELECT sr.SnapshotUserId, sr.ScenarioId, sr.Id, detailId,
       core.asCsv(CAST(COLLECT(wc.WorkCentreName) AS ParameterArray)) WorkCentres,
       core.asCsv(CAST(COLLECT(s.SiteName) AS ParameterArray)) Sites
  FROM InitialSourceSnapshots sr
  JOIN HierarchyPropertyDetails d ON (d.Id = sr.DetailId)
  JOIN InitialSourceSourceSnapshots srs ON srs.InitialSourceSnapshotId = sr.Id
  LEFT JOIN WorkCentres wc ON (wc.Id = srs.WorkCentreId)
  LEFT JOIN Sites s ON (s.Id = srs.SiteId)
 GROUP BY sr.SnapshotUserId, sr.ScenarioId, sr.Id, DetailId
top
IH#SAInitialSourceSources
SELECT sr.SnapshotUserId, sr.ScenarioId, sr.InitialSourceSnapshotId, w.WorkCentreID, w.SiteId
  FROM InitialSourceSourceSnapshots sr
  JOIN IH#WorkCentres w ON (w.SiteId = sr.SiteId)
 WHERE sr.SiteId IS NOT NULL
   AND w.IsProductionSource = 1
 UNION
SELECT sr.SnapshotUserId, sr.ScenarioId, sr.InitialSourceSnapshotId, w.WorkCentreID, w.SiteId
  FROM InitialSourceSourceSnapshots sr
  JOIN IH#WorkCentres w ON (w.WorkCentreId = sr.WorkCentreId)
 WHERE sr.WorkCentreId IS NOT NULL
   AND w.IsProductionSource = 1
top
IH#SAWeeklyCoefs
SELECT t.*, DECODE(x, 1, 1, Coef2) Coef FROM
(
SELECT w1.DateFromWeek deliveryDate,
w1.DateFromMonth deliveryMonth,
w2.DateFromWeek SourceDate,
w2.DateFromMonth SourceMonth, w1.WeeklyCoef Coef1, w2.WeeklyCoef coef2,
COUNT(1) OVER (PARTITION BY w1.DateFromWeek, w1.DateFromMonth) x

FROM weeklymonthmapiplanview w1 JOIN
weeklymonthmapiplanview w2
ON w1.DateFromWeek = w2.DateFromWeek
AND w1.DateFromMonth >= w2.DateFromMonth
) t

top
IH#ScenarioPaperMachines
SELECT wc.*
FROM   IH#Workcentres wc
LEFT   JOIN IH#Workcentreparameters wp
ON     (wp.WorkcentreId = wc.WorkcentreId AND wp.ParameterName = 'ExcludeFromSA')
WHERE  wc.WorkcentreTypeName = 'Paper Machine'
AND wp.Value = 0
top
IH#ScenarioPeriodSnapshots
SELECT p.*,
       CASE
           WHEN ss.SnapshotPeriodType = 'WeekMonth2' AND PeriodLength < 7 AND LEAD(PeriodLength)
            OVER(PARTITION BY p.SnapshotUserId ORDER BY PEriodNumber) < 7 THEN
            1
           ELSE
            0
       END IsPartial
FROM   Scenarioperiodsnapshots p
JOIN   ScenarioSessions SS
ON     ss.Snapshotuserid = p.SnapshotUserId
ORDER BY p.SnapshotUserId, PeriodNumber
top
IH#ScenarioRates

        SELECT s.ScenarioName, s.UserName, s.UserLogin, sr.SnapshotUserId, sr.Scenarioid, WorkcentreName, WorkcentreCode,
               DateFrom, d.PropertiesCode CycleType, sr.WorkcentreId, sr.PropertyValueId, sr.CycleTypeId, IsActive,
               HasOrder, HasRun, Rate, COST, Conversionfactor, Materialefficiency, TIMEEFFICIENCY, OperationTypeId
        FROM   ScenarioRates sr
        JOIN   CycleTypeSnapshots ct
        ON     ct.Id = sr.CycleTypeId
        AND    ct.Snapshotuserid = sr.SnapshotUserId
        AND    ct.ScenarioId = sr.ScenarioId
        JOIN   Ih#hierarchypropertydetails d
        ON     d.ID = ct.DetailId
        JOIN   IH#Workcentres wc
        ON     wc.WorkcentreId = sr.WorkcentreId
        JOIN   IH#Scenarios s
        ON     s.UserId = sr.SnapshotUserId
        AND    s.Id = sr.ScenarioId
top
IH#Scenarios
	SELECT s.Id, s.SnapshotUserId UserId, UserName, UserLogin, ScenarioName, DifferenceFG, DifferenceFGReplenished, s.UseUnlimitedPMCapacity,
	DifferenceSFG, PenaliseDowntime, OptimizationMode, s.State, ss.FixedPeriod, ss.Horizon, ss.StartWeek, ss.FinishWeek,
	ss.SnapshotPeriodType, s.IgnoreSourceLists, s.UseOnlyPrimarySources, s.LatenessPeriods, ss.UseFixedPeriod, s.IsFullLog, s.IsCrossSite,
	s.UseMinAllocation,
	ss.ForecastSnapshotId, fs.Description ForecastSnapshotDescription
	FROM Scenarios s
	JOIN USERS u ON (s.Snapshotuserid = u.Id)
	JOIN ScenarioSessions ss on ss.SnapshotUserId = s.SnapshotUserId
	LEFT JOIN ForecastSnapshots fs ON ss.ForecastSnapshotId = fs.Id
top
IH#ScenarioSessions
    SELECT UserName, UserLogin,
    DECODE(fs.Id, 0, TRUNC(ss.StartWeek, 'MONTH'), fs.StartDate) StartMonth,
    DECODE(fs.Id, 0, TRUNC(ss.FinishWeek, 'month'), fs.FinishDate) FinishMonth,
    SS.*,
    fs.Name SnapshotName
    FROM ScenarioSessions SS JOIN USERS u ON u.Id = ss.snapshotUserId
    LEFT JOIN IH_ForecastSnapshots fs ON (fs.Id = NVL(ss.ForecastSnapshotId,0))
top
IH#ScenarioSourcePeriods
SELECT ss.SnapshotUserId, SourceStartWeek + ((h.Column_Value - 1) * 7) SourceWeek
FROM   ScenarioSessions SS, TABLE(core.rowgenerator(SourceHorizon)) h
top
IH#ScenarioWorkcentres
SELECT wc.*, NVL(wp.Value, 0) IsExcludedFromSA
FROM   IH#Workcentres wc
LEFT   JOIN IH#Workcentreparameters wp
ON     (wp.WorkcentreId = wc.WorkcentreId AND wp.ParameterName = 'ExcludeFromSA')
top
IH#SimpleSkus
SELECT smu.Id SiteMaterialUsageId, smu.LocationId, smu.MaterialId, NULL ConsignmentLocationId, smu.IsActiveSku,
(SELECT NVL(MIN(1),0) FROM dual WHERE EXISTS (SELECT 1 FROM Workcentres wc WHERE wc.LocationId = smu.LocationId)) isWarehouse,
smu.SkuKey, Status, Replenished
FROM   SiteMaterialUsages smu
UNION ALL
SELECT cp.SiteMaterialUsageId, smu.LocationId, smu.MaterialId, cp.CustomerId AS ConsignmentLocationId, cp.IsActiveSku,
(SELECT NVL(MIN(1),0) FROM dual WHERE EXISTS (SELECT 1 FROM Workcentres wc WHERE wc.LocationId = smu.LocationId)) isWarehouse,
cp.SkuKey, 0 Status, cp.Replenished
FROM   ConsignmentParameters cp
JOIN   SiteMaterialUsages smu
ON     (smu.Id = cp.SiteMaterialUsageId)
top
IH#SimpleWarehouseSkus
select * from IH#SimpleSkus v
WHERE EXISTS (Select 1 from Workcentres wc Where wc.LocationId = v.LocationId)
top
IH#SiteMonthlyHistories
SELECT hd.SiteMaterialUSageId, hd.WorkcentreId,
       TRUNC(DateFrom, 'month') DateFrom,
       NVL(SUM(Weight),0) Weight,
       NVL(SUM(DECODE(SIGN(dateFrom - core.getTruncatedInternalDate), -1, weight, 0)), 0) mtdHistory,
       NVL(SUM(AdjustedWeight),0) OriginalAdjustedWeight,
       GREATEST(0, SUM(NVL(AdjustedWeight, Weight))) HistoryWeight,
       SUM(NVL(AdjustedWeight, Weight)) AdjustedHistoryWeight
FROM   UsageHistories hd
GROUP  BY hd.SiteMaterialUSageId, hd.WorkcentreId, TRUNC(DateFrom, 'month')

top
IH#Sites
SELECT s.*, (SELECT NVL(MIN(1),0) FROM dual
WHERE EXISTS (SELECT 1 FROM IH#Workcentres wc WHERE wc.SiteId = s.Id
AND wc.IsProductionSource = 1)
AND EXISTS (SELECT 1 FROM IH#Workcentres wc WHERE wc.SiteId = s.Id
AND wc.WorkcentreTypeName = 'Warehouse')) IsProduction,
(SELECT NVL(MIN(1),0) FROM dual
WHERE EXISTS (SELECT 1 FROM IH#Workcentres wc WHERE wc.SiteId = s.Id
AND wc.WorkcentreTypeName = 'Warehouse')) IsValid
FROM Sites s
top
IH#SiteSupersededHistories
SELECT NVL(ms.OnSiteMaterialUsageId, uh.SiteMaterialUsageId) SiteMaterialUSageID, WorkcentreId, DateFrom,
       SUM(CASE WHEN ms.StartDate IS NULL THEN Weight
            WHEN DateFrom <= ms.Startdate OR ms2.StartDate IS NULL THEN Weight * ms.PERCENTAGE / 100
            ELSE 0 END)  SupersededHistory,
       SUM(CASE WHEN ms.StartDate IS NULL THEN mtdHistory
            WHEN DateFrom <= ms.Startdate OR ms2.StartDate IS NULL THEN mtdHistory * ms.PERCENTAGE / 100
            ELSE 0 END)  mtdSupersededHistory,
       SUM(CASE WHEN ms.StartDate IS NULL THEN AdjustedHistoryWeight
            WHEN DateFrom <= ms.Startdate OR ms2.StartDate IS NULL THEN AdjustedHistoryWeight * ms.PERCENTAGE / 100
            ELSE 0 END)  AdjustedSupersededHistory
  FROM IH#SiteMonthlyHistories uh
  LEFT JOIN Ih#Allmaterialsupercessions ms
    ON ms.SITEMATERIALUSAGEID = uh.SiteMaterialUsageId
   AND ms.StartDate <= uh.DateFrom
  LEFT JOIN (SELECT SiteMaterialusageId, Min(StartDate) StartDate
               FROM Ih#Allmaterialsupercessions
              GROUP BY SiteMAterialUsageId) ms2
    ON ms2.SITEMATERIALUSAGEID = NVL(ms.OnSiteMaterialUsageId, uh.SiteMaterialUsageId)
 GROUP BY NVL(ms.OnSiteMaterialUsageId, uh.SiteMaterialUsageId), WorkcentreId, DateFrom
 ORDER BY 1,2
top
IH#SiteSupersededOrders
WITH o AS 
(
  SELECT SiteMaterialUsageId, PeriodType, WorkCentreId, LocationId,
         DeliveryDate, SUM(FinalWeight) FinalWeight, 
         SUM(CASE WHEN OnSiteMaterialUsageId IS NULL THEN FinalWeight ELSE 0 END) OrdersIncludeSupercessions
  FROM 
  (
      SELECT ol.SiteMaterialUsageId, ms.OnSiteMaterialUsageId, 
             ol.DeliveryDate, ol.PeriodType, ol.LocationId, NVL(oo.Workcentreid, ol.WorkcentreId) WorkcentreId,
             FinalWeight
        FROM OrderLines ol
        JOIN OrderLineStatuses ols
          ON ols.Id = ol.OrderLineStatusId
        LEFT JOIN OrderOperations oo
        ON oo.OrderLineId = ol.Id
        AND oo.IsLastOperation = 1
        LEFT JOIN IH#MaterialSupercessions ms
          ON ms.SiteMaterialUsageId = ol.SiteMaterialUsageId   
          AND ms.TargetStatus = 1
       WHERE ols.OrderLineStatusCode IN ('Firm', 'Completed')
  )  
  GROUP BY SiteMaterialUsageId, PeriodType, WorkCentreId, LocationId,DeliveryDate
  UNION ALL
  SELECT OnSiteMaterialUsageId, PeriodType, WorkCentreId, LocationId,
         DeliveryDate, 0 FinalWeight, SUM(FinalWeight) OrdersIncludeSupercessions
  FROM 
  (
      SELECT ol.SiteMaterialUsageId, ms.OnSiteMaterialUsageId, 
             ol.DeliveryDate, ol.PeriodType, ol.LocationId, NVL(oo.Workcentreid, ol.WorkcentreId) WorkcentreId,
             FinalWeight
        FROM OrderLines ol
        JOIN OrderLineStatuses ols
          ON ols.Id = ol.OrderLineStatusId
        LEFT JOIN OrderOperations oo
          ON oo.OrderLineId = ol.Id
          AND oo.IsLastOperation = 1
        LEFT JOIN IH#MaterialSupercessions ms
          ON ms.SiteMaterialUsageId = ol.SiteMaterialUsageId   
          AND ms.TargetStatus = 1
      WHERE ols.OrderLineStatusCode IN ('Firm', 'Completed')
  )  
  WHERE OnSiteMaterialUsageId IS NOT NULL
  GROUP BY OnSiteMaterialUsageId, PeriodType, WorkCentreId, LocationId, DeliveryDate
)
SELECT SiteMaterialUsageId, o.WorkcentreId,
       DECODE(o.PeriodType, 'day', TRUNC(o.DeliveryDate, 'month'), c.MonthDate) DeliveryMonth,
       SUM(DECODE(o.PeriodType, 'day', FinalWeight, FinalWeight * c.WeekMonthCoef)) Orders,
       SUM(DECODE(o.PeriodType, 'day', OrdersIncludeSupercessions, OrdersIncludeSupercessions * c.WeekMonthCoef)) OrdersIncludeSupercessions 
  FROM o
 CROSS JOIN IH#DefaultParameters p
  JOIN Locations l
    ON l.Id = o.LocationId
  JOIN IH#CalendarWeeklyCoefs c
    ON c.CalendarId = NVL(l.CalendarId, p.DefaultCalendarId)
   AND TRUNC(DeLiveryDate, 'IW') = c.WeekDate
   AND (o.PeriodType = 'week' OR TRUNC(DeliveryDate, 'month') = c.MonthDate)
 GROUP BY SiteMaterialUsageId, WorkcentreId,
       DECODE(o.PeriodType, 'day', TRUNC(o.DeliveryDate, 'month'), c.MonthDate)
top
IH#SiteTransportPeriods
WITH routes AS
 (SELECT CONNECT_BY_ROOT SiteId AS SiteId, FromLocationId, ToLocationId, TimePeriod, Connect_BY_ROOT FromLocationId f, ToLocationID t,
         CONNECT_BY_ROOT FromLocationId || SYS_CONNECT_BY_PATH(ToLocationId, ' --> ') TransportPath,
         LTRIM(SYS_CONNECT_BY_PATH(TimePeriod, '+'), '+') ListTimePeriods

  FROM   (SELECT t.*, ws.SiteId FROM TransportRoutes t JOIN IH#Warehouses ws ON ws.LocationId = t.FromLocationId) tr
  CONNECT BY PRIOR ToLocationId = FromLocationId
  START  WITH FromLocationId IN (SELECT LocationId
                                 FROM   Ih#mainwarehouses MW
                                 JOIN   IH#Sites s
                                 ON     s.Id = mw.SITEID
                                 AND    s.IsProduction = 1))
SELECT SiteId ProductionSiteId, f SiteWarehouseId, t ToLocationId,
       MIN((SELECT SUM(regexp_substr(ListTimePeriods, '[^+]+', 1, LEVEL)) AS RESULT
         FROM   dual
         CONNECT BY regexp_substr(ListTimePeriods, '[^+]+', 1, LEVEL) IS NOT NULL)) TotalTimePeriod
FROM   routes
GROUP BY  SiteId, f, t
UNION ALL
SELECT SiteId, LocationId, LocationId, 0 TotalTimePeriod
FROM Ih#mainwarehouses mw
JOIN   IH#Sites s
ON     s.Id = mw.SITEID
AND    s.IsProduction = 1
top
IH#SiteWorkcentreOperations
SELECT ot.Id OperationTypeId, OperationTypeName, WorkcentreId, WorkcentreName, SiteId, SiteName
FROM   IH#Workcentres wc
JOIN   OperationTypes ot
ON     ot.WorkcentreTypeId = wc.WorkcentreTypeId
top
IH#SiteWorkcentres
SELECT WorkcentreCode, SiteCode, WorkcentreName, SiteName, WorkcentreTypeName, WorkcentreTypeDesc, wct.OrderNo WorkcentreTypeOrderNo,
wc.Id WorkcentreId, SiteId, wct.HasInventory, wc.LocationId, wc.WorkcentreTypeId,
s.SiteProperty1, s.SiteProperty2, s.SiteProperty3, s.SiteProperty4, s.SiteProperty5,
SIGN(SUM(wct.IsProductionSource) OVER(PARTITION BY s.Id)) IsProductionSite
FROM Workcentres wc
JOIN Locations l
ON l.id = wc.LocationId
JOIN Sites s
ON s.Id = l.SiteId
JOIN WorkcentreTypes wct
ON wct.Id = wc.WorkcentreTypeId
top
IH#Sku
SELECT smu.ID, smu.LocationId, smu.MaterialId,
       l.LocationCode, l.LocationName, m.MaterialCode, m.MaterialName, 
       eu.EndUseCode, EndUseDescription EndUse, ec.LocationCode EndCustomerCode, ec.LocationName EndCustomer,
       m.MaterialProperties, l.LocationProperties, 
       smu.Status, 
       NVL(smu.NettingAlgorithm, s.Value) NettingAlgorithm,
       smu.ConsumptionType,
			 core.asCsv(ParameterArray(l.LocationName, m.MaterialName, EndUseDescription, ec.LocationName), ' | ', 1) SkuTitle,
 			 core.asCsv(ParameterArray(l.LocationCode, m.MaterialCode, EndUseCode, ec.LocationCode), ' | ', 1) SkuCodeTitle
  FROM SiteMaterialUSages smu
  JOIN Materials m
    ON (m.Id = smu.MaterialId)
  JOIN Locations l
    ON (l.Id = smu.LocationId)
  LEFT JOIN Locations ec ON (ec.Id = smu.EndCustomerId)
  LEFT JOIN EndUses eu ON (eu.Id = smu.EndUseId)
 CROSS JOIN (Select Value from SystemParameters where ParameterName = 'DefaultNettingAlgorithm') s
top
IH#SkuRoundUnits
SELECT smu.Id SiteMaterialUsageId, smu.LocationId, smu.MaterialId, NULL ConsignmentLocationId,
COALESCE(smu.OrderUnitId, ru.UnitId) RoundOrderUnitId, smu.MinOrderQuantity
FROM   SiteMaterialUsages smu
JOIN Materials m
ON m.Id = smu.MaterialId
LEFT JOIN IH#MaterialTypeRoundingUnits ru
ON ru.MaterialTypeId = m.MaterialTypeId
UNION ALL
SELECT cp.SiteMaterialUsageId, smu.LocationId, smu.MaterialId, cp.CustomerId AS ConsignmentLocationId,
COALESCE(cp.OrderUnitId, smu.OrderUnitId, ru.UnitId) RoundOrderUnitId, cp.MinOrderQuantity
FROM   ConsignmentParameters cp
JOIN   SiteMaterialUsages smu
ON     (smu.Id = cp.SiteMaterialUsageId)
JOIN Materials m
ON m.Id = smu.MaterialId
LEFT JOIN IH#MaterialTypeRoundingUnits ru
ON ru.MaterialTypeId = m.MaterialTypeId
top
IH#Skus

SELECT smu.Id SiteMaterialUsageId, smu.LocationId, smu.MaterialId, NULL ConsignmentLocationId, EndUseId,
NVL(EndCustomerId, LocationId) EndCustomerId, 
NVL(smu.UpperPercentile, p.DefaultSKUUpperPercentile) UpperPercentile, 
NVL(smu.LowerPercentile, p.DefaultSKULowerPercentile) LowerPercentile,
smu.DaysOfSupply,
smu.HighQuantity, smu.LowQuantity, smu.MinOrderQuantity, smu.OrderUnitId, COALESCE(smu.OrderUnitId, ru.UnitId) RoundOrderUnitId,
smu.MaxCapacity, smu.Replenished,
smu.Status, smu.HistoryStartDate, smu.ForecastStartDate, smu.ForecastFinishDate, smu.ReplenishmentStartDate, smu.ReplenishmentHorizon,
smu.ReplenishmentFinishDate, smu.ForecastMethodId,
COALESCE(smu.SafetyStockMethodId, ccl.SafetyStockMethodId, c.SafetyStockMethodId, p.DefaultSafetyStockMethodId) SafetystockmethodId,
cr.Id CustomerRankId, smu.ReplenishmentFrequency, smu.inhibitProduction, smu.inhibitSFGSearch,
smu.DDQContingency,  smu.DefaultCustomerForecast,  smu.NettingAlgorithm, smu.ConsumptionType, smu.AlternateProduct, cr.CustomerRankDesc,
smu.MaxDaysOfSupply, smu.MaxReplenishmentFrequency, smu.MaxSafetyStockMethodId,
NVL(ccl.CalendarId, p.DefaultCalendarId) CalendarId,
NVL2(smu.GroupKey, NVL(ccl.WarehouseLocationId, ccl.Id), NULL) GroupId,
smu.SkuKey, ccl.WarehouseLocationId, ccl.StockLocationId, smu.SourceListId,
smu.LastInventoryDate,
ccl.SiteId, ccl.CompanyId,
smu.GroupKey,
smu.SkuProperty1, smu.SkuProperty2, smu.SkuProperty3, smu.SkuProperty4, smu.SkuProperty5, smu.SkuProperties,
NVL(smu.SafetyStockPercentWarning, p.DefaultSSPercentWarning) SafetyStockPercentWarning,
smu.ReplenishmentFlag
FROM   SiteMaterialUsages smu
CROSS  JOIN IH#DefaultParameters p
JOIN   Locations ccl
ON     (smu.LocationId = ccl.Id)
JOIN   Companies c
ON     (c.Id = ccl.CompanyID)
JOIN Materials m
ON m.Id = smu.MaterialId
LEFT   JOIN CustomerRanks cr
ON     COALESCE(smu.CustomerRankId, ccl.CustomerRankId, c.CustomerRankId, p.DefaultCustomerRankId) = cr.Id
LEFT JOIN IH#MaterialTypeRoundingUnits ru
ON ru.MaterialTypeId = m.MaterialTypeId
UNION ALL
SELECT cp.SiteMaterialUsageId, smu.LocationId, smu.MaterialId, cp.CustomerId AS ConsignmentLocationId, NULL AS EndUseId,
NULL AS EndCustomerId, 
NVL(smu.UpperPercentile, p.DefaultSKUUpperPercentile) UpperPercentile, 
NVL(smu.LowerPercentile, p.DefaultSKULowerPercentile) LowerPercentile, 
cp.DaysOfSupply, cp.HighQuantity,
cp.LowQuantity, cp.MinOrderQuantity,  COALESCE(cp.OrderUnitId, smu.OrderUnitId) OrderUnitId,
COALESCE(cp.OrderUnitId, smu.OrderUnitId, ru.UnitId) RoundOrderUnitId,
NULL AS MaxCapacity, cp.Replenished, NULL AS Status,
NULL AS HistoryStartDate, NULL AS ForecastStartDate, NULL AS ForecastFinishDate, cp.ReplenishmentStartDate, cp.ReplenishmentHorizon,
NVL(cp.ReplenishmentStartDate, m.ReplenishmentStartDate) ReplenishmentStartDate, NULL AS ForecastMethodId,
COALESCE(cp.SafetyStockMethodId, ccl.SafetyStockMethodId, c.SafetyStockMethodId, p.DefaultSafetyStockMethodId) SafetystockmethodId,
cr.Id AS CustomerRankId, cp.ReplenishmentFrequency, NULL AS inhibitProduction, NULL AS inhibitSFGSearch,
NULL AS DDQContingency, NULL AS DefaultCustomerForecast, NULL as NettingAlgorithm, NULL as ConsumptionType, cp.AlternateProduct, cr.CustomerRankDesc,
cp.MaxDaysOfSupply, cp.MaxReplenishmentFrequency, cp.MaxSafetyStockMethodId,
NVL(ccl.CalendarId, p.DefaultCalendarId) CalendarId,
NVL2(cp.GroupKey, NVL(ccl.WarehouseLocationId, ccl.Id), NULL) GroupId,
cp.SkuKey, ccl.WarehouseLocationId, ccl.StockLocationId, smu.SourceListId,
cp.LastInventoryDate,
ccl.SiteId, ccl.CompanyId,
cp.GroupKey,
smu.SkuProperty1, smu.SkuProperty2, smu.SkuProperty3, smu.SkuProperty4, smu.SkuProperty5, smu.SkuProperties,
NVL(cp.SafetyStockPercentWarning,p.DefaultSSPercentWarning) SafetyStockPercentWarning,
smu.ReplenishmentFlag
FROM   ConsignmentParameters cp
JOIN   SiteMaterialUsages smu
ON     (smu.Id = cp.SiteMaterialUsageId)
CROSS  JOIN IH#DefaultParameters p
JOIN   Locations ccl
ON     (smu.LocationId = ccl.Id)
JOIN   Companies c
ON     (c.Id = ccl.CompanyID)
JOIN Materials m
ON m.Id = smu.MaterialId
LEFT   JOIN CustomerRanks cr
ON     COALESCE(smu.CustomerRankId, ccl.CustomerRankId, c.CustomerRankId, p.DefaultCustomerRankId) = cr.Id
LEFT JOIN IH#MaterialTypeRoundingUnits ru
ON ru.MaterialTypeId = m.MaterialTypeId
top
IH#SkuStockStatus
SELECT r.SiteMaterialUsageId, r.ConsignmentLocationId, DateFrom, OverallOpening, OverallClosing, r.SafetyStock, s.SafetyStockPercentWarning, 0 Superseded,
CASE
                        WHEN DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < 0
                             THEN 1
                        WHEN (SELECT VALUE FROM SystemParameters WHERE ParameterName = 'StockLevelAtZeroWarning') = 'InventoryLessOrEqualZero'
                             AND r.SafetyStock > 0
                             AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) = 0
                             THEN 1
                        WHEN r.SafetyStock > 0 AND s.SafetyStockPercentWarning > 0
                             AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < r.SafetyStock * s.SafetyStockPercentWarning / 100
                             THEN 2
                        WHEN r.SafetyStock > 0 AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < r.SafetyStock
                             THEN 3
                        WHEN s.MaxCapacityBehaviour IN ('Warning', 'Limit') AND s.MaxCapacity > 0 AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) > s.MaxCapacity
                             THEN 4
                        ELSE 5
                    END StockStatus
 FROM  RealInventoryProfilesIPlanView r
 JOIN IH#WHStockMonitoring s ON s.SiteMaterialUsageId = r.SiteMaterialUsageId
                            AND NVL(S.ConsignmentLocationId,0) = NVL(r.ConsignmentLocationId,0)
  CROSS JOIN (SELECT NVL(MIN(VALUE), 'Closing') StockStateField FROM SystemPArameters WHERE ParameterName = 'RPStockStateField') p
  WHERE NOT EXISTS (select 1 from ReplenishedSubstitutedSku s
                    where s.OnSiteMaterialUSageId = r.SiteMaterialUsageId and s.Replenished = 0)
UNION ALL
SELECT r.SiteMaterialUsageId, r.ConsignmentLocationId, DateFrom, OverallOpening, OverallClosing, r.SafetyStock, s.SafetyStockPercentWarning, 1 Superseded,
CASE
                        WHEN DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < 0
                             THEN 1
                        WHEN (SELECT VALUE FROM SystemParameters WHERE ParameterName = 'StockLevelAtZeroWarning') = 'InventoryLessOrEqualZero'
                             AND r.SafetyStock > 0
                             AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) = 0
                             THEN 1
                        WHEN r.SafetyStock > 0 AND s.SafetyStockPercentWarning > 0
                             AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < r.SafetyStock * s.SafetyStockPercentWarning / 100
                             THEN 2
                        WHEN r.SafetyStock > 0 AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < r.SafetyStock
                             THEN 3
                        WHEN s.MaxCapacityBehaviour IN ('Warning', 'Limit') AND s.MaxCapacity > 0 AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) > s.MaxCapacity
                             THEN 4
                        ELSE 5
                    END StockStatus
 FROM  IH#SupersededOpeningProfiles r
 JOIN IH#WHStockMonitoring s ON s.SiteMaterialUsageId = r.SiteMaterialUsageId
                            AND NVL(S.ConsignmentLocationId,0) = NVL(r.ConsignmentLocationId,0)
CROSS JOIN (SELECT NVL(MIN(VALUE), 'Closing') StockStateField FROM SystemPArameters WHERE ParameterName = 'RPStockStateField') p
 WHERE EXISTS (select 1 from ReplenishedSubstitutedSku s
               where s.OnSiteMaterialUSageId = r.SiteMaterialUsageId AND s.Replenished = 0)
top
IH#SkuWarehouseLocations

SELECT smu.Id SiteMaterialUsageId, smu.LocationId, smu.MaterialId, NULL ConsignmentLocationId, EndUseId,
NVL(EndCustomerId, LocationId) EndCustomerId,
NVL2(smu.GroupKey, NVL(ccl.WarehouseLocationId, ccl.Id), NULL) GroupId,
smu.SkuKey, ccl.WarehouseLocationId, ccl.StockLocationId
FROM   SiteMaterialUsages smu
JOIN   Locations ccl
ON     (smu.LocationId = ccl.Id)
UNION ALL
SELECT cp.SiteMaterialUsageId, smu.LocationId, smu.MaterialId, cp.CustomerId AS ConsignmentLocationId, NULL AS EndUseId,
NULL AS EndCustomerId,
NVL2(cp.GroupKey, NVL(ccl.WarehouseLocationId, ccl.Id), NULL) GroupId,
cp.SkuKey, ccl.WarehouseLocationId, ccl.StockLocationId
FROM   ConsignmentParameters cp
JOIN   SiteMaterialUsages smu
ON     (smu.Id = cp.SiteMaterialUsageId)
JOIN   Locations ccl
ON     (smu.LocationId = ccl.Id)
top
IH#SkuWorkingDays

WITH c AS (
SELECT CalendarId, DateFrom, IsWorkingDay,
         GREATEST(0, SUM(IsWorkingday) OVER(PARTITION BY CalendarId, DateFromMonth ORDER BY DateFrom) - 1) WorkingDays,
         SUM(IsWorkingDay) OVER(PARTITION BY CalendarId, DateFromMonth) TotalWorkingDays
  FROM   CalendarSources s
  WHERE   s.DATEFROMMONTH = TRUNC(core.getInternalDate, 'month')
  )
SELECT s.SiteMaterialUSageId, s.CalendarId, c.DateFrom, WorkingDays, TotalWorkingDays
FROM IH#CustomerSkuCalendars s
JOIN c ON c.CalendarId = s.CalendarId
WHERE TRUNC(c.DateFrom, 'month') = TRUNC(core.getInternalDate, 'month')

top
IH#SNPProductionConfigurations

select *
from (SELECT c.*,
ROW_NUMBER() OVER(PARTITION BY SnapshotUserId, ID, OperationTypeId ORDER BY Id) OrderNo
FROM ConfigurationSnapshots c)
Where OrderNo = 1
top
IH#SolutionTempData


SELECT d.SnapshotUserId, NVL(si.SplitItemId, si.Id) RealSNPItemId,
    AllocationId,
    MasterRouteId, WorkcentreId, si.MaterialId,
    SourcePeriod, DeliveryPeriod,
    StageNo, IsLastStage, ConfigurationId, OperationTypeId, NextOperationTypeId, SeqNo, SourcePropertyValueId, SourceMaterialId,
    isSafetyStock, WarehouseSnpItemId,
		SUM(Allocation) Allocation, SUM(productionCost) ProductionCost, SUM(TransportCost) TransportCost, SUM(InventoryCost) InventoryCost
FROM   Snosolutiontempdata d
JOIN   SNoItemsShort SI
ON     si.SnapshotUserId = d.SnapshotUserId
AND    si.Id = d.SnoItemId
AND    si.CoProductId IS NULL
GROUP BY d.SnapshotUserId, NVL(si.SplitItemId, si.Id),
    AllocationId,
    MasterRouteId, WorkcentreId, si.MaterialId,
    SourcePeriod, DeliveryPeriod,
    StageNo, IsLastStage, ConfigurationId, OperationTypeId, NextOperationTypeId, SeqNo, SourcePropertyValueId, SourceMaterialId,
    isSafetyStock, WarehouseSnpItemId
top
IH#SourcePriorities
SELECT sp.id, sp.SiteMaterialUsageId, sp.DestinationLocationId, WorkcentreId, ConsignmentLocationId,
dl.LocationName LocationName,
dl.LocationCode LocationCode,
dm.MaterialName MaterialName,
dm.MaterialCode MaterialCode,
eu.EndUseCode,
ec.LocationCode EndCustomerCode,
mt.MaterialTypeName,
wc.WorkcentreName,
wc.WorkcentreCode,
cl.LocationName CustomerName,
IsConsignmentStock,
sm.MaterialName SourceMaterialName,
sm.MaterialCode SourceMaterialCode,
Priority,
Portion,
JourneyCode Journey,
SIGN(NVL(SourcePriorityRuleId,0)) FromRule,
NVL(SourcePriorityRuleId,0) RuleId,
j.FromSiteId,
sp.DateFrom, sp.DateTo
FROM SourcePriorities sp
JOIN Workcentres wc ON (wc.Id = sp.WorkcentreId)
JOIN Locations dl ON dl.ID = sp.DestinationLocationId
JOIN Materials dm ON dm.ID = sp.DestinationMaterialId
JOIN Locations sl on sl.Id = wc.LocationId
JOIN SiteMaterialUsages smu ON smu.Id = sp.SiteMaterialUsageId
JOIN Sites s ON s.Id = sl.SiteId
LEFT JOIN Locations cl ON cl.ID = sp.ConsignmentLocationId
LEFT JOIN MaterialTypes mt ON mt.Id = sp.MaterialTypeId
LEFT JOIN Journeys j ON j.ID = sp.JourneyId
LEFT JOIN Materials sm ON sm.ID = sp.SourceMaterialId
LEFT JOIN EndUses eu on eu.Id = smu.EndUseId
LEFT JOIN Locations ec on ec.Id = smu.EndCustomerId
top
IH#SourcePriorityRules
SELECT sr.Id, d.DESCRIPTION Hierarchies,
d.PropertiesCode Properties, d.LocationCode, d.ProductCode,
MaterialTypeName,
WorkcentreName, WorkcentreCode, SiteName, SiteCode,
sr.Priority, RuleWeighting, JourneyCode
FROM Sourcepriorityrules sr JOIN IH#Workcentres wc ON wc.WorkcentreId = sr.WorkcentreID
JOIN Ih#hierarchypropertydetails d ON sr.DetailId = d.Id
LEFT JOIN MaterialTypes mt ON mt.Id = sr.MaterialTypeId
LEFT JOIN Journeys j ON j.id = sr.JourneyId
top
IH#SourceRunProducts
SELECT mrp.ProductName, sr.*
FROM SourceRuns sr JOIN MAterialRunProducts mrp
ON mrp.MAterialRunId = sr.MaterialRunId

top
IH#SplitMaterialRuns
 WITH runs AS
 (SELECT Id, WorkcentreId, RunCode, StartDate OriginalStartDate,
         DECODE(RunStatusCode, 'Started', StartDate + CompletedDuration / 1440, StartDate) StartDate,
         MIN(DECODE(RunStatusCode, 'Started', StartDate, NULL)) OVER (PARTITION BY WorkcentreId) MinStartedDate,
         TargetStartDate,
         FinishDate, RunStatusName, RunStatusCode, ProductionUpdateTimeStamp, QuantityComplete, InitialDuration, CompletedDuration,
         RemainingDuration, DECODE(RunStatusCode, 'Started', RemainingDuration, InitialDuration) Duration
  FROM   IH#MaterialRuns
  UNION ALL
  SELECT -Id, Workcentreid, RunCode, StartDate OriginalStartDate, StartDate,
         MIN(DECODE(RunStatusCode, 'Started', StartDate, NULL)) OVER (PARTITION BY WorkcentreId) MinStartedDate,
         TargetStartDate, FinishDate, RunStatusName, runStatusCode, ProductionUpdateTimeStamp,
         QuantityComplete, InitialDuration, CompletedDuration, RemainingDuration,
         DECODE(RunStatusCode, 'Started', CompletedDuration, InitialDuration) Duration
  FROM   IH#MaterialRuns
  WHERE  RunStatusCode = 'Started')
SELECT SIGN(Id) signId, to_number(to_char(ProductionUpdateTimeStamp,'YYYYMMDDHH24MISS')) n,
       SIGN(Id) * to_number(to_char(ProductionUpdateTimeStamp,'YYYYMMDDHH24MISS')) xx,
       case when RunStatusCode != 'Started' then StartDate else MinStartedDate end dd,
       row_number() over(PARTITION BY WorkcentreId order by

       case when RunStatusCode != 'Started' then StartDate else MinStartedDate end, SIGN(Id), SIGN(Id) * to_number(to_char(ProductionUpdateTimeStamp,'YYYYMMDDHH24MISS')) desc

       ) PositionNo ,

       runs.*
FROM runs
top
IH#StockMonitoringSku
SELECT m.MaterialName ProductName, m.MaterialCode ProductCode, l.LocationCode, l.LocationName,
s.AlternateProduct, NVL(cl.LocationCode, 'Free') ConsignmentCustomerCode, NVL(cl.LocationName, 'Free') ConsignmentCustomerName,
WorkcentreName, WorkcentreCode,
s.SiteMaterialUSageId,
s.ConsignmentLocationId, mt.MaterialTypeName, s.MaterialId
FROM
(SELECT smu.Id SiteMaterialUsageId, smu.LocationId, smu.MaterialId, NULL ConsignmentLocationId,
smu.SkuKey, Status, Replenished, AlternateProduct
FROM   SiteMaterialUsages smu
UNION ALL
SELECT cp.SiteMaterialUsageId, smu.LocationId, smu.MaterialId, cp.CustomerId AS ConsignmentLocationId,
cp.SkuKey, 0 Status, cp.Replenished, smu.AlternateProduct
FROM   ConsignmentParameters cp
JOIN   SiteMaterialUsages smu
ON     (smu.Id = cp.SiteMaterialUsageId)
) s
JOIN Materials m ON m.Id = s.MaterialId
JOIN Locations l ON l.Id = s.LocationId
JOIN MaterialTypes mt ON mt.Id = m.MaterialTypeId
JOIN Workcentres wc on wc.LocationId = s.LocationId
LEFT JOIN Locations cl ON cl.Id = s.ConsignmentLocationId
top
IH#StockMovements
WITH m AS
 (SELECT
   'Firm incoming orders' DESCRIPTION, SiteMaterialUsageId SkuId, SiteMaterialUsageId, SourceSiteMaterialUsageId, ol.Workcentreid, ol.Id,
   DeliveryDate MovementDate, 1 IsFirm, 'OrderLine' MovementType,
   GREATEST(0, ol.FinalWeight - GREATEST(ol.WeightComplete, ol.DeliveryWeight)) OrdersIn, 0 OrdersOut
  FROM   OrderLines ol, OrderLineStatuses ols
  WHERE  ol.orderlinestatusid = ols.id
  AND    ols.OrderLineStatusCode = 'Firm'
  AND    ol.DeliveryDate >= TRUNC(core.getInternalDate) -  (SELECT Nvl(Min(sp.Value),0) FROM SystemParameters sp WHERE sp.ParameterName = 'UseUncompleteOrders')
  UNION ALL
  SELECT
   'Completed incoming orders' DESCRIPTION, SiteMaterialUsageId SkuId, SiteMaterialUsageId, SourceSiteMaterialUsageId, ol.Workcentreid, ol.Id,
   DeliveryDate MovementDate, 1 IsFirm, 'OrderLine' MovementType,
   GREATEST(0, ol.FinalWeight - GREATEST(ol.WeightComplete, ol.DeliveryWeight)) OrdersIn, 0 OrdersOut
  FROM   OrderLines ol, OrderLineStatuses ols
  WHERE  ol.orderlinestatusid = ols.id
  AND    ols.OrderLineStatusCode = 'Completed'
  AND    ol.DeliveryDate = TRUNC(core.getInternalDate)
  UNION ALL
  SELECT
   'Incoming deliveries' DESCRIPTION, d.SiteMaterialUsageId SkuId, d.SiteMaterialUsageId, d.SourceSiteMaterialUsageId, ol.WorkcentreId, d.Id,
   d.ReceivedDate MovementDate, 1 IsFirm, 'Delivery', d.Weight OrdersIn, 0 OrdersOut
  FROM   Deliveries d, DeliveryStatuses ds, OrderLines ol
  WHERE  ol.Id = d.OrderLineId
  AND    d.DeliveryStatusId = ds.Id
  AND    ds.DeliveryStatusCode IN ('Firm', 'InTransit')
  AND    d.receiveddate >= TRUNC(core.getInternalDate) -  (SELECT Nvl(Min(sp.Value),0) FROM SystemParameters sp WHERE sp.ParameterName = 'UseUncompleteOrders')
  UNION ALL
  SELECT
   'Incoming delivered deliveries' DESCRIPTION, d.SiteMaterialUsageId SkuId, d.SiteMaterialUsageId, d.SourceSiteMaterialUsageId, ol.WorkcentreId, d.Id,
   d.ReceivedDate MovementDate, 1 IsFirm, 'Delivery', d.Weight OrdersIn, 0 OrdersOut
  FROM   Deliveries d, DeliveryStatuses ds, OrderLines ol
  WHERE  ol.Id = d.OrderLineId
  AND    d.DeliveryStatusId = ds.Id
  AND    ds.deliverystatuscode IN ('Delivered', 'SeparateDelivered')
  AND    d.ReceivedDate = TRUNC(core.getInternalDate)
  UNION ALL
  SELECT
   'Outgoing deliveries' DESCRIPTION, d.SourceSiteMaterialUsageId SkuId, d.SiteMaterialUsageId, d.SourceSiteMaterialUsageId, ol.WorkcentreId, d.Id,
   d.ShipDate MovementDate, 1 isFirm, 'Delivery', 0 OrdersIn,
   CASE
        WHEN ds.DeliveryStatusCode = 'InTransit' THEN
         d.OriginalWeight * d.SourceCoef
        ELSE
         d.SourceWeight
    END OrdersOut
  FROM   Deliveries d, DeliveryStatuses ds, OrderLines ol
  WHERE  ol.Id = d.OrderLineId
  AND    d.DeliveryStatusId = ds.Id
  AND    ds.DeliveryStatusCode IN ('Firm')
  AND    d.shipdate >= TRUNC(core.getInternalDate) -  (SELECT Nvl(Min(sp.Value),0) FROM SystemParameters sp WHERE sp.ParameterName = 'UseUncompleteOrders')
  UNION ALL
  SELECT
   'Outgoing delivered/intransit deliveries' DESCRIPTION, d.SourceSiteMaterialUsageId SkuId, d.SiteMaterialUsageId, d.SourceSiteMaterialUsageId,
   ol.WorkcentreId, d.Id, d.ShipDate, 1 isFirm, 'Delivery', 0 OrdersIn,
   CASE
        WHEN ds.DeliveryStatusCode = 'InTransit' THEN
         d.OriginalWeight * d.SourceCoef
        ELSE
         d.SourceWeight
    END OrdersOut
  FROM   Deliveries d, DeliveryStatuses ds, OrderLines ol
  WHERE  ol.Id = d.OrderLineId
  AND    d.DeliveryStatusId = ds.Id
  AND    ds.deliverystatuscode IN ('Delivered', 'InTransit')
  AND    d.ShipDate = TRUNC(core.getInternalDate)
  UNION ALL
  SELECT
   'Outgoing firm orders' DESCRIPTION, SourceSiteMaterialUsageId SkuId, SiteMaterialUsageId, SourceSiteMaterialUsageId, ol.WorkcentreId, ol.Id,
   ol.ConsumptionDate, 1 IsFirm, 'OrderLine', 0 OrdersIn,
   GREATEST(0, ol.SourceWeight - GREATEST(ol.WeightIssued, ol.WeightComplete * ol.SourceCoef, ol.DeliverySourceWeight)) OrdersOut
  FROM   OrderLines ol, OrderLineStatuses ols
  WHERE  ol.orderlinestatusid = ols.id
  AND    ols.OrderLineStatusCode = 'Firm'
  AND    ol.ConsumptionDate >=  TRUNC(core.getInternalDate) -  (SELECT Nvl(Min(sp.Value),0) FROM SystemParameters sp WHERE sp.ParameterName = 'UseUncompleteOrders')
  UNION ALL
  SELECT
   'Outgoing completed firm orders' DESCRIPTION, SourceSiteMaterialUsageId SkuId, SiteMaterialUsageId, SourceSiteMaterialUsageId, ol.workcentreId, ol.Id,
   ol.ConsumptionDate, 1 IsFirm, 'OrderLine', 0 OrdersIn,
   GREATEST(0, ol.SourceWeight - GREATEST(ol.WeightIssued, ol.WeightComplete * ol.SourceCoef, ol.DeliverySourceWeight)) OrdersOut
  FROM   OrderLines ol, OrderLineStatuses ols
  WHERE  ol.orderlinestatusid = ols.id
  AND    ols.OrderLineStatusCode = 'Completed'
  AND    ol.ConsumptionDate = TRUNC(core.getInternalDate)
  UNION ALL
  SELECT 'Completed incoming order line inventories' DESCRIPTION, SiteMaterialUsageId SkuId, SiteMaterialUsageId, SourceSiteMaterialUsageId,
         workcentreId, ob.Id, ob.deliverydate AS MovementDate, 1 IsFirm, 'OrderInventory', StockWeight ordersIn,
         0 OrdersOut
  FROM   OrderInventoryIPlanView ob
  WHERE  IsDelivered = 0
  AND    ob.OrderLineStatusCode = 'Completed'
  AND    ob.deliverydate >=  TRUNC(core.getInternalDate) -  (SELECT Nvl(Min(sp.Value),0) FROM SystemParameters sp WHERE sp.ParameterName = 'UseUncompleteOrders')
  UNION ALL
  SELECT 'Incoming order line inventories' DESCRIPTION, SiteMaterialUsageId SkuId, SiteMaterialUsageId, SourceSiteMaterialUsageId, workcentreId,
         ob.Id, ob.deliverydate AS MovementDate, 1 IsFirm, 'OrderInventory', StockWeight ordersIn, 0 OrdersOut
  FROM   OrderInventoryIPlanView ob
  WHERE  IsDelivered = 0
  AND    ob.OrderLineStatusCode NOT IN ('Completed', 'Cancelled')
  AND    ob.deliverydate >=  TRUNC(core.getInternalDate) -  (SELECT Nvl(Min(sp.Value),0) FROM SystemParameters sp WHERE sp.ParameterName = 'UseUncompleteOrders')
  UNION ALL
  SELECT 'Outgoing order line inventories' DESCRIPTION, SourceSiteMaterialUsageId SkuId, SiteMaterialUsageId, SourceSiteMaterialUsageId, workcentreId,
         ob.Id, ob.ConsumptionDate AS MovementDate, 1 IsFirm, 'OrderInventory', 0 ordersIn, StockWeight OrdersOut
  FROM   OrderInventoryIPlanView ob
  WHERE  IsSameSource = 1
  AND    ob.OrderLineStatusCode = 'Completed'
  AND    ob.ConsumptionDate >= TRUNC(core.getInternalDate) -  (SELECT Nvl(Min(sp.Value),0) FROM SystemParameters sp WHERE sp.ParameterName = 'UseUncompleteOrders')
)
SELECT m.DESCRIPTION, SkuId, m.SiteMAterialUsageId, m.SourceSiteMaterialUsageId, m.WorkcentreId, m.ID,
GREATEST(TRUNC(core.getInternalDate), m.MovementDate) MovementDate, m.isFirm,
       m.MovementType, m.OrdersIn, m.OrdersOut, NVL(l.SiteId, 0) DestinationSiteId, NVL(sl.SiteId, 0) SourceSiteId
FROM   m
JOIN   Workcentres wc
ON     m.WorkcentreId = wc.Id
JOIN   Locations sl
ON sl.Id = wc.LocationId
JOIN   siteMaterialUsages smu
ON     smu.Id = m.SiteMaterialUsageId
JOIN   Locations l
ON     l.Id = smu.LocationId

top
IH#StockStates
SELECT bv.*, Description StockState
  FROM BundleValues bv
  JOIN Bundles b ON b.Id = bv.BundleId
 WHERE b.Name = 'StockStates'
 ORDER BY bv.OrderNo
top
IH#SuccessReplenishmentLogs
Select Id, Action, Description, Stamp, Stamp - Lag(Stamp) OVER
(ORDER BY Id,Stamp) Diff
from ProcessLogs
Where ProcessId IN (Select Max(Id) from
Processes Where ProcessType = 'Replenishment'
AND Status = 1)
Order by Id
top
IH#SupersededOpeningProfiles View for calculation opening/closing values in real inventory profiles

SELECT SiteMaterialUSageID, ConsignmentLocationId, SkuKey,
              DateFrom,
              FIRST_VALUE(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(OrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0)
              - NVL(SUM(OrdersOut) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) Opening,

              First_value(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(OrdersIn + TentativeOrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0)
              - NVL(SUM(OrdersOut + Consumption + TentativeOrdersOut) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) OverAllOpening,

              First_value(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(OrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0)
              - NVL(SUM(OrdersOut + Consumption) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) TentativeOpening,

              First_value(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(OrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0)
              - NVL(SUM(OrdersOut + Consumption) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) FirmOpening,
              OrdersIn, TentativeOrdersIn,
              OrdersOut, TentativeOrdersOut,
              Consumption,
              First_value(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(OrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND p.ClosingMethod PRECEDING),0)
              - NVL(SUM(OrdersOut) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING),0) Closing,

              First_value(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(OrdersIn + TentativeOrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND p.ClosingMethod PRECEDING),0)
              - NVL(SUM(OrdersOut + Consumption + TentativeOrdersOut) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING),0) OverallClosing,

              First_value(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(OrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND p.ClosingMethod PRECEDING),0)
              - NVL(SUM(OrdersOut + Consumption) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING),0) TentativeClosing,

              First_value(Opening) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId ORDER BY DateFrom)
              + NVL(SUM(OrdersIn) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND p.ClosingMethod PRECEDING),0)
              - NVL(SUM(OrdersOut + Consumption) OVER(PARTITION BY SiteMaterialUSageId, ConsignmentLocationId
                                             ORDER BY DateFrom ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING),0) FirmClosing,
              SafetyStock,
              MaxSafetyStock
FROM IH#SupersededRealProfiles
CROSS JOIN (SELECT UseTentativeOrders, DECODE(RPClosingCalculationMethod, 'AfterDeliveryDate', 1, 0) ClosingMethod FROM IH#ReplenishmentParameters) p
/*ORDER BY 1,2, DateFrom*/
top
IH#SupersededOrderLines
SELECT ol.Id OrderLineId, NVL(OnSiteMaterialUsageId, ol.SiteMaterialUsageID) OnSiteMaterialUsageId,
       ol.SiteMaterialUsageId, ol.WorkcentreId OrderWorkcentreId, ol.WorkcentreId, DeliveryDate, FinalWeight, PeriodType,
       OrderLineStatusId, ol.LocationId
FROM   OrderLines ol
LEFT   JOIN (SELECT *
             FROM   IH#AllMaterialSupercessions s
             WHERE  NOT EXISTS
              (SELECT 1 FROM IH#AllMaterialSupercessions s2 WHERE s.OnSiteMaterialUsageId = s2.SiteMaterialUsageId)) ms
ON     ol.SiteMaterialUsageID = ms.SiteMaterialUsageId
AND    ms.Status = 0
top
IH#SupersededOrders
SELECT
SiteMaterialUsageId, DeliveryMonth,  SUM(Orders) Orders,
       SUM(OrdersIncludeSupercessions) OrdersIncludeSupercessions
FROM IH#SiteSupersededOrders
group by  SiteMaterialUsageId, DeliveryMonth
top
IH#SupersededRealProfiles View with aggregated superseded replenished sku.

SELECT NVL(rs.OnSiteMaterialUsageId, r.SiteMaterialUsageId) SiteMaterialUsageId, ConsignmentLocationId, DateFrom,
       NVL(rs.SkuKey, r.SkuKey) SkuKey, SUM(Opening) Opening,
       SUM(OrdersIn) OrdersIn, SUM(OrdersOut) OrdersOut, SUM(TentativeOrdersIn) TentativeOrdersIn,
       SUM(TentativeOrdersOut) TentativeOrdersOut, SUM(Consumption) Consumption,
       SUM(NVL2(rs.OnSiteMaterialUsageId, 0, SafetyStock)) SafetyStock,
       SUM(NVL2(rs.OnSiteMaterialUsageId, 0, MaxSafetyStock)) MaxSafetyStock
  FROM RealInventoryProfiles r
  LEFT JOIN (
	SELECT s.*, OnSiteMaterialUsageId || '-0' SkuKey
               FROM ReplenishedSubstitutedSku  s
              CROSS JOIN IH#ReplenishmentParameters p
              WHERE UseSupercessions != 'None'
              AND s.Replenished = 0
							) rs
    ON r.SiteMaterialUsageId = rs.SiteMaterialUsageId
 GROUP BY NVL(rs.OnSiteMaterialUsageId, r.SiteMaterialUsageId), ConsignmentLocationId, DateFrom, NVL(rs.SkuKey, r.SkuKey)
top
IH#SupersededSkuStockStatus

SELECT r.SiteMaterialUsageId, r.ConsignmentLocationId, r.SkuKey, DateFrom, OverallOpening, OverallClosing, r.SafetyStock,
r.MaxSafetyStock, s.MaxCapacity,
       s.SafetyStockPercentWarning, 1 Superseded,
       CASE
           WHEN DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < 0 THEN
            1
           WHEN (SELECT VALUE FROM SystemParameters WHERE ParameterName = 'StockLevelAtZeroWarning') =
                'InventoryLessOrEqualZero' AND r.SafetyStock > 0 AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) = 0 THEN
            1
           WHEN r.SafetyStock > 0 AND s.SafetyStockPercentWarning > 0 AND
                DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < r.SafetyStock * s.SafetyStockPercentWarning / 100 THEN
            2
           WHEN r.SafetyStock > 0 AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) < r.SafetyStock THEN
            3
           WHEN s.MaxCapacityBehaviour IN ('Warning', 'Limit') AND s.MaxCapacity > 0 AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) > s.MaxCapacity THEN
            4
           WHEN s.MaxSafetyStockMethodId IS NOT NULL AND r.MaxSafetyStock IS NOT NULL AND DECODE(p.StockStateField, 'Closing', OverAllClosing, OverallOpening) > r.MaxSafetyStock THEN
            5
           ELSE
            9
       END StockStatus,

       CASE
           WHEN DECODE(p.StockStateField, 'Closing', TentativeClosing, TentativeOpening) < 0 THEN
            1
           WHEN (SELECT VALUE FROM SystemParameters WHERE ParameterName = 'StockLevelAtZeroWarning') =
                'InventoryLessOrEqualZero' AND r.SafetyStock > 0 AND DECODE(p.StockStateField, 'Closing', TentativeClosing, TentativeOpening) = 0 THEN
            1
           WHEN r.SafetyStock > 0 AND s.SafetyStockPercentWarning > 0 AND
                DECODE(p.StockStateField, 'Closing', TentativeClosing, TentativeOpening) < r.SafetyStock * s.SafetyStockPercentWarning / 100 THEN
            2
           WHEN r.SafetyStock > 0 AND DECODE(p.StockStateField, 'Closing', TentativeClosing, TentativeOpening) < r.SafetyStock THEN
            3
           WHEN s.MaxCapacityBehaviour IN ('Warning', 'Limit') AND s.MaxCapacity > 0 AND DECODE(p.StockStateField, 'Closing', TentativeClosing, TentativeOpening) > s.MaxCapacity THEN
            4
           WHEN s.MaxSafetyStockMethodId IS NOT NULL AND r.MaxSafetyStock IS NOT NULL AND DECODE(p.StockStateField, 'Closing', TentativeClosing, TentativeOpening) > r.MaxSafetyStock THEN
            5
           ELSE
            9
       END TentativeStockStatus
FROM   IH#SupersededOpeningProfiles r
JOIN   IH#WHStockMonitoring s
ON     s.SiteMaterialUsageId = r.SiteMaterialUsageId
AND    NVL(S.ConsignmentLocationId, 0) = NVL(r.ConsignmentLocationId, 0)
CROSS JOIN (SELECT NVL(MIN(VALUE), 'Closing') StockStateField FROM SystemPArameters WHERE ParameterName = 'RPStockStateField') p
/* WHERE  EXISTS (SELECT 1 FROM ReplenishedSubstitutedSku s WHERE s.OnSiteMaterialUSageId = r.SiteMaterialUsageId And s.Replenished = 0) */

top
IH#TradingDays
SELECT CalendarId, DateFromMonth, SUM(IsworkingDay) TradingDays
FROM   CalendarSources
GROUP BY CalendarId, DateFromMonth
top
IH#TransportLocationLocations
    SELECT tl.LocationName TransportLocationName,
    tl.LocationCode TransportLocationCode,
    tl.Id TransportLocationId,
    l.Id LocationId, l.LocationName, l.LocationCode
    FROM IH#TransportLocations tl
    JOIN Locations l ON
    l.TransportLocationId = tl.Id
    ORDER BY 1
top
IH#TransportLocations
    SELECT * FROM Locations WHERE ID IN (SELECT TransportLocationId FROM Locations WHERE TransportLocationId IS NOT NULL)
top
IH#TransportMethodsForEdge


SELECT WorkcentreName, WorkcentreCode,
       l.LocationName ToLocationName, l.LocationCode ToLocationCode, TransportMethodId as Id, TransportMethodName,
       TransportMethodCode,
wc.Id Workcentreid, l.Id ToLocationId
FROM   Journeysiplanview j
JOIN   Workcentres wc
ON     wc.LocationId = fromLocationId
JOIN   Locations l
ON     (l.Id = j.ToLocationId or l.TransportLocationId = j.ToLocationId)

top
IH#TransportRoutes
SELECT tr.Id, tr.FromLocationId, tr.ToLocationId, tr.TransportMethodId, tr.CalendarId, tr.ScheduleId,
tr.TimePeriod, tr.COST, tr.Priority,
tr.LoadingTime, tr.UnloadingTime,
s.SiteName Site,
s.Id FromSiteId,
NVL(ts.Id,0) ToSiteId,
f.LocationName SOURCE, t.LocationName Destination,
tm.TransportMethodName Method,
c.CalendarName Calendar,
sc.ScheduleName Schedule
FROM TransportRoutes tr
JOIN Locations f ON (f.Id = tr.FromLocationId)
JOIN Locations t ON (t.Id = tr.ToLocationId)
JOIN TransportMethods tm ON (tm.Id = tr.TransportMethodId)
JOIN Sites s ON (s.Id = f.SiteId)
LEFT JOIN Sites ts ON (ts.Id = t.SiteId)
LEFT JOIN Calendars c ON (c.Id = tr.CalendarId)
LEFT JOIN Schedules sc ON (sc.Id = tr.ScheduleId)
  
top
IH#TransposedMaterials
WITH props AS (SELECT * FROM Propertiesiplanview)
SELECT m.MaterialId, props.Id AS PropertyId, Code1 PropertyCode, Value1 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 1
AND Code1 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code2 PropertyCode, Value2 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 2
AND Code2 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code3 PropertyCode, Value3 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 3
AND Code3 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code4 PropertyCode, Value4 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 4
AND Code4 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code5 PropertyCode, Value5 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 5
AND Code5 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code6 PropertyCode, Value6 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 6
AND Code6 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code7 PropertyCode, Value7 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 7
AND Code7 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code8 PropertyCode, Value8 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 8
AND Code8 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code9 PropertyCode, Value9 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 9
AND Code9 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code10 PropertyCode, Value10 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 10
AND Code10 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code11 PropertyCode, Value11 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 11
AND Code11 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code12 PropertyCode, Value12 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 12
AND Code12 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code13 PropertyCode, Value13 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 13
AND Code13 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code14 PropertyCode, Value14 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 14
AND Code14 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code15 PropertyCode, Value15 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 15
AND Code15 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code16 PropertyCode, Value16 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 16
AND Code16 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code17 PropertyCode, Value17 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 17
AND Code17 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code18 PropertyCode, Value18 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 18
AND Code18 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code19 PropertyCode, Value19 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 19
AND Code19 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code20 PropertyCode, Value20 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 20
AND Code20 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code21 PropertyCode, Value21 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 21
AND Code21 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code22 PropertyCode, Value22 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 22
AND Code22 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code23 PropertyCode, Value23 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 23
AND Code23 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code24 PropertyCode, Value24 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 24
AND Code24 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code25 PropertyCode, Value25 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 25
AND Code25 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code26 PropertyCode, Value26 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 26
AND Code26 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code27 PropertyCode, Value27 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 27
AND Code27 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code28 PropertyCode, Value28 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 28
AND Code28 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code29 PropertyCode, Value29 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 29
AND Code29 IS NOT NULL
UNION ALL
SELECT m.MaterialId, props.Id AS PropertyId, Code30 PropertyCode, Value30 PropertyValue, props.OriginalPropertyName
FROM MaterialPropsSpec m, props
WHERE props.OrderNO = 30
AND Code30 IS NOT NULL
top
IH#UsedExternalTrends
SELECT DISTINCT SiteMaterialUsageId, TRIM(REGEXP_SUBSTR(UsedExternalTrends,'[^,]+', 1, level) ) ForecastPatternId
FROM 
(
      SELECT SiteMaterialUsageId, UsedExternalTrends 
        FROM Forecaststatistics fs
       WHERE fs.ForecastId = forecasting.GetLatestForecast()
         AND UsedExternalTrends IS NOT NULL
)
CONNECT BY REGEXP_SUBSTR(UsedExternalTrends, '[^,]+', 1, level) IS NOT NULL
top
IH#UserPageParameters

SELECT pp.Id, PageId, pp.ParameterName, t.ParameterDescription, ParameterType, DataType, MINVALUE, MAXVALUE, DependOn, 
       DependBehaviour, DependValues, OrderNo, GroupName, Separator,
       DECODE(COALESCE(up.Value, pp.Value, pp.DefaultValue),
       '{SYSDATE}', to_char(Trunc(core.getInternalDate, 'month'), 'YYYY-MM-DD'),
       COALESCE(up.Value, pp.Value, pp.DefaultValue))  AS VALUE,
u.Id userId, LanguageId, pp.ParameterHint, pp.ActionId, pp.BundleId, pp.IsDevMode
FROM   PageParameters pp
JOIN IT#PageParameters t ON (t.Id = pp.Id)
CROSS JOIN USERS u
LEFT   JOIN UserPageParameters up
ON     (up.PageParameterid = pp.Id AND u.id = userid)
top
IH#UserParameters
WITH s
AS
(
SELECT u.Id UserId, sp.*
FROM SystemParameters sp, USERS u
WHERE ParameterType IN ('user', 'session')
)
SELECT s.UserId,
NVL(u.Value, s.Value) as VALUE,
s.Id, s.ParameterName, ParameterType, ParameterArea, DataType, MINVALUE, MAXVALUE, CATEGORY, DependOn, ParameterDescription, ParameterHelp,
s.Cloud, READONLY, s.BundleId
FROM s LEFT JOIN UserParameters u ON (s.Id = u.SystemParameterId AND u.UserId= s.UserId)
top
IH#UserPermissions
SELECT ur.UserId, ra.ActionId, p.PageName, a.ActionName
FROM Actions a
JOIN RolesActions ra ON (ra.ActionId = a.Id)
JOIN UsersRoles ur ON (ur.RoleId = ra.RoleId)
JOIN Pages p ON (p.Id = a.PageId)
top
IH#UserReports

SELECT uds.Id UserDataSourceId, uds.Parentdatasourceid, uds.Title, uds.Description,  ds.Name, u.UserName, uds.IsPublished
FROM   datasources uds
JOIN   DataSources ds
ON     ds.Id = uds.ParentDataSourceId
JOIN   USERS u
ON     u.Id = uds.UserId
WHERE  uds.Type = 'user'


top
IH#ValidOperationSources
SELECT ot.Id OperationTypeId, wc.WorkcentreTypeId, wc.Id WorkcentreId,
OperationTypeName, WorkcentreTypeName, WorkcentreName
 FROM OperationTypes ot
JOIN WorkcentreTypes wct ON wct.Id = ot.WorkcentreTypeId
JOIN Workcentres wc ON wc.WorkcentreTypeId = wct.Id
WHERE (EXISTS (SELECT 1 FROM Productroutestages prs WHERE prs.OperationTypeId = ot.Id)
       OR NOT EXISTS(SELECT 1 FROM ProductRoutes))
top
IH#ValidSources

   SELECT ProductionConfigurationId, OperationTypeId,
          core.AsCsv(CAST(COLLECT(to_char(WorkcentreId)) AS ParameterArray)) ValidSources,
          core.AsCsv(CAST(COLLECT(DECODE(SourceRank, 'primary', to_char(WorkcentreId), NULL)) AS ParameterArray)) PrimaryValidSources
   FROM   ValidSources
   GROUP  BY ProductionConfigurationId, OperationTypeId

top
IH#WarehouseCapacities
SELECT l.Id LocationId, l.SiteId, l.Capacity FROM Locations l JOIN Ih#workcentres wc ON wc.LocationId = l.Id
WHERE wc.WorkcentreTypeName IN ('Warehouse', 'SemiFinisingWarehouse')
top
IH#WarehouseConsumption
SELECT GroupKey, MaterialId, wc.*
FROM   WarehouseConsumption wc
JOIN   GroupedSku g
ON     wc.WarehouseSkuId = g.SiteMaterialUsageId
AND    NVL(wc.Consignmentlocationid, 0) = NVL(g.ConsignmentLocationId, 0)
top
IH#Warehouses
SELECT wc.*, NVL(wp.Value, 0) IsFreeStockWarehouse
FROM   IH#Workcentres wc
LEFT JOIN   IH#WorkcentreParameters wp
ON     wp.WorkcentreId = wc.WorkcentreId
AND    ParameterName = 'IsFreeStockWarehouse'
WHERE  wc.WorkcentreTypeName = 'Warehouse'
top
IH#WastedTableSpace

SELECT table_name, round((blocks * 8 / 1024), 2) AS SIZEmb,
       round((num_rows * avg_row_len / 1024 / 1024), 2) ActualSizeMB,
       (round((blocks * 8 / 1024), 2) - round((num_rows * avg_row_len / 1024 / 1024), 2)) WastedSize,
       ((round((blocks * 8), 2) - round((num_rows * avg_row_len / 1024), 2)) / round((blocks * 8), 2)) * 100 - PCT_FREE ReclaimableSpaceInPercent
FROM   user_tables
WHERE  (round((blocks * 8), 2) > round((num_rows * avg_row_len / 1024), 2))
AND round((blocks * 8 / 1024), 2) > 10 /* tables with size more than 10 mb */
AND ((round((blocks * 8), 2) - round((num_rows * avg_row_len / 1024), 2)) / round((blocks * 8), 2)) * 100 - 10 >= 30

top
IH#WeeklyUsageHistories
SELECT hd.SiteMaterialUSageId, TRUNC(DateFrom, 'IW') DateFrom,
       NVL(SUM(Weight),0) Weight,
       NVL(SUM(AdjustedWeight),0) OriginalAdjustedWeight,
       GREATEST(0, SUM(NVL(AdjustedWeight, Weight))) HistoryWeight,
       SUM(NVL(AdjustedWeight, Weight)) AdjustedHistoryWeight
FROM   UsageHistories hd
GROUP  BY hd.SiteMaterialUSageId, TRUNC(DateFrom, 'IW')
top
IH#WeightUnits
SELECT u.Id, u.UnitName, u.UnitDescription, Dividend, Divisor, u.UnitTypeId
FROM Units u JOIN UnitTypes ut ON ut.Id = u.UnitTypeId
AND UnitTypeName = 'Weight'
AND Dividend != -1
UNION ALL
SELECT u.Id, u.UnitName, u.UnitDescription, Dividend, Divisor, u.UnitTypeId
FROM Units u
JOIN UnitTypeConverts uc
ON (uc.ToUnitTypeId = u.UnitTypeId)
JOIN  UnitTypes ut
ON   (ut.Id = uc.FromUnitTypeID)
WHERE ut.UnitTypeName = 'Weight'
top
IH#WHSkus

SELECT smu.Id SiteMaterialUsageId, smu.LocationId, smu.MaterialId, wc.Id WorkcentreId, NULL ConsignmentLocationId,
       smu.DaysOfSupply, smu.HighQuantity, smu.LowQuantity, 
       smu.MinOrderQuantity, smu.OrderUnitId, COALESCE(smu.OrderUnitId, ru.UnitId) RoundOrderUnitId,
       smu.MaxCapacity, smu.Replenished,
       NVL(smu.ReplenishmentStartDate, m.ReplenishmentStartDate) ReplenishmentStartDate,
       NVL(smu.ReplenishmentFinishDate, m.ReplenishmentFinishDate) ReplenishmentFinishDate,
       COALESCE(smu.SafetyStockMethodId, ccl.SafetyStockMethodId, c.SafetyStockMethodId, p.DefaultSafetyStockMethodId) SafetyStockMethodId,
       NVL(smu.SafetyStockPercentWarning, p.DefaultSSPercentWarning) SafetyStockPercentWarning,
       NVL(smu.UpperPercentile, p.DefaultSKUUpperPercentile) UpperPercentile, NVL(smu.LowerPercentile, p.DefaultSKULowerPercentile) LowerPercentile,
       smu.UpperPercentileMethod, smu.UpperPercentileMonths,
       cr.Id CustomerRankId, cr.CustomerRankDesc,
       smu.ReplenishmentFrequency, smu.AlternateProduct,
       smu.MaxDaysOfSupply, NVL(smu.MaxReplenishmentFrequency, 0) MaxReplenishmentFrequency,  smu.MaxSafetyStockMethodId,
       NVL(ccl.CalendarId, p.DefaultCalendarId) CalendarId,
       smu.GroupKey, NVL2(smu.GroupKey, NVL(ccl.WarehouseLocationId, ccl.Id), NULL) GroupId,
       smu.SkuKey, ccl.WarehouseLocationId, ccl.StockLocationId, smu.SourceListId,
       smu.LastInventoryDate, smu.ReplenishmentHorizon,
       ccl.SiteId, ccl.CompanyId,
       smu.SkuProperty1, smu.SkuProperty2, smu.SkuProperty3, smu.SkuProperty4, smu.SkuProperty5, smu.SkuProperties,
       smu.IsActiveSku
  FROM SiteMaterialUsages smu
 CROSS JOIN IH#DefaultParameters p
  JOIN Locations ccl ON smu.LocationId = ccl.Id
  JOIN Companies c ON c.Id = ccl.CompanyID
  JOIN Materials m ON m.Id = smu.MaterialId
  JOIN Workcentres wc on wc.LocationId = smu.LocationId
  LEFT JOIN CustomerRanks cr ON COALESCE(smu.CustomerRankId, ccl.CustomerRankId, c.CustomerRankId, p.DefaultCustomerRankId) = cr.Id
  LEFT JOIN IH#MaterialTypeRoundingUnits ru ON ru.MaterialTypeId = m.MaterialTypeId
 WHERE EXISTS (SELECT 1 FROM WorkCentres w WHERE w.LocationId = smu.LocationId)
 UNION ALL
SELECT cp.SiteMaterialUsageId, smu.LocationId, smu.MaterialId, wc.Id WorkcentreId, cp.CustomerId AS ConsignmentLocationId,
       cp.DaysOfSupply, cp.HighQuantity, cp.LowQuantity, 
       cp.MinOrderQuantity,  COALESCE(cp.OrderUnitId, smu.OrderUnitId) OrderUnitId, COALESCE(cp.OrderUnitId, smu.OrderUnitId, ru.UnitId) RoundOrderUnitId,
       NULL AS MaxCapacity, cp.Replenished,
       NVL(cp.ReplenishmentStartDate, m.ReplenishmentStartDate) ReplenishmentStartDate,
       NVL(cp.ReplenishmentFinishDate, m.ReplenishmentFinishDate) ReplenishmentFinishDate,
       COALESCE(cp.SafetyStockMethodId, ccl.SafetyStockMethodId, c.SafetyStockMethodId, p.DefaultSafetyStockMethodId) SafetyStockMethodId,
       NVL(cp.SafetyStockPercentWarning,p.DefaultSSPercentWarning) SafetyStockPercentWarning,
       NVL(smu.UpperPercentile, p.DefaultSKUUpperPercentile) UpperPercentile, NVL(smu.LowerPercentile, p.DefaultSKULowerPercentile) LowerPercentile,
       smu.UpperPercentileMethod, smu.UpperPercentileMonths,
       cr.Id AS CustomerRankId, cr.CustomerRankDesc, 
       cp.ReplenishmentFrequency, cp.AlternateProduct,
       cp.MaxDaysOfSupply, NVL(cp.MaxReplenishmentFrequency, 0) MaxReplenishmentFrequency, cp.MaxSafetyStockMethodId,
       NVL(ccl.CalendarId, p.DefaultCalendarId) CalendarId,
       cp.GroupKey, NVL2(cp.GroupKey, NVL(ccl.WarehouseLocationId, ccl.Id), NULL) GroupId,
       cp.SkuKey, ccl.WarehouseLocationId, ccl.StockLocationId, smu.SourceListId,
       cp.LastInventoryDate, cp.ReplenishmentHorizon,
       ccl.SiteId, ccl.CompanyId,
       smu.SkuProperty1, smu.SkuProperty2, smu.SkuProperty3, smu.SkuProperty4, smu.SkuProperty5, smu.SkuProperties,
       cp.IsActiveSku
  FROM ConsignmentParameters cp
  JOIN SiteMaterialUsages smu ON smu.Id = cp.SiteMaterialUsageId
 CROSS JOIN IH#DefaultParameters p
  JOIN Locations ccl ON smu.LocationId = ccl.Id
  JOIN Companies c ON c.Id = ccl.CompanyID
  JOIN Materials m ON m.Id = smu.MaterialId
  JOIN Workcentres wc on wc.LocationId = smu.LocationId
  LEFT JOIN CustomerRanks cr ON COALESCE(smu.CustomerRankId, ccl.CustomerRankId, c.CustomerRankId, p.DefaultCustomerRankId) = cr.Id
  LEFT JOIN IH#MaterialTypeRoundingUnits ru ON ru.MaterialTypeId = m.MaterialTypeId
 WHERE EXISTS (SELECT 1 FROM WorkCentres w WHERE w.LocationId = smu.LocationId)

top
IH#WHStockMonitoring
SELECT smu.Id SiteMaterialUsageId, NULL ConsignmentLocationId, smu.LocationId, SkuKey, SafetyStockMethodId, MaxSafetyStockMethodId,
MaxCapacity, NVL(SafetyStockPercentWarning, (SELECT Value from SystemPArameters Where ParameterName = 'DefaultSafetyStockPercentWarning')) SafetyStockPercentWarning,
 VALUE MaxCapacityBehaviour
FROM SiteMaterialUsages smu
JOIN Ih#workcentreparameters wp
ON ParameterName = 'MaxCapacityBehaviour'
AND smu.LocationId = wp.LocationId
UNION ALL
SELECT cp.SiteMaterialUsageId, cp.CustomerId, smu.LocationId, cp.SkuKey, cp.SafetyStockMethodId, cp.MaxSafetyStockMethodId,
smu.MaxCapacity, NVL(cp.SafetyStockPercentWarning, (SELECT Value from SystemPArameters Where ParameterName = 'DefaultSafetyStockPercentWarning')) SafetyStockPercentWarning,  VALUE MaxCapacityBehaviour
FROM ConsignmentParameters cp
JOIN SiteMaterialUsages smu ON smu.Id = cp.Sitematerialusageid
JOIN Ih#workcentreparameters wp
ON ParameterName = 'MaxCapacityBehaviour'
AND smu.LocationId = wp.LocationId
top
IH#WorkCentreDestinations
    
WITH w AS (SELECT sw.Id AS FromWorkCentreId,
                   sl.Id AS FromLocationId,
                   sw.WorkCentreName AS FromWorkCentreName,
                   sw.WorkCentreCode AS FromWorkCentreCode,
                   sl.LocationName AS FromLocationName,
                   sl.LocationCode AS FromLocationCode,
                   dw.WorkCentreId AS ToWorkCentreId,
                   dl.Id AS ToLocationId,
                   dw.WorkCentreName AS ToWorkCentreName,
                   dw.WorkCentreCode AS ToWorkCentreCode,
                   dl.LocationName AS ToLocationName,
                   dl.LocationCode AS ToLocationCode,
                   1 IsDefault
              FROM WorkCentres sw
              LEFT JOIN (SELECT wp.WorkCentreId, w.LocationId AS Value FROM WorkCentreParameters wp
                           JOIN WorkCentreParameterTypes wpt ON wpt.Id = wp.ParameterTypeId
                            AND wpt.ParameterName = 'PMOverrideWarehouse'
                           JOIN WorkCentres w ON w.WorkCentreCode = wp.Value
                          WHERE NVL(wp.Value, wpt.DefaultValue) != 'undefined') wp ON wp.WorkCentreId = sw.Id
              JOIN Locations sl ON sl.Id = sw.LocationId
              JOIN Locations dl ON dl.SiteId = sl.SiteId
              LEFT JOIN IH#MainWarehouses dw ON dw.SiteId = dl.SiteId
             WHERE dl.Id = Coalesce(wp.Value, dw.LocationId, dl.Id))

SELECT w.FromWorkCentreId, w.FromLocationId,
       w.FromWorkCentreName, w.FromWorkCentreCode, w.FromLocationName, w.FromLocationCode,
       wh.WorkCentreId AS ToWorkCentreId, wh.LocationId AS ToLocationId,
       wh.WorkCentreName AS ToWorkCentreName, wh.WorkCentreCode AS ToWorkCentreCode,
       wh.LocationName AS ToLocationName, wh.LocationCode AS ToLocationCode,
       0 IsDefault,
       w.ToLocationId AS MainWHLocationId,
       w.ToWorkCentreName AS MainWHWorkCentreName, w.ToWorkCentreCode AS MainWHWorkCentreCode,
       w.ToLocationName AS MainWHLocationName, w.ToLocationCode AS MainWHLocationCode
  FROM w
  JOIN JourneysIPlanView j ON j.FromLocationId = w.ToLocationId
  JOIN IH#MainWarehouses wh ON wh.LocationId = j.ToLocationId
 UNION ALL
SELECT w.*, NULL AS MainWHLocationId,
       NULL AS MainWHWorkCentreName, NULL AS MainWHWorkCentreCode,
       NULL AS MainWHLocationName, NULL AS MainWHLocationCode
  FROM w
 WHERE w.FromLocationId != w.ToLocationId
top
IH#WorkcentreParameters
WITH wt AS 
(
  SELECT ID, WorkCentreTypeName, WorkCentreTypeDesc, IsProductionSource FROM WorkCentreTypes
),
pm AS 
(
  SELECT MIN(ID) ID FROM wt WHERE wt.WorkCentreTypeName = 'Paper Machine'
)
SELECT w.Id AS WorkcentreId, w.WorkCentreName, w.WorkCentreCode,
       w.WorkcentreTypeId, w.IdleCost,
       wt.WorkCentreTypeName, wt.WorkCentreTypeDesc,
       w.LocationId, l.LocationCode, l.LocationName, 
       l.SiteId, s.SiteName, s.SiteCode,
       ParameterName, ParameterDescription, ParameterHelp,
       NVL(wp.VALUE, DefaultValue) AS Value,
       wpt.DefaultValue,
       wpt.Undefined, wpt.BundleId,
       wpt.UnitDescription, wpt.ParameterGroup, wpt.MinValue, wpt.MaxValue, wpt.DataType,
       wpt.Id
  FROM WorkCentreParameterTypes wpt
 CROSS JOIN pm
  JOIN wt ON DECODE(wt.IsProductionSource, 1, pm.Id, wt.Id) = wpt.WorkcentreTypeId
  JOIN WorkCentres w ON w.WorkCentreTypeId = wt.Id
  JOIN Locations l ON l.Id = w.LocationId
  JOIN Sites s ON s.Id = l.SiteId
  LEFT JOIN WorkCentreParameters wp ON wp.ParameterTypeId = wpt.Id AND wp.WorkcentreId = w.Id
top
IH#Workcentres
SELECT l.LocationName, l.LocationCode, l.HierarchyId,
wc.WorkcentreName, wc.WorkcentreCode, s.SiteCode,
wct.WorkcentreTypeName, wct.WorkcentreTypeDesc,
s.SiteName, wc.Id WorkcentreId, l.Id LocationId, s.Id SiteId, 
WorkcentreTypeId, wc.AutoConfirmationPeriod, wc.NumberOfWorkcentres, wc.IdleCost,
COALESCE(l.CalendarId, dp.DefaultCalendarId) CalendarId,
HasInventory, IsProductionSource, wct.OrderNo, wct.StageDelayHours, wct.MaxStageDelayHours, wc.LineOfAuthority
FROM   Locations l
JOIN  Workcentres wc ON  (wc.LocationId = l.Id)
JOIN  WorkcentreTypes wct ON (wc.WorkcentreTypeId = wct.Id)
LEFT JOIN Sites s ON (l.SiteId = s.Id)
CROSS JOIN Ih#defaultparameters dp
top
IH_ForecastSnapshots
SELECT 'Snapshot' TYPE, fs.ID, fs.NAME, fs.DESCRIPTION, fs.IsBudget, fs.IsShowOnGraph,
fs.StartDate, fs.FinishDate,
Trunc(fs.StartDate, 'IW') StartWeek,
Trunc(Last_Day(fs.FinishDate), 'IW') FinishWeek,
fs.Id OrderCondition,
ufs.Name UnconstrainedName, fs.UnconstrainedSnapshotId, fs.IsConstrained, fs.DEtailId,
SIGN(fs.ErrorsQuantity) Status, fs.NewSkuCreated, d.Description FILTER
FROM ForecastSnapshots fs LEFT JOIN Forecastsnapshots ufs ON (fs.UnconstrainedSnapshotid = ufs.ID)
LEFT JOIN IH#DetailsDescription d ON fs.DetailId = d.Id
UNION ALL
SELECT 'Forecast' TYPE, 0 ID, 'Monthly Forecast', 'Monthly Forecast' Description, 0 IsBudget, 0 IsShowOnGraph,
NULL, NULL, NULL, NULL, -1 OrderCondition, NULL UnconstrainedName, NULL UnconstrainedSnapshotId, 0 IsConstrained, NULL DetailId, 0 Status, 0 NewSkuCreated, '' FILTER
FROM dual
top
IH_Navigations
    SELECT nt.TaskName, dsf.Name, NVL(n.DisplayLabel, dsf.Description) description, dsf.DataType, EntityType, Category,
    NVL(n.FreeEntry, DECODE(INITCAP(dsf.DataType), 'String', 1, 0)) IsFreeEntry,
    n.Mandatory IsMandatory, NVL(n.LevelNo, dsf.OrderNo) LevelNo, OrderByField, NVL(Hidden, 0) Hidden,
    DataSourceName, n.Id NavigationLevelId, dsf.Helper, dsf.HelperColumn, NVL(dsf.Filtered, dsf.DefaultFiltered) Filtered,
    NVL(n.DefaultOperation,
           CASE WHEN nt.FilterType = 'Picker' THEN '='
            ELSE DECODE(INITCAP(dsf.DataType), 'String', 'in', '=')
    END ) DefaultOperation, DefaultValue, nt.IsSystem, n.OperationTypeId, n.MaterialTypeId
    FROM   IH#DataSourceFields dsf
    JOIN   NavigationTasks nt
    ON     (UPPER(dsf.DataSourceName) = UPPER(nt.Source))
    LEFT   JOIN Navigations n
    ON     (UPPER(n.LevelName) = UPPER(dsf.Name) AND n.TaskName = nt.TaskName)
    ORDER  BY UPPER(TaskName), LevelNo

top
IHBS#CorrespondRuns

SELECT distinct r.Id SourceRunId, r2.Id RunId,

       wc.WorkcentreName || ' ' || r.PositionNo || ' ' || r.Properties SourceRunName,
       wc2.WorkcentreName || ' ' || r2.PositionNo || ' ' || r2.Properties RunName
FROM   BSOInputdata d
JOIN   OptimizedRuns r
ON     r.Id = d.SourceRunId
JOIN   OptimizedRunOrders o
ON     o.OrderId = d.Id
JOIN   OptimizedRuns R2
ON     r2.Id = o.RunId
JOIN   Workcentres wc
ON     r.WorkcentreID = wc.Id
JOIN   Workcentres wc2
ON     r2.WorkcentreID = wc2.Id

top
IHBS#GradeProperties
WITH g AS
(
  SELECT * FROM GradeProperties g
  UNPIVOT EXCLUDE NULLS
  (VALUE FOR PROPERTY IN (
                           Code1, Code2, Code3, Code4, Code5, Code6, Code7, Code8, Code9, Code10,
                           Code11, Code12, Code13, Code14, Code15, Code16, Code17, Code18, Code19, Code20,
                           Code21, Code22, Code23, Code24, Code25, Code26, Code27, Code28, Code29, Code30
                          ))
)
SELECT g.GradeCode, g.GradeId, g.Property, p.Id PropertyId, g.VALUE 
  FROM g
  JOIN IH#ModelCharacteristics h
    ON UPPER(h.FieldCode) = Upper(g.Property)
  JOIN PropertiesIPlanView p
    ON UPPER(h.FieldViewCode) = Upper(p.PropertyViewCode)

top
IHBS#HandlingDelay

   SELECT w.Id AS WorkCentreId, NVL(wp.Value, wpt.DefaultValue) / 1440 AS Value
     FROM WorkCentres w
     JOIN WorkCentreParameterTypes wpt ON w.WorkCentreTypeId = wpt.WorkcentreTypeId
     LEFT JOIN WorkCentreParameters wp ON wp.WorkCentreId = w.Id AND wp.ParameterTypeId = wpt.Id
    WHERE wpt.ParameterName = 'HandlingDelay'

top
IHBS#NextAllocationBodies

SELECT ab1.*, ab2.WorkcentreId NextWorkcentreId, DECODE(LiveAllocationPeriod, 'Week', ab1.SourceWeek, ab1.SourceMonth) SourcePeriod,
DECODE(LiveAllocationPeriod, 'Week', ab2.SourceWeek, ab2.SourceMonth) NextSourcePeriod, 1 NextAllocation, 1 NextCoef

FROM Allocationbodies ab1
LEFT JOIN AllocationBodies ab2
ON ab1.Sitematerialusageid = ab2.SiteMaterialUsageId
AND ab1.AllocationId = ab2.AllocationId
AND ab1.SeqNo = ab2.SeqNo + 1
AND NVL(ab1.SourceWeek,to_date('01-01-2000', 'DD-MM-YYYY')) = NVL(ab2.Sourceweek,to_date('01-01-2000', 'DD-MM-YYYY'))
AND NVL(ab1.DeliveryWeek, to_date('01-01-2000', 'DD-MM-YYYY')) = NVL(ab2.DeliveryWeek, to_date('01-01-2000', 'DD-MM-YYYY'))
AND NVL(ab1.SourceMonth,to_date('01-01-2000', 'DD-MM-YYYY')) = NVL(ab2.SourceMonth,to_date('01-01-2000', 'DD-MM-YYYY'))
AND NVL(ab1.DeliveryMonth, to_date('01-01-2000', 'DD-MM-YYYY')) = NVL(ab2.DeliveryMonth, to_date('01-01-2000', 'DD-MM-YYYY'))
CROSS JOIN (SELECt CASE WHEN Value IN ('Week', 'WeekMonth') THEN 'Week' ELSE 'Month' END LiveAllocationPeriod
           FROM SystemParameters WHERE ParameterName = 'LiveAllocationPeriod')
top
IHBS#RunOutputDelay

   SELECT w.Id AS WorkCentreId, NVL(wp.Value, wpt.DefaultValue) AS Value
     FROM WorkCentres w
     JOIN WorkCentreParameterTypes wpt ON w.WorkCentreTypeId = wpt.WorkcentreTypeId
     LEFT JOIN WorkCentreParameters wp ON wp.WorkCentreId = w.Id AND wp.ParameterTypeId = wpt.Id
    WHERE wpt.ParameterName = 'RunOutputDelay'

top
IHDP#ConvertLocations

SELECT t.*, locationName, LocationCode FROM
(
SELECT SiteId, SiteName, SiteCode, MIN(l.Id) ConvertLocationId
FROM   locations l
JOIN Sites s
ON s.Id = l.siteId
WHERE  NOT EXISTS (SELECT 1 FROM workcentres wc WHERE wc.LocationID = l.Id)
AND    SITEID IS NOT NULL
GROUP  BY SiteId, SiteName, SiteCode
) t
JOIN Locations l2
ON l2.Id = t.ConvertLocationId
top
IHDP#ConvertSku
  SELECT smu.Id SkuId, smu.LocationId, smu.MaterialId, smu.endUseId, smu.EndCustomerId, pc.Id, pc.BomId,
         bm.MaterialId SourceMaterialId, p.ConvertLocationid, dsku.Id SourceSkuId, Multiplier, Divider,
				 s2.LocationCode, s2.MaterialCode, s2.EndUseCode, s2.EndCustomerCode, s2.Status,
				 d2.LocationCode DestinationLocationCode, d2.MaterialCode DestinationMaterialCode,
				 d2.EndUseCode DestinationEndUseCode, d2.EndCustomerCode DestinationEndCustomerCode,
				 d2.Status DestinationStatus
  FROM   SiteMaterialUsages smu
  JOIN EV#SiteMaterialUsages s2 ON s2.Id = smu.Id
  JOIN   Productionconfigurations pc
  ON     pc.MaterialId = smu.MaterialId
  JOIN   BoMMaterials bm
  ON     bm.BomId = pc.BomId
  JOIN   (SELECT cl.ConvertLocationId, sp.*
          FROM   SourcePriorities sp
          JOIN   Locations l
          ON     sp.SourcelocationId = l.Id
          JOIN   IHDP#ConvertLocations cl
          ON     cl.SiteId = l.SiteId
          JOIN Workcentres wc on wc.Id = sp.WorkcentreId
          JOIN WorkcentreTypes wct on wct.Id = wc.WorkcentreTypeId
          AND WorkcentreTypeName != 'Warehouse') p
  ON     p.Sitematerialusageid = smu.Id
  AND    p.Priority = 1
  AND    p.ConvertLocationId != smu.LocationId
  LEFT   JOIN SiteMaterialUsages dsku
  ON     dsku.LocationID = p.ConvertLocationId
  AND    dsku.MaterialID = bm.MaterialId
  AND    NVL(dsku.endUseId, 0) = NVL(smu.endUseId, 0)
  AND    NVL(dsku.EndCustomerId, 0) = NVL(smu.EndCustomerId, 0)
  LEFT JOIN EV#SiteMaterialUsages d2 ON d2.Id = dsku.Id
  WHERE  smu.Status = 1

top
IHDP#ConvertSkuEVG

SELECT smu.Id SkuId, smu.LocationId, smu.MaterialId, smu.endUseId, smu.EndCustomerId, pc.Id, pc.BomId,
    bm.MaterialId SourceMaterialId, deu.Id SourceEndUseId, mps.CODE10 ManfPlant, p.ConvertLocationid, dsku.Id SourceSkuId, Multiplier, Divider,
    s2.LocationCode, s2.MaterialCode, s2.EndUseCode, s2.EndCustomerCode, s2.Status,
    p.ConvertLocationCode DestinationLocationCode, dm.MaterialCode DestinationMaterialCode,
    deu.EndUseCode DestinationEndUseCode, ConvertLocationCode DestinationEndCustomerCode,
    d2.Status DestinationStatus
  FROM   SiteMaterialUsages smu
  JOIN EV#SiteMaterialUsages s2 ON s2.Id = smu.Id
  JOIN   Productionconfigurations pc
  ON     pc.MaterialId = smu.MaterialId
  JOIN   BoMMaterials bm
  ON     bm.BomId = pc.BomId
  JOIN   (SELECT cl.ConvertLocationId, cl.LocationCode ConvertLocationCode, sp.*
          FROM   SourcePriorities sp
          JOIN   Locations l
          ON     sp.SourcelocationId = l.Id
          JOIN   IHDP#ConvertLocations cl
          ON     cl.SiteId = l.SiteId
          JOIN Workcentres wc on wc.Id = sp.WorkcentreId
          JOIN WorkcentreTypes wct on wct.Id = wc.WorkcentreTypeId
          AND WorkcentreTypeName != 'Warehouse') p
  ON     p.Sitematerialusageid = smu.Id
  AND    p.Priority = 1
  AND    p.ConvertLocationId != smu.LocationId
  JOIN Materialpropsspec mps
  ON mps.MAterialID = bm.MaterialId
  JOIN EndUses deu ON deu.EndUseCode = 'NA-' || mps.Code10
  JOIN Materials dm ON dm.Id = bm.MaterialId
  JOIN Locations dl ON dl.LocationCode = ConvertLocationCode
  LEFT   JOIN SiteMaterialUsages dsku
  ON     dsku.LocationID = p.ConvertLocationId
  AND    dsku.MaterialID = bm.MaterialId
  AND    NVL(dsku.endUseId, 0) = NVL(deu.Id, 0)
  AND    dsku.EndCustomerId IS NULL
  LEFT JOIN EV#SiteMaterialUsages d2 ON d2.Id = dsku.Id
  WHERE  smu.Status = 1

top
IHDP#ConvertSkuOnSameLocation

  SELECT smu.Id SkuId, smu.LocationId, smu.MaterialId, pc.Id, pc.BomId, bm.MaterialId SourceMaterialId,
         smu.LocationId ConvertLocationid, dsku.Id SourceSkuId, Multiplier, Divider
  FROM   SiteMaterialUsages smu
  JOIN   Productionconfigurations pc
  ON     pc.MaterialId = smu.MaterialId
  JOIN   BoMMaterials bm
  ON     bm.BomId = pc.BomId
  LEFT   JOIN SiteMaterialUsages dsku
  ON     dsku.LocationID = smu.LocationId
  AND    dsku.MaterialID = bm.MaterialId
  WHERE  smu.Status = 1

top
IHDP#DayForSnapshot

WITH DefaultCurrencies AS (SELECT ID FROM Currencies WHERE IsInternal = 1)
SELECT fb.forecastSnapshotId, fb.SiteMaterialUsageId, cs.DateFrom,
       SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum)) FINAL,
       DECODE(SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum)), 0, AVG(SystemPrice),
              SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum) * SystemPrice) /
              SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum))) SystemPrice,
       DECODE(SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum)), 0, AVG(ForecastedPrice),
              SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum) * ForecastedPrice) /
              SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum))) ForecastedPrice,
       NVL(AVG(ep.Price),0) Price,
       NVL(MIN((1 / (er.Multiplier / er.Divider)) * er2.Multiplier / er2.Divider),1) PriceCoef
  FROM ForecastSnapshotBodies fb
 CROSS JOIN DefaultCurrencies c
  JOIN ForecastWeeklyCoefs fc
    ON fb.DateFrom = fc.DateFrom 
   AND fb.FinalWeeklyCoefId = fc.Id
  JOIN CalendarSources CS
    ON cs.Calendarid = fc.CalendarId
   AND cs.DateFromIw = fc.DateFromIw
   AND cs.DateFromMonth = fc.DateFrom
  LEFT JOIN IH#ExpandedPrices ep
    ON ep.SiteMaterialUsageId = fb.SiteMaterialUsageId 
   AND cs.DateFrom BETWEEN ep.DateFrom AND ep.DateTo
  LEFT JOIN ExpandedExchangeRates er
    ON er.CurrencyId = ep.CurrencyId
   AND fb.DateFrom BETWEEN er.DateFrom AND er.DateTo
  LEFT JOIN ExpandedExchangeRates er2
    ON fb.DateFrom BETWEEN er2.DateFrom AND er2.DateTo
   AND er2.CurrencyId = c.Id
 GROUP BY fb.ForecastSnapshotId, fb.SiteMaterialUsageId, cs.DateFrom
ORDER  BY 1, 2

top
IHDP#DaySystemForecast

WITH DefaultCurrencies AS
 (SELECT ID FROM Currencies WHERE IsInternal = 1)
SELECT fb.SiteMaterialUsageId, cs.DateFrom, SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum)) FINAL,

       DECODE(SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum)), 0, AVG(SystemPrice),
               SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum) * SystemPrice) /
                SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum))) SystemPrice,
       DECODE(SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum)), 0, AVG(ForecastedPrice),
               SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum) * ForecastedPrice) /
                SUM(DECODE(WeekSum, 0, 0, FINAL * fc.Coef * IsWorkingDay / WeekSum))) ForecastedPrice,
       NVL(AVG(ep.Price),0) Price,
       NVL(MIN((1 / (er.Multiplier / er.Divider)) * er2.Multiplier / er2.Divider),1) PriceCoef

FROM   ForecastBodies fb
CROSS  JOIN DefaultCurrencies c
JOIN   ForecastWeeklyCoefs fc
ON     (fb.DateFrom = fc.DateFrom AND fb.FinalWeeklyCoefId = fc.Id)
JOIN   CalendarSources CS
ON     cs.Calendarid = fc.CalendarId
AND    cs.DateFromIw = fc.DateFromIw
AND    cs.DateFromMonth = fc.DateFrom
LEFT   JOIN IH#ExpandedPrices ep
ON     (ep.SiteMaterialUsageId = fb.SiteMaterialUsageId AND cs.DateFrom BETWEEN ep.DateFrom AND ep.DateTo)
LEFT   JOIN ExpandedExchangeRates er
ON     er.CurrencyId = ep.CurrencyId
AND    fb.DateFrom BETWEEN er.DateFrom AND er.DateTo
LEFT   JOIN ExpandedExchangeRates er2
ON     fb.DateFrom BETWEEN er2.DateFrom AND er2.DateTo
AND    er2.CurrencyId = c.Id
GROUP  BY fb.SiteMaterialUsageId, cs.DateFrom
ORDER  BY 1, 2

top
IHDP#ForecastAccuracy
WITH b AS
 (SELECT b.Name, Key, VALUE FROM Bundles b JOIN BundleValues bv ON bv.BundleId = b.Id)
             SELECT t.SiteMaterialUsageId, DateFrom,
                    SUM(OriginalSystem) OriginalSystem, SUM(SYSTEM) System,
                    SUM(Customer) Customer, SUM(FINAL) FINAL,
                    SUM(Upper) Upper, SUM(Lower) Lower,
                    SUM(UnadjustedHistory) UnadjustedHistory,
                    SUM(History) History,
                    SUM(SupersededHistory) SupersededHistory,
                    SUM(AllSupersededHistory) AllSupersededHistory,
                    SUM(mtdSupersededHistory) mtdHistory,
                    SUM(Budget) Budget,
                    SUM(Orders) Orders,
                    SUM(case when ms.SiteMaterialUsageId IS NULL THEN NVL(OrdersIncludeSupercessions,0) + NVL(Orders,0) ELSE 0 END) OrdersIncludeSupercessions,
                    SUM(mtdOrders) mtdOrders, SUM(Allocation) Allocation,
                    SUM(DECODE(SIGN(dateFrom - f.startDate), -1, history, FINAL)) FinalOrActual,
                    SUM(DECODE(SIGN(dateFrom - f.startDate), -1, supersededHistory, FINAL)) FinalOrSupersededActual,
                    MAX(ForecastMethodName) ForecastMethod, MAX(GroupedForecastMethodName) GroupedForecastMethod,
                    MAX(MonthsOut) MonthsOut, SUM(FittedHistory) FittedHistory, MAX(Seasonality) Seasonality,
                    MAX(Trend) Trend, MAX(GroupedSeasonality) GroupedSeasonality, MAX(GroupedTrend) GroupedTrend
             FROM   (
                      SELECT fb.SiteMaterialUsageId, fb.DateFrom,
                             Months_Between(fb.Datefrom, f.Startdate) MonthsOut,  fb.OriginalSystem, fb.SYSTEM, fb.Customer,
                             fb.FINAL, fb.lower, fb.Upper, NULL UnadjustedHistory, NULL History, NULL mtdHistory,
                             NULL SupersededHistory, NULL AllSupersededHistory, NULL mtdSupersededHistory, NULL FittedHistory,  NULL Budget,
                             NULL Orders, NULL OrdersIncludeSupercessions, NULL mtdOrders, NULL Allocation, fm.ForecastMethodName,
                             fmg.ForecastMethodName GroupedForecastMethodName,
                             s.Value Seasonality, t.Value Trend, gs.Value GroupedSeasonality, gt.Value GroupedTrend
                      FROM   ForecastBodies fb
                      JOIN   Forecasts f
                      ON     fb.ForecastId = f.Id
                      LEFT   JOIN ForecastStatistics fs
                      ON     fb.Forecastid = fs.ForecastId
                      AND    fb.SiteMaterialUsageID = fs.SiteMaterialUsageId
                      LEFT   JOIN ForecastMethods fm
                      ON     fs.ForecastMethodId = fm.Id
                      LEFT   JOIN ForecastMethods fmg
                      ON     fs.GroupedForecastMethodId = fmg.Id
                      LEFT   JOIN b s
                      ON     s.Name = 'ForecastSeasonal'
                      AND    s.Key = to_char(fs.Seasonality)
                      LEFT   JOIN b t
                      ON     t.Name = 'ForecastTrend'
                      AND    t.Key = to_char(fs.Trend)
                      LEFT   JOIN b gs
                      ON     gs.Name = 'ForecastSeasonal'
                      AND    gs.Key = to_char(fs.GroupedSeasonality)
                      LEFT   JOIN b gt
                      ON     gt.Name = 'ForecastTrend'
                      AND    gt.Key = to_char(fs.GroupedTrend)
                      UNION ALL
                      SELECT SiteMaterialUsageId, DateFrom,
                             NULL MonthsOut, NULL OriginalSystem, NULL System, NULL Customer,
                             NULL Final, NULL Lower, NULL Upper, Weight UnadjustedHistory, AdjustedHistoryWeight History, mtdHistory,
                             NULL SupersededHistory, NULL AllSupersededHistory, NULL mtdSupersededHistory, NULL FittedHistory, NULL Budget,
                             NULL Orders, NULL OrdersIncludeSupercessions, NULL mtdOrders, NULL Allocation, NULL ForecastMethodName,
                             NULL GroupedForecastMethodName, NULL Seasonality, NULL Trend, NULL GroupedSeasonality, NULL GroupedTrend
                      FROM   IH#MonthlyUsageHistories
                      UNION ALL
                      SELECT SiteMaterialUsageId, DateFrom,
                             NULL MonthsOut, NULL OriginalSystem, NULL System, NULL Customer,
                             NULL Final, NULL Lower, NULL Upper, NULL UnadjustedHistory, NULL History, NULL mtdHistory,
                             AdjustedSupersededHistory SupersededHistory,  NULL AllSupersededHistory, mtdSupersededHistory,
                             NULL FittedHistory, NULL Budget,
                             NULL Orders, NULL OrdersIncludeSupercessions, NULL mtdOrders, NULL Allocation, NULL ForecastMethodName,
                             NULL GroupedForecastMethodName, NULL Seasonality, NULL Trend, NULL GroupedSeasonality, NULL GroupedTrend
                      FROM   IH#MonthlySupersededHistory
                      UNION ALL
                      SELECT SiteMaterialUsageId, DateFrom,
                             NULL MonthsOut, NULL OriginalSystem, NULL System, NULL Customer,
                             NULL Final, NULL Lower, NULL Upper, NULL UnadjustedHistory, NULL History, NULL mtdHistory,
                             NULL SupersededHistory,  AllSupersededHistory AllSupersededHistory, NULL mtdSupersededHistory,
                             NULL FittedHistory, NULL Budget,
                             NULL Orders, NULL OrdersIncludeSupercessions, NULL mtdOrders, NULL Allocation, NULL ForecastMethodName,
                             NULL GroupedForecastMethodName, NULL Seasonality, NULL Trend, NULL GroupedSeasonality, NULL GroupedTrend
                      FROM   IH#MonthlyAllSupersededHistory
                      UNION ALL
                      SELECT SiteMaterialUsageId, DateFrom, NULL, NULL, NULL,
                             NULL, NULL, NULL, NULL, NULL, NULL,
                             NULL, NULL, NULL, NULL,
                             NULL, FINAL Budget,
                             NULL Orders,  NULL OrdersIncludeSupercessions, NULL, NULL,
                             NULL, NULL, NULL, NULL, NULL, NULL
                      FROM   IH#ForecastBudgets
                      UNION ALL
                      SELECT SiteMaterialUsageId, TRUNC(DeliveryDate, 'month'), NULL,
                              NULL, NULL, NULL, NULL, NULL, NULL, NULL,
                              NULL, NULL, NULL, NULL, NULL, NULL,
                              NULL,
                              SUM(FinalWeight) Orders,  NULL OrdersIncludeSupercessions,
                              SUM(DECODE(SIGN(DeliveryDate - i.internalDate), -1, finalWeight, 0)) mtdOrders,
                              NULL, NULL, NULL, NULL, NULL, NULL, NULL
                      FROM   OrderLines ol, (SELECT TRUNC(core.getInternalDate) internalDate FROM DUAL) i, OrderLineStatuses ols
                      WHERE ols.Id = ol.OrderLineStatusId
                        AND OrderLineStatusCode IN ('Firm', 'Completed')
                      GROUP  BY SiteMaterialUsageId, TRUNC(DeliveryDate, 'month')
                      UNION ALL
                      SELECT ms.OnSiteMaterialUsageId, TRUNC(DeliveryDate, 'month'), NULL,
                              NULL, NULL, NULL, NULL, NULL, NULL, NULL,
                              NULL, NULL, NULL, NULL, NULL, NULL,
                              NULL,
                              NULL Orders, SUM(FinalWeight) OrdersIncludeSupercessions,
                              NULL mtdOrders,
                              NULL, NULL, NULL, NULL, NULL, NULL, NULL
                      FROM   OrderLines ol, OrderLineStatuses ols,
                          IH#MaterialSupercessions ms
                      WHERE ols.Id = ol.OrderLineStatusId
                        AND OrderLineStatusCode IN ('Firm', 'Completed')
                        AND ol.SiteMaterialUsageId = ms.SiteMaterialUsageId
                      GROUP  BY ms.OnSiteMaterialUsageId, TRUNC(DeliveryDate, 'month')
                      UNION ALL
                      SELECT SiteMaterialUsageId, DeliveryMonth, NULL, NULL, NULL,
                             NULL, NULL, NULL, NULL,
                             NULL, NULL, NULL, NULL, NULL, NULL, NULL,
                             NULL, NULL, NULL OrdersIncludeSupercessions, NULL mtdOrders, SUM(Customer) Allocation,
                             NULL, NULL, NULL, NULL, NULL, NULL
                      FROM   AllocationBodies
                      GROUP  BY SiteMaterialUsageId, DeliveryMonth
                      UNION ALL
                      SELECT SiteMaterialUsageId, TRUNC(DateFrom, 'month'), NULL,
                             NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
                             NULL, NULL, NULL, NULL, SUM(Weight) FittedHistory,
                             NULL Budget, NULL Orders, NULL OrdersIncludeSupercessions, NULL, NULL,
                             NULL, NULL, NULL, NULL, NULL, NULL
                      FROM   FittedHistories
                      GROUP  BY SiteMaterialUsageId, TRUNC(DateFrom, 'month')
                      ) t
             CROSS  JOIN (SELECT NVL(MAX(startDate), SYSDATE + 1000000) startDate FROM Forecasts) f
             LEFT JOIN (SELECT DISTINCT SiteMaterialUsageId FROM IH#MaterialSupercessions) ms on ms.SiteMaterialUsageId = t.SiteMaterialUsageId
             GROUP  BY t.SiteMaterialUsageId, t.DateFrom

top
IHDP#ForecastChangeDetails

  WITH a AS
  (SELECT NAME AS FieldName
                  FROM   IH#Datasourcefields
                  WHERE  UPPER(DataSourceName) = UPPER('IF$ForecastCollaboration')
                  AND    filtered = 1)
SELECT v.ForecastChangeId, v.FieldName, fc.VALUE
FROM   (SELECT ID ForecastChangeId, FieldName FROM ForecastChanges CROSS JOIN a) v
LEFT   JOIN ForecastChangeDetails fc
ON     (fc.FieldName = v.FieldName AND fc.ForecastChangeId = v.ForecastChangeId)
top
IHDP#ForecastMethodsSku

WITH sku AS
 (SELECT s.Column_Value SiteMaterialUsageId, fmr.*, ROW_NUMBER() OVER(PARTITION BY s.Column_Value ORDER BY RuleWeighting DESC) r
  FROM   ForecastMethodRules fmr
  JOIN   Hierarchypropertydetails d
  ON     d.Id = fmr.DetailId
  CROSS  JOIN TABLE(core.getDetails(MyIdentityArray(d.Id), 'Sku')) s)
SELECT * FROM sku
WHERE r = 1
top
IHDP#HistoryAndOrdersPrices

SELECT uh.SiteMaterialUsageId, smu.MaterialId, Datefrom, Weight,
DECODE(IsHistory, 1, Weight, 0) HistoryWeight,
DECODE(IsHistory, 0, Weight, 0) OrdersWeight,
NVL(uh.PriceQuantityUnitId, p.BaseWeightUnitId) PriceQuantityUnitId,
NVL(uh.CurrencyId, p.InternalCurrencyId) CurrencyId,
Price, UnitName, CurrencyName,
LAST_Value(NVL(uh.CurrencyId, p.InternalCurrencyId))
   OVER (PARTITION BY SiteMaterialUsageId
         ORDER BY DateFrom
         RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) TargetCurrencyId,
CASE WHEN DateFrom = LAST_VALUE(DateFrom)  OVER (PARTITION BY SiteMaterialUsageId
         ORDER BY DateFrom
         RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) THEN 1 ELSE 0 END IsLastKnownPeriod,
   IsHistory
FROM (
	SELECT SiteMaterialUsageId, DateFrom,  NVL(AdjustedWeight, Weight) Weight, Price, PriceQuantityUnitId, CurrencyId, 1 IsHistory
	FROM Usagehistories
	WHERE Price IS NOT NULL
	AND NVL(AdjustedWeight, Weight) > 0
	UNION ALL
	SELECT SiteMaterialUsageId, DeliveryDate DateFrom, FinalWeight Weight, Price, UnitId, CurrencyId, 0 IsHistory
	FROM OrderLines ol
	JOIN OrderLineStatuses ols ON ols.Id = ol.OrderLineStatusId
	WHERE NOT EXISTS (SELECT 1 FROM Workcentres wc WHERE wc.LocationId = ol.WorkcentreId)
	AND Price IS NOT NULL
	AND FinalWeight > 0
	AND OrderLineStatusCode IN ('Firm', 'Completed')
	) uh
CROSS JOIN Ih#defaultparameters p
JOIN SiteMaterialUsages smu
ON smu.Id = uh.SiteMaterialUsageId
JOIN Currencies c
ON c.Id = NVL(uh.CurrencyId, p.InternalCurrencyId)
JOIN Units u
ON u.Id = NVL(uh.PriceQuantityUnitId, p.BaseWeightUnitId)
top
IHDP#MonthForSnapshot Monthly forecast snapshot used as SNP input Look to procedure populateSNPForecast

WITH DefaultCurrencies AS
 (SELECT ID FROM Currencies WHERE IsInternal = 1)
SELECT fb.ForecastSnapshotId, fb.SiteMaterialUsageId, fb.DateFrom, FINAL, SystemPrice, ForecastedPrice,
       NVL(ep.Price, 0) Price,
       NVL((1 / (er.Multiplier / er.Divider)) * er2.Multiplier / er2.Divider, 1) PriceCoef
FROM   ForecastSnapshotBodies fb
CROSS  JOIN DefaultCurrencies c
LEFT   JOIN IH#ExpandedPrices ep
ON     (ep.SiteMaterialUsageId = fb.SiteMaterialUsageId AND fb.DateFrom BETWEEN ep.DateFrom AND ep.DateTo)
LEFT   JOIN ExpandedExchangeRates er
ON     er.CurrencyId = ep.CurrencyId
AND    fb.DateFrom BETWEEN er.DateFrom AND er.DateTo
LEFT   JOIN ExpandedExchangeRates er2
ON     fb.DateFrom BETWEEN er2.DateFrom AND er2.DateTo
AND    er2.CurrencyId = c.Id
top
IHDP#MonthSystemForecast System monthly forecast used as SNP input

WITH DefaultCurrencies AS
 (SELECT ID FROM Currencies WHERE IsInternal = 1)
SELECT fb.SiteMaterialUsageId, fb.DateFrom, FINAL, SystemPrice, ForecastedPrice,
       NVL(ep.Price, 0) Price,
       NVL((1 / (er.Multiplier / er.Divider)) * er2.Multiplier / er2.Divider, 1) PriceCoef
FROM   ForecastBodies fb
CROSS  JOIN DefaultCurrencies c
LEFT   JOIN IH#ExpandedPrices ep
ON     (ep.SiteMaterialUsageId = fb.SiteMaterialUsageId AND fb.DateFrom BETWEEN ep.DateFrom AND ep.DateTo)
LEFT   JOIN ExpandedExchangeRates er
ON     er.CurrencyId = ep.CurrencyId
AND    fb.DateFrom BETWEEN er.DateFrom AND er.DateTo
LEFT   JOIN ExpandedExchangeRates er2
ON     fb.DateFrom BETWEEN er2.DateFrom AND er2.DateTo
AND    er2.CurrencyId = c.Id
top
IHDP#OrderLinePrices

SELECT ol.SiteMaterialUsageId, ol.MaterialId, DeliveryDate, FinalWeight FinalWeight,
u.Id PriceQuantityUnitId,
NVL(ol.CurrencyId, p.InternalCurrencyId) CurrencyId,
Price, UnitName, CurrencyName,
LAST_Value(NVL(ol.CurrencyId, p.InternalCurrencyId))
   OVER (PARTITION BY SiteMaterialUsageId
         ORDER BY DeliveryDate
         RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) TargetCurrencyId,
CASE WHEN DeliveryDate = LAST_VALUE(DeliveryDate)  OVER (PARTITION BY SiteMaterialUsageId
         ORDER BY DeliveryDate
         RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) THEN 1 ELSE 0 END IsLastKnownPeriod
FROM OrderLines ol
CROSS JOIN Ih#defaultparameters p
JOIN SiteMaterialUsages smu
ON smu.Id = ol.SiteMaterialUsageId
JOIN Currencies c
ON c.Id = NVL(ol.CurrencyId, p.InternalCurrencyId)
JOIN Units u
ON u.Id = p.BaseWeightUnitId
JOIN OrderLineStatuses ols ON ols.Id = ol.OrderLineStatusId
WHERE Price IS NOT NULL
AND FinalWeight > 0
AND NOT EXISTS (SELECT 1 FROM Workcentres wc WHERE wc.LocationId = smu.LocationId)
AND OrderLineStatusCode IN ('Firm', 'Completed')

top
IHDP#OrderWorkingDays
WITH d AS
 (SELECT TRUNC(CORE.getInternalDate, 'month') CurrentMonth, TRUNC(CORE.getInternalDate) CurrentDate,
  Value MethodName
  FROM SystemParameters
  WHERE ParameterName='OrdersVsFinal'),
skumethod AS
 (SELECT SiteMaterialUsageId, d.CurrentDate, d.CurrentMonth,
         LEAST(GREATEST(MAX(DeliveryDate), d.CurrentDate - 1), LAST_DAY(d.CurrentMonth)) MaxDeliveryDate
  FROM   OrderLines ol
  JOIN   OrderLineStatuses ols
  ON     ols.Id = ol.OrderLineStatusId
  CROSS  JOIN d
  WHERE  TRUNC(DeliveryDate, 'month') >= d.CurrentMonth
  AND    OrderLineStatusCode IN ('Completed', 'Firm')
  GROUP  BY SiteMaterialUsageId, d.CurrentDate, d.CurrentMonth),
locmethod AS
 (SELECT LocationId, d.CurrentDate, d.CurrentMonth,
         LEAST(GREATEST(MAX(DeliveryDate), d.CurrentDate - 1), LAST_DAY(d.CurrentMonth)) MaxDeliveryDate
  FROM   OrderLines ol
  JOIN   OrderLineStatuses ols
  ON     ols.Id = ol.OrderLineStatusId
  CROSS  JOIN d
  WHERE  TRUNC(DeliveryDate, 'month') >= d.CurrentMonth
  AND    OrderLineStatusCode IN ('Completed', 'Firm')
  GROUP  BY LocationId, d.CurrentDate, d.CurrentMonth),
CalSources AS
 (SELECT CalendarId, DateFrom, IsWorkingDay,
         SUM(IsWorkingday) OVER(PARTITION BY CalendarId ORDER BY DateFrom) WorkingDays,
         SUM(IsWorkingDay) OVER(PARTITION BY CalendarId) TotalWorkingDays
  FROM   CalendarSources s
  JOIN   d
  ON     s.DATEFROMMONTH = d.CurrentMonth)
SELECT s.SiteMaterialUsageId, d.CurrentMonth,
       NVL(s1.Workingdays, GREATEST(0, s2.WorkingDays - 1)) OrdersWorkingDays,
       s2.WorkingDays WorkingDays,
       s2.Totalworkingdays
FROM   IH#CustomerSkuCalendars s
CROSS  JOIN d
JOIN   CalSources s2
ON     s2.CalendarId = s.CalendarId
AND    s2.DateFrom = d.CurrentDate
LEFT   JOIN skumethod
ON     skumethod.SiteMaterialUsageId = s.SiteMaterialUsageId
LEFT   JOIN locmethod
ON     locmethod.LocationId = s.LocationId
LEFT JOIN   CalSources s1
ON     s1.CalendarId = s.CalendarId
AND    s1.DateFrom = DECODE(d.MethodName, 'Sku', skumethod.MaxDeliveryDate, locmethod.MaxDeliveryDate)

top
IHDP#QuarterForSnapshot

WITH DefaultCurrencies AS (SELECT ID FROM Currencies WHERE IsInternal = 1)
SELECT fb.forecastSnapshotId, fb.SiteMaterialUsageId, TRUNC(fb.DateFrom, 'Q') DateFrom,
       SUM(FINAL) FINAL,
       DECODE(SUM(FINAL), 0, AVG(SystemPrice), SUM(FINAL * SystemPrice) / SUM(FINAL)) SystemPrice,
       DECODE(SUM(FINAL), 0, AVG(ForecastedPrice), SUM(FINAL * ForecastedPrice) / SUM(FINAL)) ForecastedPrice,
       NVL(AVG(ep.Price),0) Price,
       NVL(MIN((1 / (er.Multiplier / er.Divider)) * er2.Multiplier / er2.Divider),1) PriceCoef
  FROM ForecastSnapshotBodies fb
 CROSS JOIN DefaultCurrencies c
  LEFT JOIN IH#ExpandedPrices ep
    ON ep.SiteMaterialUsageId = fb.SiteMaterialUsageId 
   AND fb.DateFrom BETWEEN ep.DateFrom AND ep.DateTo
  LEFT JOIN ExpandedExchangeRates er
    ON er.CurrencyId = ep.CurrencyId
   AND fb.DateFrom BETWEEN er.DateFrom AND er.DateTo
  LEFT JOIN ExpandedExchangeRates er2
    ON fb.DateFrom BETWEEN er2.DateFrom AND er2.DateTo
   AND er2.CurrencyId = c.Id
 GROUP BY fb.forecastSnapshotId, fb.SiteMaterialUsageId, TRUNC(fb.DateFrom, 'Q')
 ORDER BY 1, 2

top
IHDP#QuarterSystemForecast
WITH DefaultCurrencies AS
 (SELECT ID FROM Currencies WHERE IsInternal = 1)
SELECT fb.SiteMaterialUsageId, TRUNC(fb.DateFrom, 'Q') DateFrom, SUM(FINAL) FINAL,
       DECODE(SUM(FINAL), 0, AVG(SystemPrice), SUM(FINAL * SystemPrice) / SUM(FINAL)) SystemPrice,
       DECODE(SUM(FINAL), 0, AVG(ForecastedPrice), SUM(FINAL * ForecastedPrice) / SUM(FINAL)) ForecastedPrice,
       NVL(AVG(ep.Price),0) Price,
       NVL(MIN((1 / (er.Multiplier / er.Divider)) * er2.Multiplier / er2.Divider), 1) PriceCoef
FROM   ForecastBodies fb
CROSS  JOIN DefaultCurrencies c
LEFT   JOIN IH#ExpandedPrices ep
ON     (ep.SiteMaterialUsageId = fb.SiteMaterialUsageId AND fb.DateFrom BETWEEN ep.DateFrom AND ep.DateTo)
LEFT   JOIN ExpandedExchangeRates er
ON     er.CurrencyId = ep.CurrencyId
AND    fb.DateFrom BETWEEN er.DateFrom AND er.DateTo
LEFT   JOIN ExpandedExchangeRates er2
ON     fb.DateFrom BETWEEN er2.DateFrom AND er2.DateTo
AND    er2.CurrencyId = c.Id
GROUP  BY fb.SiteMaterialUsageId, TRUNC(fb.DateFrom, 'Q')
ORDER  BY 1, 2

top
IHDP#SourcingDates

WITH SourceData AS
(
SELECT SiteMaterialUSageId, MaterialCode, DateFrom StartDate, NVL(DateTo, to_date('01-01-2050', 'DD-MM-YYYY')) FinishDate, TRUNC(core.getInternalDate) CurrentDate
           FROM   SourcePriorities sp JOIN Materials m ON m.Id = sp.DestinationMaterialId
           WHERE  Priority = 1
           AND    NOT EXISTS (SELECT 1 FROM Workcentres wc WHERE wc.LocationId = sp.DestinationLocationId)
           AND    NOT EXISTS (SELECT 1
                   FROM   Ih#workcentres w
                   WHERE  WorkcentreTypeName IN ('Virtual Paper Machine', 'Virtual Warehouse')
                   AND    w.WorkcentreId = sp.WorkcentreId)
),
grp_starts AS /* remove gaps */
 (SELECT SiteMaterialUSageId, MaterialCode, StartDate, FinishDate, CurrentDate, MAX(FinishDate + 1) over(PARTITION BY SiteMaterialUSageId ORDER BY StartDate,
                       FinishDate rows BETWEEN unbounded preceding AND 1 preceding) mm,
         CASE

             WHEN StartDate > MAX(FinishDate + 1) over(PARTITION BY SiteMaterialUSageId ORDER BY StartDate,
                  FinishDate rows BETWEEN unbounded preceding AND 1 preceding)
									AND LAG(StartDate, 1) over(PARTITION BY SiteMaterialUSageId ORDER BY StartDate, FinishDate) > CurrentDate
                 THEN
              0

             WHEN StartDate > MAX(FinishDate + 1) over(PARTITION BY SiteMaterialUSageId ORDER BY StartDate,
                       FinishDate rows BETWEEN unbounded preceding AND 1 preceding) THEN
              1
             ELSE
              0
         END grp_start,

				  LAG(StartDate, 1) over(PARTITION BY SiteMaterialUSageId ORDER BY StartDate,
                       FinishDate) PrevStartDate


  FROM sourceData)
/*SELECT * FROM grp_starts*/
,
grps AS /* get group numbers */
 (SELECT SiteMaterialUSageId, MaterialCode, StartDate, FinishDate, CurrentDate,
         SUM(grp_start) over(PARTITION BY SiteMaterialUsageId ORDER BY StartDate, FinishDate) grp
  FROM   grp_starts)
/*SELECT * FROM grps*/
,
periods AS /* select range attributes */
(
SELECT SiteMaterialUSageId, MaterialCode, grp,
       MIN(StartDate) over(PARTITION BY SiteMaterialUSageId, grp) StartDate,
       MAX(FinishDate) over(PARTITION BY SiteMaterialUSageId, grp) FinishDate,
       MAX(FinishDate) over(PARTITION BY SiteMaterialUSageId, grp) - MIN(StartDate) over(PARTITION BY SiteMaterialUSageId, grp) lengthPeriod,
			 CASE WHEN MIN(StartDate) over(PARTITION BY SiteMaterialUSageId, grp) > CurrentDate THEN 1 ELSE 0 END IsFuturePeriod,
			 CASE WHEN CurrentDate BETWEEN MIN(StartDate) over(PARTITION BY SiteMaterialUSageId, grp)
				    AND MAX(FinishDate) over(PARTITION BY SiteMaterialUSageId, grp) THEN 1 ELSE 0 END IsLivePeriod
FROM grps
)
/*select p.* from Periods p*/
SELECT SiteMaterialUSageId, MaterialCode, StartDate SourcingStartDate, NULLIF(FinishDate, to_date('01-01-2050', 'DD-MM-YYYY')) SourcingEndDate, rr, isFuturePeriod, isLivePeriod
 FROM
 (
SELECT SiteMaterialUSageId, MaterialCode, grp, StartDate, FinishDate, lengthPeriod, isFuturePeriod, isLivePeriod,
                row_number() OVER(PARTITION BY SiteMaterialUSageId ORDER BY isFuturePeriod, lengthPeriod DESC) rr
                 FROM periods
  ) t
WHERE rr = 1

top
IHDP#UsageHistoryPrices

SELECT uh.SiteMaterialUsageId, smu.MaterialId, Datefrom, NVL(AdjustedWeight, Weight) HistoryWeight,
NVL(uh.PriceQuantityUnitId, p.BaseWeightUnitId) PriceQuantityUnitId,
NVL(uh.CurrencyId, p.InternalCurrencyId) CurrencyId,
Price, UnitName, CurrencyName,
LAST_Value(NVL(uh.CurrencyId, p.InternalCurrencyId))
   OVER (PARTITION BY SiteMaterialUsageId
	       ORDER BY DateFrom
         RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) TargetCurrencyId,
CASE WHEN DateFrom = LAST_VALUE(DateFrom)  OVER (PARTITION BY SiteMaterialUsageId
	       ORDER BY DateFrom
         RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) THEN 1 ELSE 0 END IsLastKnownPeriod
FROM UsageHistories uh
CROSS JOIN Ih#defaultparameters p
JOIN SiteMaterialUsages smu
ON smu.Id = uh.SiteMaterialUsageId
JOIN Currencies c
ON c.Id = NVL(uh.CurrencyId, p.InternalCurrencyId)
JOIN Units u
ON u.Id = NVL(uh.PriceQuantityUnitId, p.BaseWeightUnitId)
WHERE Price IS NOT NULL
AND NVL(AdjustedWeight, Weight) > 0
top
IHDP#WeekForSnapshot Weekly forecast snapshot used as SNP input

WITH DefaultCurrencies AS (SELECT ID FROM Currencies WHERE IsInternal = 1)
SELECT fb.ForecastSnapshotId, fb.SiteMaterialUsageId, fc.DateFromIW DateFrom, 
       SUM(FINAL * fc.Coef) FINAL,
       DECODE(SUM(FINAL * fc.Coef), 0, AVG(SystemPrice), SUM(FINAL * fc.Coef * SystemPrice) / SUM(FINAL * fc.Coef)) SystemPrice,
       DECODE(SUM(FINAL * fc.Coef), 0, AVG(ForecastedPrice),
              SUM(FINAL * fc.Coef * ForecastedPrice) / SUM(FINAL * fc.Coef)) ForecastedPrice,
       NVL(AVG(ep.Price),0) Price,
       NVL(MIN((1 / (er.Multiplier / er.Divider)) * er2.Multiplier / er2.Divider),1) PriceCoef
  FROM ForecastSnapshotBodies fb
 CROSS JOIN DefaultCurrencies c
  JOIN ForecastWeeklyCoefs fc
    ON fc.Id = fb.FinalWeeklyCoefId AND fb.DateFrom = fc.DateFrom
  LEFT JOIN IH#ExpandedPrices ep
    ON (ep.SiteMaterialUsageId = fb.SiteMaterialUsageId AND fc.DateFromIW BETWEEN ep.DateFrom AND ep.DateTo)
  LEFT JOIN ExpandedExchangeRates er
    ON er.CurrencyId = ep.CurrencyId
   AND fb.DateFrom BETWEEN er.DateFrom AND er.DateTo
  LEFT JOIN ExpandedExchangeRates er2
    ON fb.DateFrom BETWEEN er2.DateFrom AND er2.DateTo
   AND er2.CurrencyId = c.Id
 GROUP BY fb.ForecastSnapshotId, fb.SiteMaterialUsageId, DateFromIW
 ORDER BY 1,2,3

top
IHDP#WeeklyForecastBodies
WITH c AS (SELECT wc.Id, wc.DateFromIW, wc.DateFrom, wc.Coef
FROM ForecastWeeklyCoefs wc
)
SELECT
fb.SiteMaterialUsageID, fc.DateFromIW,
system * sc.Coef System,
Customer * cc.Coef Customer,
FINAL * fc.Coef Final,
fb.ForecastStatusId,
IsWorking
FROM ForecastBodies fb, c fc, c sc, c cc
WHERE fc.Id = fb.FinalWeeklyCoefid
AND fb.DateFrom = fc.DateFrom
AND cc.Id = fb.CustomerWeeklyCoefid
AND fb.DateFrom = cc.DateFrom
AND sc.Id = fb.SystemWeeklyCoefid
AND fb.DateFrom = sc.DateFrom
AND sc.DateFromIW = fc.DateFromIW
AND cc.DateFromIw = fc.DatefromIw
AND sc.Datefrom = fc.DateFrom
AND cc.Datefrom = fc.DateFrom
top
IHDP#WeeklyForecastBudgets
SELECT
fb.SiteMaterialUsageID, fc.DateFromIW,
SUM(FINAL * fc.Coef) Final
FROM IH#ForecastBudgets fb, ForecastWeeklyCoefs fc
WHERE fc.Id = fb.FinalWeeklyCoefid
AND fb.DateFrom = fc.DateFrom
group by fb.ForecastSnapshotId, fb.SiteMaterialUsageID, fc.DateFromIW
top
IHDP#WeeklyForecastSnapshots
SELECT fb.ForecastSnapshotId,
fb.SiteMaterialUsageID, fc.DateFromIW,
SUM(FINAL * fc.Coef) Final
FROM ForecastSnapshotBodies fb, ForecastWeeklyCoefs fc
WHERE fc.Id = fb.FinalWeeklyCoefid
AND fb.DateFrom = fc.DateFrom
group by fb.ForecastSnapshotId, fb.SiteMaterialUsageID, fc.DateFromIW
top
IHDP#WeekMonth2ForSnapshot
SELECT * FROM IHDP#WeekMonthForSnapshot
top
IHDP#WeekMonth2SystemForecast
SELECT * FROM IHDP#WeekMonthSystemForecast
top
IHDP#WeekMonthForSnapshot

WITH DefaultCurrencies AS (SELECT ID FROM Currencies WHERE IsInternal = 1)
SELECT fb.ForecastSnapshotId, fb.SiteMaterialUsageId, 
       CASE WHEN fc.DateFromIW > fc.DateFrom THEN fc.DateFromIW ELSE fc.DateFrom END DateFrom,
			 SUM(FINAL * fc.Coef) FINAL,
       DECODE(SUM(FINAL * fc.Coef), 0, AVG(SystemPrice),
              SUM(FINAL * fc.Coef * SystemPrice) / SUM(FINAL * fc.Coef)) SystemPrice,
       DECODE(SUM(FINAL * fc.Coef), 0, AVG(ForecastedPrice),
              SUM(FINAL * fc.Coef * ForecastedPrice) / SUM(FINAL * fc.Coef)) ForecastedPrice,
			 NVL(AVG(ep.Price),0) Price,
       NVL(MIN((1 / (er.Multiplier / er.Divider)) * er2.Multiplier / er2.Divider),1) PriceCoef
  FROM ForecastSnapshotBodies fb
 CROSS JOIN DefaultCurrencies c
  JOIN ForecastWeeklyCoefs fc
    ON fc.Id = fb.FinalWeeklyCoefId AND fb.DateFrom = fc.DateFrom
  LEFT JOIN IH#ExpandedPrices ep
    ON ep.SiteMaterialUsageId = fb.SiteMaterialUsageId 
   AND CASE WHEN fc.DateFromIW > fc.DateFrom THEN fc.DateFromIW ELSE fc.DateFrom END BETWEEN ep.DateFrom AND ep.DateTo
  LEFT JOIN ExpandedExchangeRates er
    ON er.CurrencyId = ep.CurrencyId
   AND fb.DateFrom BETWEEN er.DateFrom AND er.DateTo
  LEFT JOIN ExpandedExchangeRates er2
    ON fb.DateFrom BETWEEN er2.DateFrom AND er2.DateTo
   AND er2.CurrencyId = c.Id
 GROUP BY fb.ForecastSnapshotId, fb.SiteMaterialUsageId, 
          CASE WHEN fc.DateFromIW > fc.DateFrom THEN fc.DateFromIW ELSE fc.DateFrom END
 ORDER BY 1,2,3

top
IHDP#WeekMonthSystemForecast
WITH DefaultCurrencies AS
 (SELECT ID FROM Currencies WHERE IsInternal = 1)
SELECT fb.SiteMaterialUsageId, CASE WHEN fc.DateFromIW > fc.DateFrom THEN fc.DateFromIW ELSE fc.DateFrom END DateFrom,
			 SUM(FINAL * fc.Coef) FINAL,
       DECODE(SUM(FINAL * fc.Coef), 0, AVG(SystemPrice),
			        SUM(FINAL * fc.Coef * SystemPrice) / SUM(FINAL * fc.Coef)) SystemPrice,
       DECODE(SUM(FINAL * fc.Coef), 0, AVG(ForecastedPrice),
              SUM(FINAL * fc.Coef * ForecastedPrice) / SUM(FINAL * fc.Coef)) ForecastedPrice,
			NVL(AVG(ep.Price),0) Price,
       NVL(MIN((1 / (er.Multiplier / er.Divider)) * er2.Multiplier / er2.Divider),1) PriceCoef
FROM   ForecastBodies fb
CROSS  JOIN DefaultCurrencies c
JOIN   ForecastWeeklyCoefs fc
ON     (fb.DateFrom = fc.DateFrom AND fb.FinalWeeklyCoefId = fc.Id)
LEFT   JOIN IH#ExpandedPrices ep
ON     (ep.SiteMaterialUsageId = fb.SiteMaterialUsageId AND CASE WHEN fc.DateFromIW > fc.DateFrom THEN fc.DateFromIW ELSE fc.DateFrom END BETWEEN ep.DateFrom AND ep.DateTo)
LEFT   JOIN ExpandedExchangeRates er
ON     er.CurrencyId = ep.CurrencyId
AND    fb.DateFrom BETWEEN er.DateFrom AND er.DateTo
LEFT   JOIN ExpandedExchangeRates er2
ON     fb.DateFrom BETWEEN er2.DateFrom AND er2.DateTo
AND    er2.CurrencyId = c.Id
GROUP  BY fb.SiteMaterialUsageId, CASE WHEN fc.DateFromIW > fc.DateFrom THEN fc.DateFromIW ELSE fc.DateFrom END
ORDER BY 1,2

top
IHDP#WeekSystemForecast System weekly forecast used as SNP input

WITH DefaultCurrencies AS
 (SELECT ID FROM Currencies WHERE IsInternal = 1)
SELECT fb.SiteMaterialUsageId, fc.DateFromIW DateFrom, SUM(FINAL * fc.Coef) FINAL,
       DECODE(SUM(FINAL * fc.Coef), 0, AVG(SystemPrice), SUM(FINAL * fc.Coef * SystemPrice) / SUM(FINAL * fc.Coef)) SystemPrice,
       DECODE(SUM(FINAL * fc.Coef), 0, AVG(ForecastedPrice),
               SUM(FINAL * fc.Coef * ForecastedPrice) / SUM(FINAL * fc.Coef)) ForecastedPrice,
       NVL(AVG(ep.Price),0) Price,
       NVL(MIN((1 / (er.Multiplier / er.Divider)) * er2.Multiplier / er2.Divider), 1) PriceCoef
FROM   ForecastBodies fb
CROSS  JOIN DefaultCurrencies c
JOIN   ForecastWeeklyCoefs fc
ON     (fb.DateFrom = fc.DateFrom AND fb.FinalWeeklyCoefId = fc.Id)
LEFT   JOIN IH#ExpandedPrices ep
ON     (ep.SiteMaterialUsageId = fb.SiteMaterialUsageId AND fc.DateFromIW BETWEEN ep.DateFrom AND ep.DateTo)
LEFT   JOIN ExpandedExchangeRates er
ON     er.CurrencyId = ep.CurrencyId
AND    fb.DateFrom BETWEEN er.DateFrom AND er.DateTo
LEFT   JOIN ExpandedExchangeRates er2
ON     fb.DateFrom BETWEEN er2.DateFrom AND er2.DateTo
AND    er2.CurrencyId = c.Id
GROUP  BY fb.SiteMaterialUsageId, fc.DateFromIW

top
IHForecastSnapshots
SELECT 'Snapshot' TYPE, fs.ID, fs.NAME, fs.DESCRIPTION, fs.IsBudget, fs.IsShowOnGraph,
fs.StartDate, fs.FinishDate,
Trunc(fs.StartDate, 'IW') StartWeek,
Trunc(Last_Day(fs.FinishDate), 'IW') FinishWeek,
fs.Id OrderCondition,
ufs.Name UnconstrainedName, fs.UnconstrainedSnapshotId, fs.IsConstrained, fs.DEtailId,
SIGN(fs.ErrorsQuantity) Status, fs.NewSkuCreated, d.Description FILTER
FROM ForecastSnapshots fs LEFT JOIN Forecastsnapshots ufs ON (fs.UnconstrainedSnapshotid = ufs.ID)
LEFT JOIN IH#DetailsDescription d ON fs.DetailId = d.Id
UNION ALL
SELECT 'Forecast' TYPE, 0 ID, 'Monthly Forecast', 'Monthly Forecast' Description, 0 IsBudget, 0 IsShowOnGraph,
NULL, NULL, NULL, NULL, -1 OrderCondition, NULL UnconstrainedName, NULL UnconstrainedSnapshotId, 0 IsConstrained, NULL DetailId, 0 Status, 0 NewSkuCreated, '' FILTER
FROM dual
top
IHL#OrderOperations
SELECT OrderCode, LineNoCode, OperationNo,
OrderBookId, OrderLineId, oo.Id OrderOperationId,
NVL(oo.MaterialId, ol.MaterialId) TargetMaterialId
from OrderOperations oo
JOIN OrderLines ol
ON ol.Id = oo.OrderLineId
JOIN OrderBooks ob
ON ob.Id = ol.OrderBookId

top
IHMP#Allocation
SELECT SiteMaterialUsageId, smu.MaterialId, WorkcentreId, DeliveryWeek DemandWeek, DeliveryMonth DemandMonth, DispatchMonth, DispatchWeek,
SUM(System) System,
SUM(Customer) Customer,
SUM(Indicatives) Indicatives,
SUM(Orders) Orders,
SUM(Customer - Orders) RemainingAllocation
FROM (
    SELECT SiteMaterialUsageId, WorkcentreId, DeliveryWeek, DeliveryMonth,
    TRUNC(DeliveryWeek - NVL(mr.TimePeriod,0), 'IW') DispatchWeek,
    TRUNC(DeliveryWeek - NVL(mr.TimePeriod,0), 'month') DispatchMonth,
    System, Customer, 0 Indicatives, 0 Orders
    FROM AllocationBodies a
    LEFT JOIN MasterRoutes mr
    ON mr.Id = a.MasterRouteId
    UNION ALL
    SELECT SitematerialusageId, WorkcentreId, TRUNC(DeliveryDate, 'IW') DeliveryWeek,
    TRUNC(DeliveryDate, 'month') DeliveryMonth,
    TRUNC(DespatchDate, 'IW') DispatchWeek,
    TRUNC(DespatchDate, 'month') DispatchMonth,
     0 System, 0 Customer, 0 Indicatives, FinalWeight Orders
    FROM   OrderLines ol
    JOIN   OrderLineStatuses ols
    ON     ols.Id = ol.OrderLineStatusId
    WHERE  ols.OrderLineStatusCode IN ('Firm', 'Completed')
) t
JOIN SiteMaterialUsages smu
ON t.SiteMaterialUsageID = smu.Id
GROUP BY SiteMaterialUsageId, MaterialId, WorkcentreId, DeliveryWeek, DeliveryMonth, DispatchWeek, DispatchMonth
top
IHMP#AllocationIndicatives
SELECT SiteMaterialUsageId, smu.MaterialId, WorkcentreId, DeliveryWeek DemandWeek, DeliveryMonth DemandMonth,
DispatchWeek, DispatchMonth,
SUM(System) System,
SUM(Customer) Customer,
SUM(Indicatives) Indicatives,
SUM(Orders) Orders,
SUM(Customer - Orders) RemainingAllocation
FROM (
    SELECT SiteMaterialUsageId, WorkcentreId, DeliveryWeek, DeliveryMonth,
    TRUNC(DeliveryWeek - NVL(mr.TimePeriod,0), 'IW') DispatchWeek, TRUNC(DeliveryWeek - NVL(mr.TimePeriod,0), 'month') DispatchMonth,
    System, Customer, 0 Indicatives, 0 Orders
    FROM AllocationBodies a
    LEFT JOIN MasterRoutes mr
    ON mr.Id = a.MasterRouteId
    UNION ALL
    SELECT SiteMaterialUsageId, WorkcentreId, DeliveryWeek, DeliveryMonth,
    TRUNC(DeliveryWeek - NVL(mr.TimePeriod,0), 'IW') DispatchWeek, TRUNC(DeliveryWeek - NVL(mr.TimePeriod,0), 'month') DispatchMonth,
    0 System, 0 Customer, VALUE Indicatives, 0 Orders
    FROM Indicatives i
    LEFT JOIN MasterRoutes mr
    ON mr.Id = i.MasterRouteId
    UNION ALL
    SELECT SitematerialusageId, WorkcentreId, TRUNC(DeliveryDate, 'IW') DeliveryWeek,
    TRUNC(DeliveryDate, 'month') DeliveryMonth,
    TRUNC(DespatchDate, 'IW') DispatchWeek, TRUNC(DespatchDate, 'month') DispatchMonth,
    0 System, 0 Customer, 0 Indicatives, FinalWeight Orders
    FROM   OrderLines ol
    JOIN   OrderLineStatuses ols
    ON     ols.Id = ol.OrderLineStatusId
    WHERE  ols.OrderLineStatusCode IN ('Firm', 'Completed')
) t
JOIN SiteMaterialUsages smu
ON t.SiteMaterialUsageID = smu.Id
GROUP BY SiteMaterialUsageId, MaterialId, WorkcentreId, DeliveryWeek, DeliveryMonth, DispatchWeek, DispatchMonth
top
IHMP#MonthlySnapshotAllocation View for releasing SNP Allocation to Forecast snapshot.
SELECT sd.ScenarioId, sd.SnapshotUserId, c.SiteMaterialUsageId, sd.DateFrom DeliveryDate,
sd.Price,
sd.Aggregated * c.Coef DEMAND,
DECODE(sd.Allocation, 0, 0, sd.Allocation) * c.Coef AS Allocation,
DECODE(sd.Aggregated - sd.Allocation, 0, 0, sd.Aggregated - sd.Allocation) * c.Coef AS Unallocated,
NVL(sd.COST, 0) COST,
DECODE(sd.Allocation, 0, 0, sd.Cost / sd.Allocation) NominalCost, sd.Id
FROM   SNODemands sd
JOIN   SNOItemsShort SI
ON     si.SnapshotUserId = sd.SnapshotUserId
AND    si.Id = sd.Id
JOIN   SNOItemCoefs c
ON     sd.Id = c.Id
AND    sd.SnapshotUserId = c.SnapshotUserId
AND    c.DateFrom = sd.DateFrom
WHERE  sd.Aggregated * c.Coef > 0


top
IHMP#SkuWorkcentrePairs2
SELECT DISTINCT SiteMaterialUsageId, WorkcentreId
FROM (
SELECT smu.Id SiteMaterialUsageId, NULL WorkcentreId
FROM   SiteMaterialUsages smu
WHERE  EXISTS (SELECT 1
        FROM   ForecastBodies fb
        WHERE  fb.SiteMaterialUsageId = smu.Id
        AND    DateFrom >= (SELECT add_months(TRUNC(core.getTruncatedInternalDate, 'month'), -NVL(MIN(VALUE), 12)) StartDateInPast
                            FROM   Systemparameters
                            WHERE  ParameterName = 'LiveAllocationPeriodInPast'))
UNION ALL
SELECT SiteMaterialUsageId, WorkcentreId
FROM   AllocationBodies
WHERE  NVL(DeliveryMonth, DeliveryWeek) >=
    (SELECT add_months(TRUNC(core.getTruncatedInternalDate, 'month'), -NVL(MIN(VALUE), 12)) StartDateInPast
     FROM   Systemparameters
     WHERE  ParameterName = 'LiveAllocationPeriodInPast')
UNION ALL
SELECT ol.siteMaterialUsageId, COALESCE(oo.WorkcentreId, ol.WorkcentreId) WorkcentreId
FROM   OrderLines ol
LEFT JOIN OrderOperations oo
ON oo.OrderLineId = ol.Id
WHERE  DeliveryDate >= (SELECT add_months(TRUNC(core.getTruncatedInternalDate, 'month'), -NVL(MIN(VALUE), 12)) StartDateInPast
                     FROM   Systemparameters
                     WHERE  ParameterName = 'LiveAllocationPeriodInPast')
UNION ALL
SELECT uh.SiteMaterialUsageId, uh.WorkcentreId
FROM   UsageHistories uh
WHERE  DateFrom >= (SELECT add_months(TRUNC(core.getTruncatedInternalDate, 'month'), -NVL(MIN(VALUE), 12)) StartDateInPast
                 FROM   Systemparameters
                 WHERE  ParameterName = 'LiveAllocationPeriodInPast')
)

top
IHRP#SourceRunCombinedCapacity

WITH q AS (
SELECT sr.SiteId, WorkcentreId, MaterialId, SUM(Capacity) Capacity
FROM sourceRuns sr
JOIN SourceRunMaterials srm ON srm.MaterialRunId = sr.MaterialRunId
WHERE sr.MaterialRunid > 0
GROUP BY SiteId, WorkcentreId, MaterialId
)
SELECT NVL(q.SiteId, r.SiteId) SiteId,
NVL(q.WorkcentreId, r.WorkcentreId) WorkcentreId,
NVL(q.MaterialId, r.MaterialId) MaterialId,
NVL(q.Capacity, 0) Capacity,
NVL(Rate,0) Rate
FROM  q
FULL OUTER JOIN Ivbs#actualproductionrates r
ON r.WorkcentreId = q.WorkcentreId
AND r.materialId = q.MaterialId

top
IHSA#AllocationMTD

WITH allocations AS
 (SELECT ab.SiteMaterialUsageId, ab.WorkcentreId, SUM(Customer) Allocation
  FROM   AllocationBodies ab
  WHERE  DeliveryMonth = TRUNC(core.getInternalDate, 'month')
  GROUP  BY ab.SiteMaterialUsageId, ab.WorkcentreId),
history AS
 (SELECT SiteMaterialUsageId, WorkcentreId, SUM(NVL(AdjustedWeight, Weight)) HistoryWeight
  FROM   UsageHistories
  WHERE  TRUNC(DateFrom, 'month') = TRUNC(core.getInternalDate, 'month')
  GROUP  BY SiteMaterialUsageId, WorkcentreId)

SELECT NVL(a.SiteMaterialUsageId, h.SiteMaterialUsageId) SiteMaterialUsageId, NVL(a.WorkcentreId, h.WorkcentreId) WorkcentreId,
       NVL(Allocation, 0) Allocation, NVL(HistoryWeight, 0) HistoryWeight, WorkingDays, totalWorkingDays,
       CASE WHEN WorkingDays = 0 THEN 0 ELSE NVL(Allocation, 0) / WorkingDays END DailyAllocation,
       CASE WHEN WorkingDays = 0 OR NVL(Allocation, 0) = 0 OR TotalWorkingDays = 0 THEN 0
           ELSE NVL(HistoryWeight, 0) / WorkingDays * TotalWorkingDays / NVL(Allocation, 0) * 100
       END Percentage
FROM   allocations a
FULL   OUTER JOIN history h
ON     h.SiteMaterialUsageId = a.SiteMaterialUsageId
AND    h.WorkcentreId = a.WorkcentreId
JOIN   IH#SkuWorkingDays c
ON     c.SiteMaterialUsageID = NVL(a.SiteMaterialUsageId, h.SiteMaterialUsageId)
AND c.DateFrom = core.getTruncatedInternalDate()

top
IHSA#AllocationsVsOrders
WITH orders AS
(
SELECT SiteMaterialUsageId, NVL(oo.WorkcentreId, ol.WorkcentreId) WorkcentreId, SUM(FinalWeight) OrdersWeight,
LEAST(GREATEST(MAX(DeliveryDate), core.getTruncatedInternalDate), LAST_DAY(core.getTruncatedInternalDate)) MaxDeliveryDate
  FROM   OrderLines ol
  JOIN   OrderLineStatuses ols
  ON     ols.Id = ol.OrderLineStatusId
  LEFT JOIN OrderOperations oo
  ON oo.OrderLineId = ol.Id
  AND oo.IsLastOperation = 1
  WHERE  TRUNC(DeliveryDate, 'month') = TRUNC(CORE.getInternalDate, 'month')
  AND    OrderLineStatusCode IN ('Completed', 'Firm')
  GROUP  BY SiteMaterialUsageId,  NVL(oo.WorkcentreId, ol.WorkcentreId)
),
allocations AS
 (SELECT ab.SiteMaterialUsageId, ab.WorkcentreId, SUM(Customer) Allocation
  FROM   AllocationBodies ab
  WHERE  DeliveryMonth = TRUNC(core.getInternalDate, 'month')
  GROUP  BY ab.SiteMaterialUsageId, ab.WorkcentreId)
SELECT o.SiteMaterialUsageID, o.WorkcentreId, WorkingDays, TotalWorkingDays, a.Allocation,  o.OrdersWeight,
case when TotalWorkingDays = 0 THEN 0 ELSE a.Allocation / TotalWorkingDays END DailyAllocation,
case when TotalWorkingDays = 0 OR WorkingDays = 0 THEN 0 ELSE a.Allocation / TotalWorkingDays * WorkingDays END CurrentAllocation,
case when TotalWorkingDays = 0 OR WorkingDays = 0 OR a.Allocation = 0 THEN 0 ELSE OrdersWeight / (a.Allocation / TotalWorkingDays * WorkingDays)  * 100 END Percentage
FROM Orders o
JOIN allocations a
ON a.SiteMaterialUsageId = o.SiteMaterialUsageId
AND a.WorkcentreId = o.WorkcentreId
JOIN IH#SkuWorkingDays s
ON s.SiteMaterialUSageID = o.siteMaterialUsageId
AND s.DateFrom = o.MaxDeliveryDate

top
IHSA#AllocationVsHistory


WITH allocations AS
(

SELECT ab.SiteMaterialUsageId, smu.MaterialId, smu.LocationId, ab.WorkcentreId, DeliveryWeek Period,
SUM(Customer) Allocation, ep.Price CalculatedPrice,
SUM(Customer * COST) / SUM(Customer) COST
FROM AllocationBodies ab
JOIN SiteMaterialUsages smu
ON smu.Id = ab.SiteMaterialUsageId
JOIN Workcentres wc
ON wc.Id = ab.WorkcentreId
JOIN Locations l
ON l.Id = wc.LocationId
LEFT JOIN IH#ExpandedPrices ep
ON ep.SiteMaterialUsageId = ab.Sitematerialusageid
AND DeliveryWeek BETWEEN ep.DateFrom AND ep.DateTo
LEFT JOIN IH#ProductCosts pc
ON pc.MaterialId = smu.MaterialId
AND pc.WorkcentreId = ab.WorkcentreId
AND DeliveryWeek BETWEEN pc.Effective AND pc.NextEffective
AND Customer > 0
GROUP BY  ab.SiteMaterialUsageId, smu.MaterialId, smu.LocationId, ab.WorkcentreId, DeliveryWeek,  ep.Price
)
,
history AS
(
  SELECT SiteMaterialUsageId, smu.MaterialId, smu.LocationId, uh.WorkcentreId, TRUNC(dateFrom, 'IW') Period,
         SUM(NVL(AdjustedWeight, Weight)) History,
         SUM(NVL(AdjustedWeight, Weight) * Price) / SUM(NVL(AdjustedWeight, Weight)) ActualPrice,
				 AVG(pc.COST) COST
  FROM   UsageHistories uh
  JOIN   SiteMaterialUsages smu
  ON     smu.Id = uh.SiteMaterialUsageId
  LEFT   JOIN IH#ProductCosts pc
  ON     pc.MaterialId = smu.MaterialId
  AND    pc.WorkcentreId = uh.WorkcentreId
  AND    uh.dateFrom BETWEEN pc.Effective AND pc.NextEffective
  GROUP  BY SiteMaterialUsageId, smu.MaterialId, smu.LocationId, uh.WorkcentreId, TRUNC(dateFrom, 'IW')
)
SELECT NVL(a.SiteMaterialUsageId, h.SiteMaterialUsageId) SiteMaterialUsageId,
NVL(a.MaterialId, h.MaterialId) MaterialId,
NVL(a.LocationId, h.LocationId) LocationId,
NVL(a.Workcentreid, h.Workcentreid) WorkcentreId,
NVL(a.Period, h.Period) Period,
a.Allocation, h.History, a.CalculatedPrice, ActualPrice,
NVL(a.Cost, h.Cost) COST
FROM allocations a
FULL OUTER JOIN history h
ON h.SiteMaterialUsageId = a.SiteMaterialUSageId
AND h.WorkcentreId = a.WorkcentreId
AND h.Period = a.Period

top
IHSA#CoProductAllocations
SELECT a.SnapshotUserId, a.ScenarioId, a.Id, a.WorkcentreId,
       CASE
           WHEN SIGN(MasterRouteId) = -1 THEN
            NULL
           ELSE
            MasterRouteId
       END MasterRouteId, smu.Id SitematerialusageId, a.DeliveryDate DeliveryPeriod, a.SourceDate SourcePeriod,
       0 AS NonMoveableWeight, a.Allocation * c.Coef AS System, a.AllocationId, a.StageNo, a.SeqNo, a.IsLastStage,
       si.PropertyValueId, a.ProductRouteId, a.OperationTypeId, a.NextOperationTypeId, a.SourceMaterialId

FROM   SourcingAllocation a
JOIN   SNOItemCoefs c
ON     a.Id = c.Id
AND    a.SnapshotUserId = c.SnapshotUserId
AND    c.DateFrom = a.DeliveryDate
JOIN SNOItemsShort si
 ON    c.SnapshotUserId = si.SnapshotUserId
 AND    si.Id = a.Id
 AND  si.CoProductId = a.CoProductId
JOIN IH#MainWarehouses wh
ON wh.SiteId = a.SiteId
LEFT JOIN SiteMaterialUsages smu
ON smu.LocationId = wh.LocationId
AND smu.MaterialId = a.CoProductId
WHERE  a.CoProductid IS NOT NULL
UNION ALL
SELECT so.Snapshotuserid, NULL ScenarioId, SnoItemId as id, so.WorkcentreId, MasterRouteId, smu.Id SiteMaterialUsageId,
       DeliveryPeriod,
			 SourcePeriod,
       so.Weight AS NonMoveableWeight, 0 AS System,
       -1 AllocationId, 0 StageNo, 0 seqNo, 1 IsLastStage,
			 so.PropertyValueId,  NULL ProductRouteId, so.OperationTypeId, NULL NextOperationTypeId, NULL SourceMaterialId
FROM   SNOAllOrderSnapshots so
JOIN IH#Workcentres wc
ON so.WorkcentreId = wc.WorkcentreID
JOIN IH#MainWarehouses wh
ON wh.SiteId = wc.SiteId
LEFT JOIN SiteMaterialUsages smu
ON smu.LocationId = wh.LocationId
AND smu.MaterialId = so.CoProductId
WHERE  so.IsFirm = 1
AND    so.CoProductId IS NOT NULL
AND    so.SourceType IN ('stock', 'production')
AND    so.PropertyValueId IS NOT NULL
AND    so.SourcePeriod IS NOT NULL
top
IHSA#CoProductCoefs
SELECT SnapshotUSerId, SnpITemId, CoProductId, Percentage, TotalPercentage, TotalPricePercentage, Percentage / 100 Coef
FROM   CoProductSnapshots



top
IHSA#CycleCapacity
WITH q AS (
SELECT DISTINCT SnapshotUserId, ScenarioId, WorkcentreId, CycleTypeId, DateFrom FROM ScenarioRates
WHERE IsActive > 0
)
SELECT q.SnapshotUserId, q.ScenarioId, q.DateFrom, q.CycleTypeId, q.WorkcentreId FROM IVSA#PaperMachineCapacities pm
JOIN q ON pm.Workcentreid = q.WorkcentreId
AND q.DateFrom = pm.DateFrom
AND pm.SnapshotUserId = q.SnapshotUserId
AND pm.ScenarioId = q.ScenarioId
WHERE HasCapacity = 1
top
IHSA#CycleFixedPeriods
    SELECT ss.SnapshotUserId, ct.ScenarioId, ct.CycleTypeId, CycleType, ct.DetailId,
        ss.FixedPeriodDate,
        MaxStartDate LastFixedRunPeriodDate,
		ss.StartWeek + FixedPeriodInWeeks * 7 CyclePeriodDate,
        LEAST(ss.FinishWeek, GREATEST(ss.FixedPeriodDate, ss.StartWeek + FixedPeriodInWeeks * 7, NVL(mr.MaxStartDate, ss.FixedPeriodDate))) CycleFixedPeriodDate,
        Frequency, WeekTolerance, ct.Priority, ProducingDay, GroupName,
        FixedPeriodInWeeks
    FROM IHSA#CycleTypes ct
    JOIN ScenarioSessions ss
    ON ss.SnapshotUserId = ct.SnapshotUserId
	LEFT JOIN (
        SELECT SnapshotUserId, cycleTypeId, MAX(TRUNC(StartDate)) MaxStartDate
        FROM SNPMaterialRunSnapshots
        WHERE ScenarioId = 0
        AND IsFixed = 1
        GROUP BY SnapshotUserId, cycleTypeId
	) mr
	ON mr.SnapshotUserId = ss.SnapshotUserId
	AND mr.CycleTypeID = ct.CycleTypeId
top
IHSA#CycleFrequency
    WITH orders AS
         (SELECT  /*+ INDEX(si LISNOITEMS2 ) */ so.SnapshotUserId, ct.CycleTypeId, ct.ScenarioId,
            MAX(CASE WHEN p.Value = 1 OR so.SourcePeriod > ct.CycleFixedPeriodDate THEN NULL ELSE so.SourcePeriod END) MaxOrderPeriodFixed,
            MIN(CASE WHEN p.Value = 1 OR so.SourcePeriod <= ct.CycleFixedPeriodDate THEN NULL ELSE so.SourcePeriod END) MinOrderPeriodPostFixed
          FROM   SNOAllOrderSnapshots so
          JOIN   SnoItems si
            ON   si.Id = so.SnoItemId
            AND  so.SnapshotUserId = si.SnapshotUserId
            AND  so.SourceType = 'production'
            AND  so.IsFirm = 1
          CROSS JOIN (SELECT NVL(MIN(VALUE), 0) VALUE from SystemParameters Where ParameterName = 'SNPExcludeOrdersFromDetermination') p
          JOIN IHSA#CycleFixedPeriods ct
            ON   ct.CycleTypeId = si.CycleTypeId
            AND  ct.SnapshotUserId = so.SnapshotUserId
          WHERE so.SourcePeriod IS NOT NULL
          GROUP  BY so.SnapshotUserId, ct.ScenarioId, ct.CycleTypeId),
    runs AS
         (SELECT SnapshotUserId, CycleTypeId, MAX(TRUNC(FinishDate)) MaxRunPeriod
          FROM   SNPMaterialRunSnapshots
          WHERE IsActive = 1
          AND   ScenarioId = 0
          GROUP  BY SnapshotUserId, CycleTypeid)
  SELECT ct.ScenarioId, ss.SnapshotUserId, UserName, StartWeek, ct.CycleTypeId, CycleType, Frequency, WeekTolerance, FixedPeriodInWeeks,
         MaxRunPeriod, MaxOrderPeriodFixed, MinOrderPeriodPostFixed,
         ss.FixedPeriodDate ScenarioFixedPeriodDate,
         ct.CycleFixedPeriodDate,
         CASE WHEN MaxOrderPeriodFixed IS NULL AND MaxOrderPeriodFixed IS NULL AND MaxRunPeriod IS NULL
              THEN ct.CycleFixedPeriodDate
              ELSE LEAST(
                GREATEST(
                    GREATEST(NVL(MaxRunPeriod, ss.StartWeek), NVL(MaxOrderPeriodFixed, ss.StartWeek)) + DECODE(Frequency, 0, 1, Frequency) * 7,
                    ct.CycleFixedPeriodDate
                ),
                GREATEST(ct.CycleFixedPeriodDate, NVL(MinOrderPeriodPostFixed, ss.StartWeek))
              )
         END AS FirstPeriodDate
  FROM IHSA#CycleFixedPeriods ct
  JOIN IH#ScenarioSessions SS
  ON ct.SnapshotUserId = ss.SnapshotUserId
  LEFT JOIN Orders o
  ON o.CycleTypeId = ct.CycleTypeId
  AND ss.SnapshotUserId = o.SnapshotUserId
  AND o.ScenarioId = ct.ScenarioId
  LEFT JOIN Runs r
  ON r.CycleTypeId = ct.CycleTypeId
  AND ss.SnapshotUserId = r.SnapshotUserId
top
IHSA#CycleTypes
    SELECT SnapshotUserId, ScenarioId, d.PropertiesCode CycleType, ct.Id CycleTypeId,
        DetailId, Frequency, WeekTolerance, ct.Priority, ProducingDay, GroupName, FixedPeriodInWeeks
    FROM CycleTypeSnapshots ct
    JOIN Ih#hierarchypropertydetails d
    ON d.ID = ct.DetailId
top
IHSA#CycleUtilisation

WITH q AS
(
    SELECT so.SnapshotUSerId, SnoItemId, NULL ScenarioId, SourcePeriod, WorkcentreId, si.cycleTypeId, so.SourcePropertyValueId,
           CASE WHEN so.RemainingDuration != 0 THEN so.RemainingDuration / 60
                WHEN NVL(so.Rate,0) != 0 THEN so.RemainingSourceWeight / Rate * (100 / TimeEfficiency)
                ELSE 0
           END OrdersHours,
           0 AllocationHours,
           so.RemainingSourceWeight OrdersWeight, 0 AllocationWeight, Rate
      FROM Snoallordersnapshots so
      JOIN SNOItemsShort SI
        ON so.Snoitemid = si.Id
       AND so.snapshotUserId = si.SnapshotUserId
       AND SourceType = 'production'
       AND so.RemainingSourceWeight > 0
       AND so.SourcePeriod IS NOT NULL
     UNION ALL
    SELECT sa.SnapshotUSerId, sa.Id SnoItemId, sa.ScenarioId, SourceDate SourcePeriod, WorkcentreId, si.cycleTypeId, sa.SourcePropertyValueId,
           0 OrdersHours, DECODE(Rate, 0, 0, Allocation / Rate * (100 / TimeEfficiency)) AllocationHours,
           0 OrdersWeight,
           Allocation AllocationWeight,
           Rate
      FROM SourcingAllocation sa
      JOIN SnoitemsShort SI
        ON sa.Id = si.Id
       AND sa.snapshotUserId = si.SnapshotUserId
       AND Allocation > 0
       AND OperationTypeId IS NOT NULL
)
SELECT SnapshotUserId, ScenarioId, SnoItemId, SourcePeriod, WorkcentreId, WorkcentreTypeId, CycleTypeId, SourcePropertyValueId,
       NVL(SUM(OrdersHours),0) OrdersHours, NVL(SUM(AllocationHours),0) AllocationHours,
       DECODE(SUM(OrdersHours + AllocationHours), 0, 0, SUM(OrdersWeight + AllocationWeight ) / SUM(OrdersHours + AllocationHours)) Rate
  FROM q
  JOIN Workcentres wc ON wc.Id = q.WorkcentreId
 GROUP BY SnapshotUserId, ScenarioId, SnoItemId, SourcePeriod, WorkcentreId, WorkcentreTypeId, cycleTypeId, SourcePropertyValueId

top
IHSA#DefaultOperations
SELECT wc.Id WorkcentreId, MIN(o.Id) OperationTypeId
FROM Workcentres wc JOIN
WorkcentreTypes wct ON wct.Id = wc.WorkcentreTypeId
JOIN OperationTypes o
ON o.Workcentretypeid = wct.Id
GROUP BY wc.Id
top
IHSA#DefaultProductRoutes
SELECT MaterialId, MIN(ProductRouteId) ProductRouteId
 FROM Productionconfigurations pc
 GROUP BY MaterialId
top
IHSA#IgnoredSmallDemands
WITH q AS (
SELECT SnapshotUserId, ScenarioID, ID
FROM  SnoDemands
GROUP BY SnapshotUserId, ScenarioID, Id
HAVING  SUM(Netted) != SUM(Aggregated)
)
SELECT sd.SnapshotUserId, sd.ScenarioID, sd.ID, sd.DateFrom, sd.Netted
FROM SNODemands sd
JOIN q
ON q.SnapshotUserId = sd.SnapshotUserId
AND q.ScenarioId = sd.ScenarioId
AND q.Id = sd.Id
top
IHSA#IndicativesMTD

WITH indicative AS
 (SELECT ab.SiteMaterialUsageId, ab.WorkcentreId, SUM(VALUE) IndicativeValue
  FROM   indicatives ab
  WHERE  DeliveryMonth = TRUNC(core.getInternalDate, 'month')
  GROUP  BY ab.SiteMaterialUsageId, ab.WorkcentreId),
history AS
 (SELECT SiteMaterialUsageId, WorkcentreId, SUM(NVL(AdjustedWeight, Weight)) HistoryWeight
  FROM   UsageHistories
  WHERE  TRUNC(DateFrom, 'month') = TRUNC(core.getInternalDate, 'month')
  GROUP  BY SiteMaterialUsageId, WorkcentreId)
SELECT NVL(a.SiteMaterialUsageId, h.SiteMaterialUsageId) SiteMaterialUsageId, NVL(a.WorkcentreId, h.WorkcentreId) WorkcentreId,
       NVL(IndicativeValue, 0) IndicativeValue,
       NVL(HistoryWeight, 0) HistoryWeight, WorkingDays, totalWorkingDays,
       CASE WHEN WorkingDays = 0 THEN 0 ELSE NVL(IndicativeValue, 0) / WorkingDays END DailyAllocation,
       CASE WHEN WorkingDays = 0 OR NVL(IndicativeValue, 0) = 0 OR TotalWorkingDays = 0 THEN 0
            ELSE NVL(HistoryWeight, 0) / WorkingDays * TotalWorkingDays / NVL(IndicativeValue, 0) * 100
       END Percentage
FROM   Indicative a
FULL   OUTER JOIN history h
ON     h.SiteMaterialUsageId = a.SiteMaterialUsageId
AND    h.WorkcentreId = a.WorkcentreId
JOIN   IH#SkuWorkingDays c
ON     c.SiteMaterialUsageID = NVL(a.SiteMaterialUsageId, h.SiteMaterialUsageId)
AND c.DateFrom = core.getTruncatedInternalDate
top
IHSA#IndicativesVsOrders
WITH orders AS
(
SELECT SiteMaterialUsageId, NVL(oo.WorkcentreId, ol.WorkcentreId) WorkcentreId, SUM(FinalWeight) OrdersWeight,
LEAST(GREATEST(MAX(DeliveryDate), core.getTruncatedInternalDate), LAST_DAY(core.getTruncatedInternalDate)) MaxDeliveryDate
  FROM   OrderLines ol
  JOIN   OrderLineStatuses ols
  ON     ols.Id = ol.OrderLineStatusId
  LEFT JOIN OrderOperations oo
  ON oo.OrderLineId = ol.Id
  AND oo.IsLastOperation = 1
  WHERE  TRUNC(DeliveryDate, 'month') = TRUNC(CORE.getInternalDate, 'month')
  AND    OrderLineStatusCode IN ('Completed', 'Firm')
  GROUP  BY SiteMaterialUsageId, NVL(oo.WorkcentreId, ol.WorkcentreId)
),
allocations AS
 (SELECT ab.SiteMaterialUsageId, ab.WorkcentreId, SUM(VALUE) IndicativesValue
  FROM   indicatives ab
  WHERE  DeliveryMonth = TRUNC(core.getInternalDate, 'month')
  GROUP  BY ab.SiteMaterialUsageId, ab.WorkcentreId)
SELECT o.SiteMaterialUsageID, o.WorkcentreId, WorkingDays, TotalWorkingDays, a.IndicativesValue,  o.OrdersWeight,
case when TotalWorkingDays = 0 THEN 0 ELSE a.IndicativesValue / TotalWorkingDays END DailyAllocation,
case when TotalWorkingDays = 0 OR WorkingDays = 0 THEN 0 ELSE a.IndicativesValue / TotalWorkingDays * WorkingDays END CurrentAllocation,
case when TotalWorkingDays = 0 OR WorkingDays = 0 OR a.IndicativesValue = 0 THEN 0 ELSE OrdersWeight / (a.IndicativesValue / TotalWorkingDays * WorkingDays)  * 100 end Percentage
FROM Orders o
JOIN IH#SkuWorkingDays s
ON s.SiteMaterialUSageID = o.siteMaterialUsageId
AND s.DateFrom = o.MaxDeliveryDate
JOIN allocations a
ON a.SiteMaterialUsageId = o.SiteMaterialUsageId
AND a.WorkcentreId = o.WorkcentreId
top
IHSA#MaterialRunSnapshots
SELECT WorkcentreName, CycleType, InitialDuration / 60 Hours, mr.*
FROM Snpmaterialrunsnapshots mr
JOIN Workcentres wc
ON wc.Id = mr.WorkcentreId
JOIN IHSA#CycleTypes ct
ON ct.CycleTypeId = mr.CycleTypeId
AND ct.ScenarioId = mr.ScenarioId
AND mr.SnapshotUserId = ct.SnapshotUserId
ORDER BY WorkcentreId, SourcePeriod, StartDate
top
IHSA#NettedLiveAllocation
WITH OrderLineOperations
AS (
SELECT SiteMaterialUsageId,
       TRUNC(NVL(oo.DueDate, ol.DespatchDate), DECODE(LiveAllocationPeriod, 'Month', 'month', 'IW')) SourceDate,
       oo.WorkcentreId, oo.OperationTypeId, SUM(oo.Quantity) Quantity
FROM   OrderLines ol
JOIN   OrderOperations oo
ON     oo.OrderLineId = ol.Id
JOIN   Orderlinestatuses ols
ON     ols.Id = ol.OrderLineStatusId
JOIN   OrderOperationStatuses oos
ON     oos.Id = oo.OrderOperationStatusId
CROSS  JOIN (SELECT NVL(MIN(VALUE), 'WeekMonth') LiveAllocationPeriod
FROM   SystemParameters
WHERE  ParameterName = 'LiveAllocationPeriod') p
WHERE  OrderLineStatusCode IN ('Firm', 'Completed')
AND    OrderOperationStatusCode IN ('Firm', 'Completed')
GROUP  BY SiteMaterialUsageId,  oo.OperationTypeId,
          TRUNC(NVL(oo.DueDate, ol.DespatchDate), DECODE(LiveAllocationPeriod, 'Month', 'month', 'IW')), oo.WorkcentreId
),
allocations AS
(
SELECT siteMaterialUsageId, DECODE(LiveAllocationPeriod, 'Month', SourceMonth, SourceWeek) SourceDate,
       WorkcentreId, OperationTypeId, SUM(Customer) Allocation
 FROM AllocationBodies
CROSS  JOIN (SELECT NVL(MIN(VALUE), 'WeekMonth') LiveAllocationPeriod
FROM   SystemParameters
WHERE  ParameterName = 'LiveAllocationPeriod') p
WHERE Customer > 0
GROUP BY siteMaterialUsageId, OperationTypeId, DECODE(LiveAllocationPeriod, 'Month', SourceMonth, SourceWeek),
       WorkcentreId
)
SELECT NVL(a.SiteMaterialUsageId, oo.SiteMaterialUsageId) SiteMaterialUsageId,
 NVL(a.WorkcentreId, oo.WorkcentreId) WorkcentreId,
 NVL(a.OperationTypeId, oo.OperationTypeId) OperationTypeId,
 NVL(a.SourceDate, oo.SourceDate) SourceDate,
 SUM(NVL(a.Allocation,0)) Allocation, SUM(NVL(oo.Quantity,0)) Quantity,
GREATEST(0, SUM(NVL(a.Allocation,0) - NVL(oo.Quantity,0))) RemainingAllocation
FROM allocations a
FULL OUTER JOIN OrderLineOperations oo
ON a.SiteMaterialUsageId = oo.SiteMaterialUsageId
AND a.WorkcentreId = oo.WorkcentreId
AND a.OperationTypeId = oo.OperationTypeId
AND a.SourceDate = oo.SourceDate
GROUP BY NVL(a.SiteMaterialUsageId, oo.SiteMaterialUsageId),
 NVL(a.WorkcentreId, oo.WorkcentreId),
 NVL(a.OperationTypeId, oo.OperationTypeId),
 NVL(a.SourceDate, oo.SourceDate)
HAVING GREATEST(0, SUM(a.Allocation - NVL(oo.Quantity,0))) > 0 OR SUM(NVL(oo.Quantity,0)) > 0
top
IHSA#OrderOperations
SELECT ol.MaterialId, oo.WorkcentreId, NVL(oo.OperationTypeId, o.OperationTypeId) OperationTypeId,
 TRUNC(NVL(oo.DueDate, ol.DespatchDate), 'IW') SourceWeek,
pr.ProductRouteId, m.ReplenishmentFlag, SIGN(NVL(wc.Id, 0)) IsWarehouse, NVL(oo.Quantity, ol.Finalweight) Weight
FROM OrderLines ol
LEFT JOIN OrderOperations oo
ON oo.Orderlineid = ol.Id
JOIN OrderLineStatuses ols
ON ols.Id = ol.OrderLineStatusID
JOIN OrderOperationStatuses oos
ON oos.Id = oo.OrderOperationStatusId
LEFT JOIN Workcentres wc
ON wc.LocationId = ol.LocationId
JOIN IHSA#ReplenishedMaterials m ON m.MaterialId = ol.MaterialId
LEFT JOIN IHSA#DefaultOperations o ON o.WorkcentreId = oo.WorkcentreId
LEFT JOIN IHSA#DefaultProductRoutes pr ON pr.MaterialId = ol.MaterialId
WHERE OrderLineStatusCode IN ('Firm', 'Completed')
AND OrderOperationStatusCode IN ('Firm', 'Completed')
top
IHSA#ProductionConfigurations
SELECT SnapshotUserId, MaterialId, LocationId, MIN(ProductRouteId) ProductRouteId,
       core.asCsv(SET(CAST(COLLECT(unique ID ORDER BY ID) AS myIdentityArray))) ConfigurationSet
FROM   ConfigurationSnapshots
GROUP  BY SnapshotUserId, MaterialId, LocationId

top
IHSA#ProductionPlanSnapshots
SELECT WorkcentreName, CycleType, InitialDuration / 60 Hours, p.* FROM SnpProductionPlanSnapshots p
JOIN Workcentres wc
ON wc.Id = p.WorkcentreId
JOIN IHSA#CycleTypes ct
ON ct.CycleTypeId = p.CycleTypeId
aND p.ScenarioId = ct.ScenarioId
AND p.SnapshotUserID = ct.SnapshotUserId
ORDER BY WorkcentreId, SourcePeriod, StartDate

top
IHSA#ProductionUtilisation
WITH q AS
(
  SELECT mi.SnapshotUserId, ScenarioId, OrderNo, wc.WorkcentreTypeId, WorkcentreTypeDesc, mi.WorkcentreId,
         DateFrom, TimePeriod, PeriodLength * 24 * NumberOfWorkcentres PeriodHours,
           SUM( (PeriodLength * NumberOfWorkcentres * 24 - ShutHours) * ((100 - TimeEfficiency)  / 100)) RoughTimeLostHours,
         SUM(NominalCapacityHours + ShutHours) TotalHours, SUM(ShutHours) ShutHours, SUM(OrdersHours) OrdersHours,
         SUM(AllocationHours) AllocationHours, SUM(FixedCapacityHours) FixedHours, SUM(GREATEST(0, CapacityHours - FixedCapacityHours)) FreeCapacityHours
    FROM Machineinformation mi
    JOIN IH#Workcentres wc
      ON wc.WorkcentreId = mi.workcentreId
    JOIN Scenarioperiodsnapshots p ON p.startperiod = mi.DateFrom
     AND p.SnapshotUserId = mi.SnapshotUserId
   WHERE wc.IsProductionSource = 1
   GROUP BY mi.SnapshotUserId, ScenarioId, OrderNo, NumberOfWorkcentres, wc.WorkcentreTypeId, WorkcentreTypeDesc,
            DateFrom, TimePeriod, PeriodLength, CUBE(mi.WorkcentreId)
)
SELECT SnapshotUserId, ScenarioId, q.WorkcentreTypeId, q.WorkcentreTypeDesc, q.WorkcentreId, WorkcentreName, WorkcentreCode, SiteCode,
       SiteName, DateFrom, TimePeriod, PeriodHours, RoughTimeLostHours, TotalHours, ShutHours, OrdersHours, AllocationHours, FixedHours, 
       FreeCapacityHours, 
       CASE WHEN ShutHours + OrdersHours + AllocationHours > TotalHours THEN 1 ELSE 0 END IsOverbooked,
       CASE WHEN ShutHours + OrdersHours + AllocationHours = TotalHours THEN 1 ELSE 0 END IsBottleneck      
  FROM q
  LEFT JOIN IH#Workcentres wc
    ON wc.WorkcentreId = q.WorkcentreId
 ORDER BY SnapshotUserId, ScenarioId, q.OrderNo,
          DateFrom, TimePeriod, WorkcentreName NULLS FIRST, WorkcentreCode NULLS FIRST
top
IHSA#ReplenishedMaterials
SELECT m.Id MaterialId, NVL(ab.ReplenishmentFlag, 0) ReplenishmentFlag
FROM   Materials m
LEFT   JOIN (SELECT MaterialId, MAX(ReplenishmentFlag) ReplenishmentFlag FROM AllocationBodies2 GROUP BY MaterialId) ab
ON     ab.MaterialId = m.Id
top
IHSA#ScenarioPeriods
SELECT p.*,
       DECODE(UseFixedPeriod, 0, 0, case when StartPeriod < FixedPeriodDate then 1 else 0 end) IsFixed
FROM   Scenarioperiodsnapshots p
JOIN   ScenarioSessions SS
ON     ss.SnapshotUserId = p.SnapshotUserId
top
IHSA#SiteMape

WITH a AS
 (

 SELECT ab.SiteMaterialUsageId, ab.WorkcentreId, ab.DeliveryMonth, ab.Customer, ab.System, 0 Orders, 0 OrdersIncludeSupercessions, 0 History, 0 AdjustedHistory,
          0 SupersededHistory, 0 Indicatives
  FROM   AllocationBodies ab
  WHERE ab.System > 0 or ab.Customer > 0
  UNION ALL
  SELECT ol.SiteMaterialUsageId, ol.WorkcentreId, ol.DeliveryMonth,
         0 Customer, 0 System,
         ol.Orders, ol.OrdersIncludeSupercessions,
         0 History, 0 AdjustedHistoryWeight, 0 SupersededHistory, 0 Indicatives
  FROM   IH#SiteSupersededOrders ol
  WHERE ol.Orders > 0 OR ol.OrdersIncludeSupercessions > 0
  UNION ALL
  SELECT h.SiteMaterialUsageId, h.WorkcentreId, DateFrom DeliveryMonth, 0 Customer, 0 System, 0 Orders, 0 OrdersIncludeSupercessions,
         Weight History, adjustedHistoryWeight AdjustedHistory, 0 SupersededHistory, 0 Indicatives
  FROM   IH#SiteMonthlyHistories h
  WHERE Weight != 0 OR adjustedHistoryWeight != 0
  UNION ALL
  SELECT h.SiteMaterialUsageId, h.WorkcentreId, DateFrom DeliveryMonth, 0 Customer, 0 System, 0 Orders, 0 OrdersIncludeSupercessions,
         0 History, 0 AdjustedHistory, AdjustedSupersededHistory SupersededHistory, 0 Indicatives
  FROM   IH#SiteSupersededHistories h
  WHERE AdjustedSupersededHistory != 0
  UNION ALL
  SELECT SiteMaterialUsageId, i.WorkcentreId, DeliveryMonth, 0 Customer, 0 System, 0 Orders, 0 OrdersIncludeSupercessions,
         0 History, 0 AdjustedHistory, 0 SupersededHistory, Value Indicatives
  FROM   Indicatives i
  WHERE Value > 0
  )
SELECT SiteMaterialUsageId, WorkcentreId, DeliveryMonth, SUM(Customer) Customer, SUM(System) System, SUM(Orders) Orders,
         SUM(OrdersIncludeSupercessions) OrdersIncludeSupercessions,
         SUM(History) History, SUM(AdjustedHistory) AdjustedHistory,
         SUM(SupersededHistory) SupersededHistory,
         SUM(Indicatives) Indicatives
 FROM   a
 GROUP  BY SiteMaterialUsageId, WorkcentreId, DeliveryMonth
 
top
IHSA#SnapshotPeriodTypes
SELECT 'day' PeriodType, 0 PeriodTypeOrder
FROM dual
UNION ALL
SELECT 'weekmonth' PeriodType, 1 PeriodTypeOrder
FROM dual
UNION ALL
SELECT 'weekmonth2' PeriodType, 2 PeriodTypeOrder
FROM dual
UNION ALL
SELECT 'week' PeriodType,  3 PeriodTypeOrder
FROM dual
UNION ALL
SELECT 'month' PeriodType, 4 PeriodTypeOrder
FROM dual
UNION ALL
SELECT 'quarter' PeriodType, 5 PeriodTypeOrder
FROM dual
UNION ALL
SELECT 'total' PeriodType, 6 PeriodTypeOrder
FROM dual
top
IHSA#SnapshotTables
SELECT 1 AS OrderNo, 'ForecastBodySnapshots' AS TableName, 1 AS HaveStateFieldFlag, 1 AS IsDeleteFlag,  1 AS IsPartitionedTableFlag
FROM   DUAL
UNION ALL
SELECT 2, 'SNPInventorySnapshots', 0, 1, 0
FROM   DUAL
UNION ALL
SELECT 3, 'ScenarioPeriodSnapshots', 0, 1, 0
FROM   DUAL
UNION ALL
SELECT 7, 'ProductionRateSnapshots', 0, 1, 1
FROM   DUAL
UNION ALL
SELECT 12, 'InventorySnapshots', 0, 1, 1
FROM   DUAL
UNION ALL
SELECT 13, 'SNOAllOrderSnapshots', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 14, 'HoldingCostSnapshots', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 15, 'SNOMaterialCoefs', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 16, 'WorkCentreShutSnapshots', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 17, 'CustomerRankSnapshots', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 18, 'SNODemands', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 20, 'ScenarioRates', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 21, 'ScenarioAnalysisSnapshots', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 22, 'ScenarioActions', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 23, 'SNOItems', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 24, 'SiteInventorySnapshots', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 25, 'CoProductPriceSnapshots', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 25, 'CoProductSnapshots', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 26, 'SourcingAllocation', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 27, 'MachineInformation', 0, 0, 1
FROM   DUAL

UNION ALL
SELECT 36, 'MasterRouteSnapshots', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 37, 'ExpandedMasterRouteSnapshots', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 39, 'SNOForecastData', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 40, 'CycleUtilisationSnapshots', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 44, 'SNOInventoryCostData', 0, 1, 0
FROM   DUAL
UNION ALL
SELECT 46, 'SNOSFGInventoryData', 0, 1, 0
FROM   DUAL
UNION ALL
SELECT 47, 'SNOItemsShort', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 51, 'SNOSFGtoFGMapData', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 52, 'SNOSKUWeeklyData', 0, 0, 1
FROM   DUAL
UNION ALL
SELECT 53, 'SNPMaterialRunSnapshots', 0, 0, 0
FROM   DUAL


UNION ALL
SELECT 57, 'SNOPreNettingAllocations', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 57, 'MandatorySnpItemSnapshots', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 60, 'SNOSolutionTempData', 0, 0, 1
FROM   DUAL

UNION ALL

SELECT 61, 'TimeEfficiencySnapshots',  0, 0, 1
FROM   DUAL
UNION ALL
SELECT 63, 'ConfigurationSnapshots', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 64, 'COSTRULESNAPSHOTS', 1, 1, 1
FROM   DUAL
UNION ALL
SELECT 66, 'RealInventoryProfileSnapshot', 0, 1, 1
FROM   DUAL
UNION ALL
SELECT 67, 'MinimumAllocationsSnapshot', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 68, 'WorkCentreParameterSnapshots', 0, 1, 1
FROM  DUAL
UNION ALL
SELECT 69, 'SNOItemCoefs', 0, 1, 1
FROM   DUAL
UNION ALL
SELECT 70, 'SafetyStockSnapshots', 1, 1, 1
FROM   DUAL
UNION ALL
SELECT 71, 'CycleTypeSnapshots', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 71, 'SNPProductionPlanSnapshots', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 72, 'BomMaterialSnapshots', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 73, 'TransportRouteSnapshots', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 74, 'OrderOperationSnapshots', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 76, 'FixedSourceSnapshots', 0, 0, 0
FROM   DUAL
UNION ALL
SELECT 90, 'ExternalAllocationSnapshots', 0, 0, 0
FROM   DUAL
ORDER  BY 1



top
IHSA#SNODemands
SELECT NVL(si.SplitItemId, si.Id) SNPItemId, si.SplitItemId, sd.*, NVL(ur.description, 'Fully Allocated') AllocationStatus,
CASE WHEN Splititemid IS NULL THEN Aggregated - AfterPrenetting + SNoDemand
	   ELSE SNODemand END - DECODE(NVL(sd.CoProductId,0), 0, sd.allocation, 0) UnallocatedVolume,
DECODE(NVL(sd.CoProductId,0), 0, sd.Aggregated, sd.Allocation) PriceVolume,
CASE WHEN Splititemid IS NULL THEN Aggregated - AfterPrenetting + SNoDemand
	   ELSE SNODemand END  DemandIncludeMandatory,
	   DECODE(NVL(sd.CoProductId,0), 0, sd.Aggregated, sd.Allocation) * Price PriceVolume2
FROM   SNODemands sd
LEFT   JOIN UnallocatedReasons ur
ON     ur.Id = sd.Unallocatedreasonid
JOIN SnoItemsShort si
on si.SnapshotUserId = sd.SnapshotUserId
AND si.Id = sd.Id
AND NVL(si.CoProductId,0) = NVL(sd.CoProductId,0)
JOIN CustomerRankSnapshots cr
on cr.SnapshotUserid = si.SnapshotUserId
and cr.ScenarioId = sd.ScenarioId
AND cr.Id = si.Customerrankid
WHERE cr.DisplayInForecast = 1

top
IHSA#SNPItemConfigurations
SELECT SnapshotUserId, si.Id SNPItemId, cs.*
FROM   SNOItems si
JOIN IH#IdenticalConfigurations cs
ON cs.SiteMaterialUsageId = si.SiteMaterialUsageId


top
IHSA#SolutionTempData

SELECT WorkcentreTypeName, wc.LocationId, wc.SiteId, dp.StartPeriod DeliveryDate, sp.StartPeriod SourceDate,
MAX(IsSafetyStock) OVER(Partition by d.SnapshotUserId, RealSNPItemId, AllocationId) UsedSafetyStock,
d.*
FROM   IH#solutiontempdata d
JOIN   IH#Workcentres wc
ON     wc.WorkcentreId = d.WorkcentreId
JOIN   Scenarioperiodsnapshots dp
ON     dp.PeriodNumber = d.Deliveryperiod
AND    dp.SnapshotUserId = d.SnapshotUserId
JOIN   Scenarioperiodsnapshots sp
ON     sp.PeriodNumber = d.SourcePeriod
AND    sp.SnapshotUserId = d.SnapshotUserId
/* WHERE  1 = 1
AND    SnoItemId = 2
*/
top
IHSA#SourcingAllocation View for releasing allocations. Source view for aggregation by required time periods, NULL ScenarioId which used for Order Lines should be replaced by NVL(ScenarioId, ScenarioIdIn) ScenarioId

    SELECT a.SnapshotUserId, a.ScenarioId, a.Id, a.WorkcentreId, case when SIGN(MasterRouteId) = -1 then NULL else MasterRouteId end MasterRouteId, c.SiteMaterialUsageId,
    c.MaterialId,
    a.DeliveryDate DeliveryPeriod, a.SourceDate SourcePeriod,
    a.DeliveryDate - NVL(mr.TimePeriod,0) DispatchPeriod,
    0 AS NonMoveableWeight, a.Allocation * c.Coef AS System,
    a.AllocationId, a.StageNo, a.SeqNo, a.IsLastStage,
    si.PropertyValueId, a.ProductRouteId, a.OperationTypeId, a.NextOperationTypeId, a.SourceMaterialId
    FROM   SourcingAllocation a
    LEFT   JOIN MasterRoutes mr
    ON     mr.Id = a.MasterRouteId
    JOIN SNOItemCoefs c
    ON a.Id = c.Id
    AND a.SnapshotUserId = c.SnapshotUserId
    AND c.DateFrom = a.DeliveryDate
    JOIN SNOItemsShort si
    ON    c.SnapshotUserId = si.SnapshotUserId
    AND    si.Id = a.Id
    AND si.CoProductId IS NULL
    WHERE  a.WorkcentreId IS NOT NULL
    AND a.CoProductId IS NULL
    AND    Allocation > 0
    UNION ALL
    SELECT so.Snapshotuserid, NULL ScenarioId, SnoItemId as id, NVL(so.WorkcentreId, wh.WorkcentreId) WorkcentreId,
    MasterRouteId, so.SiteMaterialUsageId, so.MaterialId,
    DeliveryPeriod,
    SourcePeriod,
    DespatchDate DispatchPeriod,
    so.Weight AS NonMoveableWeight, 0 AS System,
    -1 AllocationId, 0 StageNo, 0 seqNo, IsLastStage,
    so.PropertyValueId,  NULL ProductRouteId, so.OperationTypeId, NULL NextOperationTypeId, NULL SourceMaterialId
    FROM   SNOAllOrderSnapshots so
    LEFT JOIN IH#MainWarehouses wh
    ON wh.SiteId = so.SiteId
    WHERE  so.IsFirm IN (1,2)
    AND    so.CoProductId IS NULL
    AND    so.SourceType IN ('stock', 'production')
    AND    so.PropertyValueId IS NOT NULL
    AND   EXISTS (SELECT 1 FROM SNoItems SI WHERE si.SnapshotUserId = so.SnapshotUserId AND si.SiteMaterialUsageId = so.SiteMaterialUsageId)
    AND   EXISTS (SELECT 1 FROM ForecastbodySnapshots fb WHERE fb.SnapshotState = 1 AND fb.SnapshotUserId = so.SnapshotUserId AND fb.DateFrom = so.DeliveryPeriod
    AND fb.SiteMaterialUsageId = so.SiteMaterialUsageId
    AND so.SourcePeriod IS NOT NULL)

top
IHSA#SourcingAllocation2
SELECT a.SnapshotUserId, a.ScenarioId, a.Id, a.WorkcentreId,
       case when SIGN(MasterRouteId) = -1 then NULL else MasterRouteId end MasterRouteId,
       a.DeliveryDate DeliveryPeriod, a.SourceDate SourcePeriod,
       0 AS NonMoveableWeight, a.Allocation * c.Coef AS System,
       a.AllocationId, a.StageNo, a.IsLastStage,
       a.ProductRouteId, a.OperationTypeId, a.SourceMaterialId, c.MaterialId, si.ReplenishmentFlag
FROM   SourcingAllocation a, SNOMaterialCoefs c, SNOItemsShort si
WHERE  a.Id = c.Id
AND    a.SnapshotUserId = c.SnapshotUserId
AND    a.DeliveryDate = c.Datefrom
AND    c.SnapshotUserId = si.SnapshotUserId
AND    si.Id = a.Id
AND    a.WorkcentreId IS NOT NULL
AND    Allocation > 0
UNION ALL
SELECT so.Snapshotuserid, NULL ScenarioId, SnoItemId as id, WorkcentreId, MasterRouteId,
       DeliveryPeriod,
       SourcePeriod,
       so.Weight AS NonMoveableWeight, 0 AS System,
       -1 AllocationId, 0 StageNo, 1 IsLastStage,
       NULL ProductRouteId, so.OperationTypeId, NULL SourceMaterialId, so.MaterialId, si.ReplenishmentFlag
FROM   SNOAllOrderSnapshots so,  SNOItemsShort si
WHERE  so.IsFirm = 1
AND    so.SnapshotUserId = si.SnapshotUserId
AND    si.Id = so.SnoItemId
AND    so.SourceType IN ('stock', 'production')
AND    so.PropertyValueId IS NOT NULL
AND    so.SourcePeriod IS NOT NULL

top
IHSA#UnallocatedItemDetails
SELECT si.Description SNPItemDescription, SiteName, WorkcentreName, OperationTypeName, ur.Description,
d.* FROM SNPUnallocatedItemDetails d
JOIN IH#Workcentres wc ON wc.WorkcentreID = d.WorkcentreId
JOIN SNOItemsShort SI ON si.Id = d.SNPItemId AND si.SnapshotUserId = d.SnapshotUserId
JOIN UnallocatedReasons ur ON ur.Id = d.unallocatedreasonid
JOIN OperationTypes Ot ON ot.Id = d.OperationTypeId
top
IHSA#WeeklyMonthPeriods Define Periods for SNP mode week/month (hybrid mode)

SELECT CASE WHEN dateWeek > DateMonth THEN DateWeek ELSE DateMonth END StartPeriod,
SUM(1) PeriodLength,
CASE WHEN dateWeek > DateMonth THEN DateWeek ELSE DateMonth END + SUM(1) EndPeriod
FROM IH#DAILYRANGE
GROUP BY CASE WHEN dateWeek > DateMonth THEN DateWeek ELSE DateMonth END
ORDER BY 1

top
IHSA#WorkcentreShutSnapshots
SELECT ws.SnapshotUserId, ws.WorkcentreId, ws.Id, ws.StartDate, ws.FinishDate, sp.StartPeriod, sp.EndPeriod, sp.PeriodNumber,
DECODE(Sign(sp.StartPeriod-ws.StartDate), -1 , ws.StartDate, sp.StartPeriod) NewStartDate,
DECODE(Sign(sp.EndPeriod - ws.FinishDate), -1, (sp.EndPeriod), ws.FinishDate) NewFinishDate,
(DECODE(Sign(sp.EndPeriod - ws.FinishDate), -1, (sp.EndPeriod), ws.FinishDate) -
DECODE(Sign(sp.StartPeriod-ws.StartDate), -1 , ws.StartDate, sp.StartPeriod)) * 24 ShutDurationInHours,
numtodsinterval(DECODE(Sign(sp.EndPeriod - ws.FinishDate), -1, (sp.EndPeriod), ws.FinishDate) -
DECODE(Sign(sp.StartPeriod-ws.StartDate), -1 , ws.StartDate, sp.StartPeriod), 'day') Duration
FROM   WorkCentreShutSnapshots ws, Scenarioperiodsnapshots sp
WHERE  ws.StartDate < sp.EndPeriod
AND    ws.FinishDate > sp.StartPeriod
AND    ws.ScenarioId = -1
AND    ws.SnapshotUserId = sp.SnapshotUserID
top
IM$Characteristics
SELECT propertyName Name, 'EndUseProperty' TYPE, HierarchyLevelNo AS OrderNo FROM ENDUSEPROPERTIES
UNION ALL
SELECT HierarchyLevelName Name, 'Hierarchy' TYPE, HierarchyLevelNo AS OrderNo FROM HierarchyLevels
UNION ALL
SELECT PropertyName Name, 'Property' TYPE, NULL OrderNo FROM Properties
ORDER BY 2,3
top
IM$EndUseProperties
SELECT propertyName Name, HierarchyLevelNo AS OrderNo FROM ENDUSEPROPERTIES
top
IM$HierarchyLevels
SELECT HierarchyLevelName as Name, OrderNo FROM HierarchyLevelsIplanView
top
IM$ProductProperties
SELECT MaterialTypeName TYPE, PropertyName property, HierarchyLevelNo OrderNo, mtp.DefaultValue
FROM MaterialTypes mt JOIN MaterialTypeProperties mtp ON (mt.Id = mtp.MaterialTypeId)
JOIN Properties p ON (p.Id = mtp.PropertyId)
ORDER BY 1,3

top
IM$ProductTypes
SELECT MaterialTypeName Name,
case when IsFinishedGoods = 1 then 'yes' else 'no' end FinishedGoods,
case when IsSingleStage = 1 then 'yes' else 'no' end SingleStage
FROM MaterialTypes
top
IM$Properties
SELECT PropertyName Name, PropertyDesc DESCRIPTION, DataType, DataMask mask, DefaultValue FROM Properties
top
IM$SkuProperties
SELECT propertyName Name, HierarchyLevelNo AS OrderNo FROM SkuPROPERTIES
top
IM$WorkCentreTypes
SELECT wt.WorkCentreTypeName Name,
       wt.WorkCentreTypeDesc Description,
       DECODE(wt.IsValidInitialSource, 1, 'yes', 'no') IsValidSource,
       DECODE(wt.IsProductionSource, 1, 'yes', 'no') IsProductionSource,
       DECODE(wt.HasInventory, 1, 'yes', 'no') HasInventory,
       wt.StageDelayHours,
       wt.MaxStageDelayHours,
       wt.Orderno
  FROM WorkCentreTypes wt
top
IRH#ScenarioAllocation


WITH a AS (
   SELECT sa.ID, sa.CoProductId, sa.ScenarioId, sa.SnapshotUserId, sa.WorkCentreId, sa.Siteid, r.RouteCategory,
          TRUNC(sa.DeliveryDate, 'IW') AS DeliveryWeek,
          TRUNC(sa.DeliveryDate, 'month') as DeliveryMonth,
          TRUNC(sa.DeliveryDate - NVL(r.TimePeriod,0), 'IW') AS DispatchWeek,
          TRUNC(sa.DeliveryDate - NVL(r.TimePeriod,0), 'month') AS DispatchMonth,
          TRUNC(sa.SourceDate, 'IW') AS SourceWeek,
          TRUNC(sa.SourceDate, 'month') as SourceMonth,
          (sa.Allocation / sa.ConversionFactor) AS Allocation,
          CASE WHEN Rate > 0 THEN (sa.Allocation / sa.ConversionFactor) / sa.Rate ELSE 0 END AS AllocationHours,
          0 Orders, 0 OrderHours,
          sa.Revenue, sa.TransportCost, sa.ProductionCost + sa.TransportCost + sa.InventoryCost AS TotalCost, sa.Margin
     FROM SourcingAllocation sa
     LEFT JOIN MasterRouteSnapshots r ON r.SnapshotUserId = sa.SnapshotUserId
                                     AND r.ScenarioId = sa.ScenarioId
                                     AND r.Id = sa.MasterRouteId
    UNION ALL
   SELECT so.SnoItemId, so.CoProductId, s.Id ScenarioId, so.SnapshotUserId, so.WorkCentreId, so.SiteId, r.RouteCategory,
          TRUNC(so.DeliveryPeriod, 'IW') AS DeliveryWeek,
          TRUNC(so.DeliveryPeriod, 'Month') AS DeliveryMonth,
          TRUNC(so.SourcePeriod, 'IW') AS DispatchWeek,
          TRUNC(so.SourcePeriod, 'month') AS DispatchMonth,
          TRUNC(so.SourcePeriod, 'IW') AS SourceWeek,
          TRUNC(so.SourcePeriod, 'month') AS SourceMonth,
          0 Allocation, 0 AllocationHours,
          so.Weight AS Orders, DECODE(so.Rate, 0, 0, so.RemainingSourceWeight / so.Rate) AS OrderHours,
          so.Revenue, so.TransportCost, so.TotalCost, so.Margin
     FROM SNOAllOrderSnapshots so
     JOIN Scenarios s
      ON so.SnapshotUserId = s.SnapshotUserId
     LEFT JOIN MasterRouteSnapshots r ON r.SnapshotUserId = so.SnapshotUserId
                                     AND r.ScenarioId = s.Id
                                     AND r.Id = so.MasterRouteId
    WHERE so.IsFirm IN (1,2)
      AND so.Snoitemid IS NOT NULL
      AND EXISTS(SELECT 1 FROM ScenarioSessions ss
                  WHERE so.RequestedDate BETWEEN ss.StartWeek AND ss.FinishWeek
                    AND so.SnapshotUserId = ss.SnapshotUserId)
      AND so.SourcePeriod IS NOT NULL
),
ab AS (
   SELECT ID, CoProductId, ScenarioId, SnapshotUserId, WorkCentreId, SiteId, RouteCategory,
          DeliveryWeek, DeliveryMonth, DispatchWeek, DispatchMonth, SourceWeek, SourceMonth,
          SUM(Allocation) AS Allocation, SUM(AllocationHours) AS AllocationHours,
          SUM(Orders) AS Orders, SUM(OrderHours) AS OrderHours,
          SUM(Revenue) AS Revenue, SUM(TransportCost) AS TransportCost,
          SUM(TotalCost) AS Cost, SUM(Margin) AS Margin
     FROM a
    GROUP BY ID, CoProductId, ScenarioId, SnapshotUserId, WorkCentreId, SiteId, RouteCategory,
             DeliveryWeek, DeliveryMonth, DispatchWeek, DispatchMonth, SourceWeek, SourceMonth
),
hc as (
  SELECT h.ScenarioId, h.SnapshotUserId, h.SiteId, h.HoldingCost, h.Effective DateFrom,
         NVL(LEAD(h.Effective,1) OVER (PARTITION BY h.ScenarioId, h.SnapshotUserId, h.SiteId ORDER BY h.Effective) - 1, to_date('01.01.2050', 'dd.mm.yyyy')) DateTo
    FROM HoldingCostSnapshots h
)
SELECT ab.ID, ab.CoProductId, ab.ScenarioId, ab.SnapshotUserId, ab.WorkCentreId, ab.SiteId, ab.RouteCategory,
       ab.DeliveryWeek, ab.DeliveryMonth, ab.DispatchWeek, ab.DispatchMonth, ab.SourceWeek, ab.SourceMonth,
       ab.Allocation, ab.AllocationHours, ab.Orders, ab.OrderHours,
       ab.Revenue, ab.TransportCost, ab.Cost, ab.Margin, hc.HoldingCost,
       ROW_NUMBER() OVER (PARTITION BY ab.SnapshotUserId, ab.ScenarioId, ab.DeliveryMonth, ab.DeliveryWeek, ab.Id, ab.CoProductId ORDER BY NULL) LevelNo
  FROM ab
  LEFT JOIN hc ON hc.ScenarioId = ab.ScenarioId
              AND hc.SnapshotUserId = ab.SnapshotUserId
              AND ab.SiteId = hc.SiteId
              AND ab.DeliveryWeek BETWEEN hc.DateFrom AND hc.DateTo

top
IT#Actions
	SELECT a.Id Id, ActionName,
	COALESCE(d1.DictionaryValue, a.ActionDescription) AS ActionDescription,
	COALESCE(d2.DictionaryValue, a.ActionHint) AS ActionHint,
	GridName,
	GridColumnName,
	GridAction,
	Isdefault,
	MULTISELECT,
	Pageid,
	a.Icon,
	a.IsDevMode,
	a.IsEtc,
	GroupName,
	IsVisible,
	a.OverrideActionId,
	a.ParentActionId,
	a.InsertUserId,
	a.InsertDate,
	a.UpdateUserId,
	a.UpdateDate,
	l.Id LanguageId
	FROM   Actions a
	JOIN Pages p ON (p.Id = a.PageId)
	CROSS  JOIN Languages l
	LEFT   JOIN DBDictionaries d1 ON (d1.Dictionarykey = 'Actions.' || p.PageName || '.Description' AND a.Id = d1.TableRowId AND d1.LanguageId = l.Id)
	LEFT   JOIN DBDictionaries d2 ON (d2.Dictionarykey = 'Actions.' || p.PageName || '.Hint' AND a.Id = d2.TableRowId AND d2.LanguageId = l.Id)
	UNION
	SELECT a.Id Id, ActionName,
	COALESCE(d1.DictionaryValue, a.ActionDescription) AS ActionDescription,
	COALESCE(d2.DictionaryValue, a.ActionHint) AS ActionHint,
	GridName,
	GridColumnName,
	GridAction,
	Isdefault,
	MULTISELECT,
	Pageid,
	Icon,
	a.IsDevMode,
	a.IsEtc,
	GroupName,
	IsVisible,
	NULL OverrideActionId,
	NULL ParentActionId,
	a.InsertUserId,
	a.InsertDate,
	a.UpdateUserId,
	a.UpdateDate,
	l.Id LanguageId
	FROM   Actions a
	CROSS  JOIN Languages l
	LEFT  JOIN DBDictionaries d1 ON (d1.Dictionarykey = 'CommonActions.Description' AND a.Id = d1.TableRowId AND d1.LanguageId = l.Id)
	LEFT  JOIN DBDictionaries d2 ON (d2.Dictionarykey = 'CommonActions.Hint' AND a.Id = d2.TableRowId AND d2.LanguageId = l.Id)
	WHERE a.Pageid IS NULL
top
IT#Currencies

SELECT c.Id CurrencyId, CurrencyName, COALESCE(DictionaryValue, CurrencyDescription) AS CurrencyDescription, l.Id LanguageId
FROM   Currencies c
CROSS  JOIN Languages l
LEFT   JOIN DBDictionaries d
ON     (d.Dictionarykey = 'Currencies.Desription' AND c.Id = d.TableRowId AND d.LanguageId = l.Id)

top
IT#CustomerRanks

SELECT cr.Id CustomerRankId, cr.CustomerRankName, COALESCE(DictionaryValue, CustomerRankDesc) AS CustomerRankDesc, l.Id LanguageId
FROM   CustomerRanks cr
CROSS  JOIN Languages l
LEFT   JOIN DBDictionaries d
ON     (d.Dictionarykey = 'CustomerRanks' AND cr.Id = d.TableRowId AND d.LanguageId = l.Id)

top
IT#DataSourceFields
SELECT ds.Name DataSourceName, ds.Title, ds.Description DataSourceDescription, DataSourceId,
       dsf.Id, dsf.Name, COALESCE(d1.DictionaryValue, dsf.Description) AS Description,
       COALESCE(d2.DictionaryValue, dsf.EntityType) AS EntityType,
       dsf.EntityType AS DefaultEntityType, Category, Expression, DataType, OrderNo,
       DefaultFiltered,
       NVL(Filtered, DefaultFiltered) Filtered, Helper, HelperColumn, PARTITION, ParentField, FUNCTION, UnitTypeId, UnitId, CurrencyId,
       IsCurrency, IncludeNullCondition, IsCustomField, IsMandatory,
			 l.Id LanguageId
FROM   (
SELECT df.Id AS TranslateRowId, NVL(ds.Name, d.Name) DataSourceNameForTranslation,
rf.*
FROM DataSourceFields rf
JOIN DataSources d
ON d.Id = rf.DataSourceId
LEFT JOIN DataSourceFields DF
ON df.DataSourceId = NVL(d.ParentDataSourceId, d.Id)
AND UPPER(rf.Name) = UPPER(df.Name)
LEFT JOIN DataSources ds ON ds.Id = NVL(d.ParentDataSourceId, d.Id)
) dsf
JOIN   DataSources ds
ON     ds.Id = dsf.DataSourceId
CROSS  JOIN Languages l
LEFT   JOIN DBDictionaries d1
ON     (d1.Dictionarykey = 'DataSourceFields.' || dsf.DataSourceNameForTranslation || '.Description' AND dsf.TranslateRowId = d1.TableRowId AND
       d1.LanguageId = l.Id)
LEFT   JOIN DBDictionaries d2
ON     (d2.Dictionarykey = 'DataSourceFields.' || dsf.DataSourceNameForTranslation || '.EntityType' AND dsf.TranslateRowId = d2.TableRowId AND
       d2.LanguageId = l.Id)

top
IT#EventMessages

SELECT em.Id EventMessageId, EventName, COALESCE(DictionaryValue, EventDescription) AS EventDescription, l.Id LanguageId
FROM   EventMessages em
CROSS  JOIN Languages l
LEFT   JOIN DBDictionaries d
ON     (d.Dictionarykey = 'EventMessages.Description' AND em.Id = d.TableRowId AND d.LanguageId = l.Id)

top
IT#ForecastMethods

SELECT f.Id ForecastMethodId, f.ForecastMethodName, COALESCE(d.DictionaryValue, f.ForecastMethodDesc) AS ForecastMethodDesc, l.Id LanguageId
FROM   ForecastMethods f
CROSS  JOIN Languages l
LEFT   JOIN DBDictionaries d
ON     (d.Dictionarykey = 'ForecastMethodTypes' AND f.Id = d.TableRowId AND d.LanguageId = l.Id)

top
IT#Navigations
    SELECT nt.TaskName, dsf.Name, NVL(n.DisplayLabel, dsf.Description) description, dsf.DataType, EntityType, Category,
    NVL(n.FreeEntry, DECODE(INITCAP(dsf.DataType), 'String', 1, 0)) IsFreeEntry,
    n.Mandatory IsMandatory, NVL(n.LevelNo, dsf.OrderNo) LevelNo, OrderByField, NVL(Hidden, 0) Hidden,
    DataSourceName, n.Id NavigationLevelId, dsf.Helper, dsf.HelperColumn, dsf.Filtered Filtered,
    NVL(n.DefaultOperation,
           CASE WHEN nt.FilterType = 'Picker' THEN '='
            ELSE DECODE(INITCAP(dsf.DataType), 'String', 'in', '=')
    END ) DefaultOperation, DefaultValue, nt.IsSystem, n.OperationTypeId, n.MaterialTypeId,
		LanguageId
    FROM   IT#DataSourceFields dsf
    JOIN   NavigationTasks nt
    ON     (UPPER(dsf.DataSourceName) = UPPER(nt.Source))
    LEFT   JOIN Navigations n
    ON     (UPPER(n.LevelName) = UPPER(dsf.Name) AND n.TaskName = nt.TaskName)
    ORDER  BY UPPER(TaskName), LevelNo

top
IT#OrderLineReasons

SELECT r.Id ReasonId, r.Reason ReasonName, COALESCE(DictionaryValue, ReasonDescription) AS ReasonDesc, l.Id LanguageId
FROM   Reasons r
CROSS  JOIN Languages l
LEFT   JOIN DBDictionaries d
ON     (d.Dictionarykey = 'Reasons' AND r.Id = d.TableRowId AND d.LanguageId = l.Id)
WHERE r.ReasonType = 'OrderLine'

top
IT#PageParameters
SELECT pp.Id, ParameterName, COALESCE(DictionaryValue, ParameterDescription) AS ParameterDescription, l.Id LanguageId, pp.IsDevMode
FROM   PageParameters pp
CROSS  JOIN Languages l
JOIN Pages p ON (p.Id = pp.PageId)
LEFT   JOIN DBDictionaries d
ON     (d.Dictionarykey = 'PageParameters' AND pp.Id = d.TableRowId AND d.LanguageId = l.Id)
top
IT#Pages
SELECT p.ID, PageName, COALESCE(d1.DictionaryValue, p.PageDescription) AS PAgeDescription,
       COALESCE(d2.DictionaryValue, p.PageHint) AS PAgeHint, IsBasePage,
       ShowAlways, HelpRef, Cloud, BlockedTasks, CloudParentPageId, p.InsertUserId,
       p.InsertDate, p.UpdateUserId, p.UpdateDate, l.Id LanguageId, p.IsDevMode, p.Icon
FROM   Pages p
CROSS  JOIN Languages l
LEFT   JOIN DBDictionaries d1
ON     (d1.Dictionarykey = 'Pages.Description' AND p.Id = d1.TableRowId AND d1.LanguageId = l.Id)
LEFT   JOIN DBDictionaries d2
ON     (d2.Dictionarykey = 'Pages.Hint' AND p.Id = d2.TableRowId AND d2.LanguageId = l.Id)
top
IT#ProcessParts

SELECT pp.Id as ProcessPartId, pp.ProcessPartName, COALESCE(d.DictionaryValue, pp.ProcessPartDesc) AS ProcessPartDesc, l.Id LanguageId
FROM   ProcessParts pp
CROSS  JOIN Languages l
LEFT   JOIN DBDictionaries d
ON     (d.Dictionarykey = 'ProcessParts' AND pp.Id = d.TableRowId AND d.LanguageId = l.Id)

top
IT#Roles

SELECT r.Id RoleId, RoleName, COALESCE(DictionaryValue, RoleDescription) AS RoleDescription, IsAdmin, IsInternal,
r.InsertUserId,
r.InsertDate,
r.UpdateUserId,
r.UpdateDate,
l.Id LanguageId
FROM   Roles r
CROSS  JOIN Languages l
LEFT   JOIN DBDictionaries d
ON     (d.Dictionarykey = 'Roles.Description' AND r.Id = d.TableRowId AND d.LanguageId = l.Id)

top
IT#SafetyStockMethods

SELECT s.Id SafetyStockMethodId, s.SafetyStockMethodName, COALESCE(d.DictionaryValue, s.SafetyStockMethodDesc) AS SafetyStockMethodDesc, l.Id LanguageId
FROM   SafetyStockMethods s
CROSS  JOIN Languages l
LEFT   JOIN DBDictionaries d
ON     (d.Dictionarykey = 'SafetyStockMethods' AND s.Id = d.TableRowId AND d.LanguageId = l.Id)

top
IT#Tasks

SELECT t.Id as TaskId, t.TaskName, COALESCE(d.DictionaryValue, t.Description) AS TaskDesc, l.Id LanguageId
FROM   Tasks t
CROSS  JOIN Languages l
LEFT   JOIN DBDictionaries d
ON     (d.Dictionarykey = 'Tasks' AND t.Id = d.TableRowId AND d.LanguageId = l.Id)

top
IT#Units

SELECT u.Id Id, UnitName, COALESCE(DictionaryValue, UnitDescription) AS UnitDescription, l.Id LanguageId
FROM   Units u
CROSS  JOIN Languages l
LEFT   JOIN DBDictionaries d
ON     (d.Dictionarykey = 'Units' AND u.Id = d.TableRowId AND d.LanguageId = l.Id)


top
IV#CostRules
SELECT cr.*, wc.SiteName, wc.WorkcentreName, ot.OperationTypeName,
d.Code1, d.Code2, d.Code3, d.Code4, d.Code5, d.Code6, d.Code7, d.Code8, d.Code9, d.Code10,
d.Code11, d.Code12, d.Code13, d.Code14, d.Code15, d.Code16, d.Code17, d.Code18, d.Code19, d.Code20,
d.Code21, d.Code22, d.Code23, d.Code24, d.Code25, d.Code26, d.Code27, d.Code28, d.Code29, d.Code30,
 NVL(LEAD(Effective) OVER(PARTITION BY cr.WorkcentreId, cr.OperationTypeId, cr.DetailId ORDER BY cr.Effective) - 1,
            to_date('2100-01-01', 'YYYY-MM-DD')) EffectiveTo,
CASE WHEN TRUNC(core.getInternalDate) BETWEEN Effective AND NVL(LEAD(Effective) OVER(PARTITION BY cr.WorkcentreId, cr.OperationTypeId, cr.DetailId ORDER BY cr.Effective),
            to_date('2100-01-01', 'YYYY-MM-DD')) THEN 1 ELSE 0 END IsActive

FROM CostRules cr
JOIN HierarchyPropertyDetails d ON (d.Id = cr.DetailId)
JOIN IH#Workcentres wc ON wc.WorkcentreId = cr.WorkcentreId
LEFT JOIN OperationTypes ot ON ot.Id = cr.OperationTypeId
top
IV#DataSourceFilters
SELECT rf.Id, rf.Code, rf.IsShared, rf.Logic, rf.HashCode, rf.ToolTip, rf.SqlText, dsf.DataSourceId, dsf.Name, dsf.UserId
FROM   ReportFilters rf
JOIN   DataSourceFilters dsf
ON     (dsf.ReportFilterId = rf.Id)
top
IV#Hierarchies
SELECT HierarchyId,

RTRIM(NVL2(HierarchyName1, HierarchyName1 || ' / ', '') ||
NVL2(HierarchyName2, HierarchyName2 || ' / ', '') ||
NVL2(HierarchyName3, HierarchyName3 || ' / ', '') ||
NVL2(HierarchyName4, HierarchyName4 || ' / ', '') ||
NVL2(HierarchyName5, HierarchyName5 || ' / ', '') ||
NVL2(HierarchyName6, HierarchyName6 || ' / ', '') ||
NVL2(HierarchyName7, HierarchyName7 || ' / ', '') ||
NVL2(HierarchyName8, HierarchyName8 || ' / ', '') ||
NVL2(HierarchyName9, HierarchyName9 || ' / ', '') ||
NVL2(HierarchyName10, HierarchyName10 || ' / ', '') ||
NVL2(HierarchyName11, HierarchyName11 || ' / ', '') ||
NVL2(HierarchyName12, HierarchyName12 || ' / ', '') ||
NVL2(HierarchyName13, HierarchyName13 || ' / ', '') ||
NVL2(HierarchyName14, HierarchyName14 || ' / ', '') ||
NVL2(HierarchyName15, HierarchyName15 || ' / ', ''), ' / ') Hierarchies
FROM   Expandedhierarchiesspec
top
IV#MaterialProperties
SELECT em.MaterialId, pv.PropertyValueCode, Value, pv.PropertyId, p.PropertyName, mtp.Hierarchylevelno, m.MaterialTypeId
FROM ExpandedMaterials em
jOIN PropertyValues pv ON (pv.Id = em.Propertyvalueid)
JOIN Materials m ON (m.Id = em.MaterialId)
JOIN Properties p ON (p.Id = pv.PropertyId)
JOIN MaterialTypeProperties mtp ON (mtp.MaterialTypeId = m.MaterialTypeId AND p.Id = mtp.PropertyId)
ORDER BY em.MaterialID, mtp.Hierarchylevelno
top
IV#MAterials
  SELECT mt.MaterialTypeName,
m.* FROM materials m JOIN MaterialTypes mt ON (mt.Id = m.MaterialtypeId)
top
IV#PriceRules
SELECT pr.*, LocationCode, ProductCode, EndUseCode, EndCustomerCode,
d.Code1, d.Code2, d.Code3, d.Code4, d.Code5, d.Code6, d.Code7, d.Code8, d.Code9, d.Code10,
d.Code11, d.Code12, d.Code13, d.Code14, d.Code15, d.Code16, d.Code17, d.Code18, d.Code19, d.Code20,
d.Code21, d.Code22, d.Code23, d.Code24, d.Code25, d.Code26, d.Code27, d.Code28, d.Code29, d.Code30,
HierarchyCode1, HierarchyCode2, HierarchyCode3, HierarchyCode4, HierarchyCode5,
HierarchyCode6, HierarchyCode7, HierarchyCode8, HierarchyCode9, HierarchyCode10,
HierarchyCode11, HierarchyCode12, HierarchyCode13, HierarchyCode14, HierarchyCode15,
 NVL(LEAD(Effective) OVER(PARTITION BY pr.DetailId ORDER BY pr.Effective) - 1,
            to_date('2100-01-01', 'YYYY-MM-DD')) EffectiveTo,
CASE WHEN TRUNC(core.getInternalDate) BETWEEN Effective AND NVL(LEAD(Effective) OVER(PARTITION BY pr.DetailId ORDER BY pr.Effective),
            to_date('2100-01-01', 'YYYY-MM-DD')) THEN 1 ELSE 0 END IsActive
FROM PriceRules pr
JOIN HierarchyPropertyDetails d ON (d.Id = pr.DetailId)
top
IV#ProductionRates
SELECT pr.*, wc.SiteName, wc.WorkcentreName, ot.OperationTypeName,
d.Code1, d.Code2, d.Code3, d.Code4, d.Code5, d.Code6, d.Code7, d.Code8, d.Code9, d.Code10,
d.Code11, d.Code12, d.Code13, d.Code14, d.Code15, d.Code16, d.Code17, d.Code18, d.Code19, d.Code20,
d.Code21, d.Code22, d.Code23, d.Code24, d.Code25, d.Code26, d.Code27, d.Code28, d.Code29, d.Code30,
 NVL(LEAD(Effective) OVER(PARTITION BY pr.WorkcentreId, pr.OperationTypeId, pr.DetailId ORDER BY pr.Effective) - 1,
            to_date('2100-01-01', 'YYYY-MM-DD')) EffectiveTo,
CASE WHEN TRUNC(core.getInternalDate) BETWEEN Effective AND NVL(LEAD(Effective) OVER(PARTITION BY pr.WorkcentreId, pr.OperationTypeId, pr.DetailId ORDER BY pr.Effective),
            to_date('2100-01-01', 'YYYY-MM-DD')) THEN 1 ELSE 0 END IsActive

FROM ProductionRates pr
JOIN HierarchyPropertyDetails d ON (d.Id = pr.DetailId)
JOIN IH#Workcentres wc ON wc.WorkcentreId = pr.WorkcentreId
LEFT JOIN OperationTypes ot ON ot.Id = pr.OperationTypeId


top
IV#PropertyValues
SELECT PropertyValueId,

RTRIM(NVL2(Value1, Value1 || ' / ', '') ||
NVL2(Value2, Value2 || ' / ', '') ||
NVL2(Value3, Value3 || ' / ', '') ||
NVL2(Value4, Value4 || ' / ', '') ||
NVL2(Value5, Value5 || ' / ', '') ||
NVL2(Value6, Value6 || ' / ', '') ||
NVL2(Value7, Value7 || ' / ', '') ||
NVL2(Value8, Value8 || ' / ', '') ||
NVL2(Value9, Value9 || ' / ', '') ||
NVL2(Value10, Value10 || ' / ', '') ||
NVL2(Value11, Value11 || ' / ', '') ||
NVL2(Value12, Value12 || ' / ', '') ||
NVL2(Value13, Value13 || ' / ', '') ||
NVL2(Value14, Value14 || ' / ', '') ||
NVL2(Value15, Value15 || ' / ', '') ||

NVL2(Value16, Value16 || ' / ', '') ||
NVL2(Value17, Value17 || ' / ', '') ||
NVL2(Value18, Value18 || ' / ', '') ||
NVL2(Value19, Value19 || ' / ', '') ||
NVL2(Value20, Value20 || ' / ', '') ||
NVL2(Value21, Value21 || ' / ', '') ||
NVL2(Value22, Value22 || ' / ', '') ||
NVL2(Value23, Value23 || ' / ', '') ||
NVL2(Value24, Value24 || ' / ', '') ||
NVL2(Value25, Value25 || ' / ', '') ||
NVL2(Value26, Value26 || ' / ', '') ||
NVL2(Value27, Value27 || ' / ', '') ||
NVL2(Value28, Value28 || ' / ', '') ||
NVL2(Value29, Value29 || ' / ', '') ||
NVL2(Value30, Value30 || ' / ', ''), ' / ') Properties
FROM   Propertyvaluesspec
top
IV#RangeProperties
SELECT DISTINCT MaterialId, WorkcentreId
FROM
(
SELECT em.MaterialId, pv.Value, pv.PropertyId, r.WorkcentreId, r.rangefrom, r.RangeTo FROM ExpandedMaterials em
JOIN PropertyValues pv ON pv.Id = em.PropertyValueId
JOIN Properties p ON (p.Id = pv.PropertyID AND p.DataType = 'Integer')
LEFT JOIN ReplenishmentRestrictions r ON r.PropertyID = pv.PropertyId
WHERE to_number(pv.Value) BETWEEN NVL(RANGEFrom,0) AND NVL(RangeTo, 9999999999999)
)
WHERE WorkcentreId IS NOT NULL
top
IV#WorkcentreRangeProperties
SELECT r.Id, wc.WorkcentreId, p.PropertyId, p.PropertyDesc, r.Rangefrom, r.RangeTo FROM
(
SELECT * FROM IH#Workcentres WHERE IsProductionSource = 1) wc
CROSS JOIN
(SELECT Id PropertyId, PropertyDesc FROM properties WHERE datatype = 'Integer') p
LEFT JOIN ReplenishmentRestrictions r ON r.WorkcentreId = wc.WorkcentreId AND p.PropertyId = r.PropertyId
top
IVBS#ActualProductionRates

WITH rates AS
 (SELECT pr.*, l.SiteId, ROW_NUMBER() OVER(PARTITION BY WorkcentreId, OperationTypeId, ProductionRateCode ORDER BY Effective DESC) r
  FROM   ProductionRates pr
  JOIN Workcentres wc on wc.Id = pr.WorkcentreId
  JOIN Locations l on l.Id = wc.LocationId
),
pairs AS
(
SELECT Id, WorkcentreId, SiteId, Effective, ProductionRateCode, OperationTypeId, Rate, TimeEfficiency, MaterialEfficiency, SpecificWeight, ConversionFactor,
       MaterialId, d.Priority,
       ROW_NUMBER() OVER(PARTITION BY WorkcentreId, OperationTypeId, MaterialId ORDER BY Effective, Priority DESC) OrderNo
FROM   Rates r
JOIN   Ih#detailsmaterial d
ON     r.Detailid = d.DetailId
AND r.r = 1)
SELECT * FROM pairs
WHERE Rate > 0
AND OrderNo = 1

top
IVBS#MaterialRuns
SELECT mr.Quantity - NVL(oo.Weight,0) FreeCapacity, mr.*
FROM MaterialRuns mr
LEFT JOIN 
(
  SELECT oo.MaterialRunId, SUM(oo.RemainingQuantity) AS Weight
    FROM IH#OrderDuration oo 
   WHERE oo.MaterialRunId IS NOT NULL
     AND oo.OrderOperationStatusCode IN ('Firm', 'Completed')
   GROUP BY oo.MaterialRunId
) oo ON oo.MaterialRunId = mr.Id
top
IVDP#HistoryData
SELECT hd.SiteMaterialUSageId,
       l.LocationCode, m.MaterialCode,
       l.LocationName, m.MaterialName,
       eu.EndUseCode, eu.EndUseDescription,
       ec.LocationCode EndCustomerCode, ec.LocationName EndCustomerName,
       StartDate,
       DateFrom,
       Weight,
       l.LocationCode || ' / ' || m.MaterialCode SkuCode,
       l.LocationName || ' / ' || m.MaterialName SkuName
  FROM HistoryData hd
  JOIN SiteMaterialUsages smu ON hd.Sitematerialusageid = smu.Id
  JOIN Locations l ON l.Id = smu.LocationId
  JOIN Materials m ON m.Id = smu.MaterialId
  LEFT JOIN EndUses eu ON eu.Id = smu.EndUseId
  LEFT JOIN Locations ec ON ec.Id = smu.EndCustomerId
 ORDER BY l.LocationCode, m.MaterialCode, eu.EndUseCode, ec.LocationCode, StartDate, DateFrom
top
IVDP#HistoryStartDate
SELECT t.SiteMaterialUsageId, NVL(smu.HistoryStartDate, MIN(FirstHistoryDate)) HistoryDate
FROM   (

    SELECT uh.SiteMaterialUsageId, MIN(Trunc(uh.DateFrom, 'month')) AS FirstHistoryDate
    FROM   UsageHistories uh
    WHERE NVL(uh.AdjustedWeight, uh.Weight) > 0
    group by SiteMaterialUsageId
    UNION ALL
    SELECT ms.OnSiteMaterialUsageId,  MIN(Trunc(uh.DateFrom, 'month')) AS FirstHistoryDate
    FROM   UsageHistories uh
    JOIN   IH#MaterialSupercessions ms
    ON     (uh.SiteMaterialUsageId = ms.SiteMaterialUSageId AND ms.Status = 0)
    group by ms.OnSiteMaterialUsageId
) t
JOIN SiteMaterialUsages smu
ON smu.Id = t.SiteMaterialUsageId

GROUP BY t.SiteMaterialUsageId, smu.HistoryStartDate
top
IVDP#UsageHistories
SELECT hd.SiteMaterialUSageId,
       l.LocationCode, m.MaterialCode,
       l.LocationName, m.MaterialName,
       eu.EndUseCode, eu.EndUseDescription,
       ec.LocationName EndCustomerName, ec.LocationCode EndCustomerCode,
       DateFrom,
       Weight,
       AdjustedWeight,
       NVL(AdjustedWeight, Weight) Quantity,
       l.LocationCode || ' / ' || m.MaterialCode SkuCode,
       l.LocationName || ' / ' || m.MaterialName SkuName
  FROM UsageHistories hd
  JOIN IH#CUSTOMERSKUS smu ON hd.Sitematerialusageid = smu.SiteMaterialUSageId
  JOIN Locations l ON l.Id = smu.LocationId
  JOIN Materials m ON m.Id = smu.MaterialId
  LEFT JOIN EndUses eu ON eu.Id = smu.EndUseId
  LEFT JOIN Locations ec ON eu.Id = smu.EndCustomerId
 ORDER BY l.LocationCode, m.MaterialCode, eu.EndUseCode, ec.LocationCode, DateFrom
top
IVMP#Indicatives

SELECT SiteMaterialUsageId, GradeId, WorkcentreId, SiteId,
        DeliveryMonth, DeliveryWeek,
        SUM(OrdersWeight) OrdersWeight,
        SUM(Allocation) Allocation
FROM   (
       SELECT SiteMaterialUsageId, GradeId, ab.WorkcentreId, wc.SiteId, DeliveryMonth,
                DeliveryWeek, 0 OrdersWeight, VALUE Allocation
         FROM   Indicatives ab
         JOIN   SiteMaterialUsages smu
         ON     ab.SiteMaterialUsageId = smu.Id
         JOIN   GradeMaterials gm
         ON     smu.MaterialId = gm.MaterialId
         JOIN   IH#Workcentres wc
         ON     ab.WorkcentreId = wc.WorkcentreId
         UNION ALL
         SELECT NVL(ms.OnSiteMaterialUsageId, ol.SiteMaterialUsageId), GradeId, ol.WorkcentreId, wc.SiteId,
                Trunc(DeliveryDate, 'Month') DeliveryMonth, Trunc(DeliveryDate, 'IW') DeliveryWeek,
                FinalWeight / NVL(ConversionFactor, 1) OrdersWeight,
                0 Allocation
         FROM   OrderLines ol
         JOIN   GradeMaterials gm
         ON     ol.SourceMaterialId = gm.MaterialId
         JOIN   OrderLineStatuses ols
         ON     ol.OrderLineStatusId = ols.Id
         JOIN   IH#Workcentres wc
         ON     ol.WorkcentreId = wc.WorkcentreId
         LEFT   JOIN IH#MaterialSupercessions ms
         ON     ms.SiteMaterialUsageId = ol.SiteMaterialUsageId
         AND    Status = 0
         LEFT   JOIN IVBS#ActualProductionRates r
         ON     r.WorkcentreId = ol.WorkcentreId
         AND    r.MaterialId = NVL(ms.ToMaterialId, ol.MaterialId)
         WHERE  ols.OrderLineStatusCode IN ('Firm', 'Completed')
				 AND OrderType = 'Customer'
				 )
GROUP  BY SiteMaterialUsageId, GradeId, WorkcentreId, SiteId,  DeliveryMonth, DeliveryWeek
top
IVMP#LiveAllocations
SELECT SiteMaterialUsageId, WorkcentreId, SiteId, OperationTypeId, MaterialId, SourceMonth, SourceWeek, DeliveryMonth, DeliveryWeek, AllocationId,
SUM(OrdersWeight) OrdersWeight, SUM(SystemOrdersWeight) SystemOrdersWeight, SUM(RevisedAllocation) RevisedAllocation,
SUM(Allocation) Allocation
FROM
(
SELECT SiteMaterialUsageId, ab.WorkcentreId, ab.OperationTypeId, wc.SiteId, smu.MaterialId, SourceMonth, SourceWeek, DeliveryMonth, DeliveryWeek,
       0 OrdersWeight, 0 SystemOrdersWeight,
       Revised RevisedAllocation, Customer / DECODE(wc.WorkcentreTypeName, 'Paper Machine', ConversionFactor, 1) Allocation, ab.Id AllocationId
  FROM AllocationBodies ab
  JOIN SiteMaterialUsages smu ON ab.SiteMaterialUsageId = smu.Id
  JOIN IH#Workcentres wc ON ab.WorkcentreId = wc.WorkcentreId
 UNION ALL
SELECT NVL(ms.OnSiteMaterialUsageId, ol.SiteMaterialUsageId), NVL(ol.WorkcentreId, wh.WorkcentreId) WorkcentreId,
       r.OperationTypeId, NVL(wc.SiteId, ol.SiteId) SiteId,
       ol.MaterialId MaterialId, Trunc(NVL(ol.ConsumptionDate, ol.DespatchDate), 'Month') SourceMonth,
       Trunc(NVL(ol.ConsumptionDate, ol.DespatchDate), 'IW') SourceWeek, Trunc(DeliveryDate, 'Month') DeliveryMonth,
       Trunc(DeliveryDate, 'IW') DeliveryWeek,
       DECODE(ols.OrderLineStatusCode, 'Firm', FinalWeight / NVL(ConversionFactor, 1), 0) OrdersWeight,
       DECODE(ols.OrderLineStatusCode, 'System', FinalWeight / NVL(ConversionFactor, 1), 0) SystemOrdersWeight,
       0 RevisedAllocation, 0 Allocation, 0 AllocationId
  FROM OrderLines ol
  JOIN OrderLineStatuses ols ON ol.OrderLineStatusId = ols.Id
  LEFT JOIN IH#Workcentres wc ON ol.WorkcentreId = wc.WorkcentreId
  LEFT JOIN IH#MainWarehouses wh ON wh.SiteId = ol.SiteId
  LEFT JOIN IH#MaterialSupercessions ms ON ms.SiteMaterialUsageId = ol.SiteMaterialUsageId AND Status = 0
  LEFT JOIN IVBS#ActualProductionRates r ON r.WorkcentreId = ol.WorkcentreId AND r.MaterialId = NVL(ms.ToMaterialId, ol.MaterialId)
 WHERE ols.OrderLineStatusCode IN ('Firm', 'System')
)
GROUP BY SiteMaterialUsageId, WorkcentreId, OperationTypeId, MaterialId, SiteId, SourceMonth, SourceWeek, DeliveryMonth, DeliveryWeek, AllocationId
top
IVMP#TransportAllocations
WITH t AS
 (SELECT ab.SiteMaterialUsageId, ab.WorkCentreId, ab.MasterRouteId, wc.LocationId SourceLocationId, wc.SiteId,
         ab.DeliveryWeek, ab.DeliveryMonth, Trunc(ab.DeliveryWeek - NVL(mr.TimePeriod, 0), 'Month') DespatchMonth,
         Trunc(ab.DeliveryWeek - NVL(mr.TimePeriod, 0), 'IW') DespatchWeek, ab.SourceWeek, ab.SourceMonth,
         Customer / NVL(ConversionFactor,1) AS Allocation, 0 Orders,
         0 SourceWeight, 0 RemainingWeight, 0 RemainingSourceWeight, 'CUST' DestinationType,
         CASE wc.WorkCentreTypeName
              WHEN 'Paper Machine' THEN
               'PM'
              WHEN 'SemiFinishingWarehouse' THEN
               'SFG'
              ELSE
               'FG'
          END AS SourceType
  FROM  AllocationBodies ab
  JOIN IH#Workcentres wc ON wc.WorkcentreID = ab.workcentreId
  LEFT   JOIN MasterRoutes mr
  ON     mr.Id = ab.MasterRouteId
  where ab.DeliveryMonth >= (SELECT MIN(TRUNC(core.getInternalDate)) - 93 FROM dual)
  UNION ALL
  SELECT ol.SiteMaterialUsageId, ol.WorkCentreId, mr.Id MasterRouteId, sw.LocationId SourceLocationId, sw.SiteId,
         Trunc(DeliveryDate, 'Month') DeliveryMonth, Trunc(DeliveryDate, 'IW') DeliveryWeek,
         Trunc(DespatchDate, 'Month') DespatchMonth, Trunc(DespatchDate, 'IW') DespatchWeek,
         Trunc(ol.DespatchDate, 'Month') SourceMonth, Trunc(ol.DespatchDate, 'IW') SourceWeek, 0 Allocation,
         ol.FinalWeight / NVL(ConversionFactor,1) AS Orders, ol.SourceWeight,
         GREATEST(0, ol.FinalWeight - GREATEST(ol.WeightComplete, ol.DeliveryWeight)) AS RemainingWeight,
         GREATEST(0,
                   ol.SourceWeight - GREATEST(ol.WeightIssued, ol.WeightComplete * ol.SourceCoef, ol.DeliverySourceWeight))
									  AS RemainingSourceWeight,
         CASE dw.WorkCentreTypeName
              WHEN 'SemiFinishingWarehouse' THEN
               'SFG'
              WHEN 'Warehouse' THEN
               'FG'
              ELSE
               'CUST'
          END AS DestinationType,
         CASE sw.WorkCentreTypeName
              WHEN 'Paper Machine' THEN
               'PM'
              WHEN 'SemiFinishingWarehouse' THEN
               'SFG'
              ELSE
               'FG'
          END AS SourceType
  FROM   OrderLines ol
  JOIN   OrderLineStatuses ols
  ON     ols.Id = ol.OrderLineStatusId
  AND    ols.OrderLineStatusCode IN ('Firm')
  JOIN   IH#WorkCentres sw
  ON     sw.WorkCentreId = ol.WorkCentreId
  LEFT JOIN IVBS#ActualProductionRates r
     ON r.WorkcentreId = ol.WorkcentreId
		 and r.MaterialId = ol.MaterialId
  LEFT   JOIN IH#WorkCentres dw
  ON     dw.LocationId = ol.LocationId
  LEFT   JOIN (SELECT mr.Id, mr.Cost, mr.TimePeriod, mr.FromSiteId, d.LocationId ToLocationId,
                     DENSE_RANK() OVER(PARTITION BY mr.FromSiteId, d.LocationId ORDER BY mr.TimePeriod, mr.Id DESC) r
              FROM   MasterRoutes mr
              JOIN   IH#DetailsLocation d
              ON     d.DetailId = mr.DetailId) mr
  ON     mr.ToLocationId = ol.LocationId
  AND    mr.FromSiteId = sw.SiteId
  AND    mr.r = 1
  WHERE DeliveryDate >= (SELECT MIN(TRUNC(core.getInternalDate)) - 93 FROM dual)
)
SELECT SiteMaterialUsageId, WorkCentreId, MasterRouteId, SourceLocationId, SiteId, DeliveryWeek, DeliveryMonth,
       DespatchWeek, DespatchMonth, SourceWeek, SourceMonth, SUM(Allocation) Allocation, SUM(Orders) Orders,
       SUM(SourceWeight) SourceWeight, SUM(RemainingWeight) RemainingWeight,
       SUM(RemainingSourceWeight) RemainingSourceWeight, DestinationType, SourceType
FROM   t
GROUP  BY SiteMaterialUsageId, WorkCentreId, MasterRouteId, SourceLocationId, SiteId, DeliveryWeek, DeliveryMonth,
          DespatchWeek, DespatchMonth, SourceWeek, SourceMonth, DestinationType, SourceType
top
IVRP#MaterialRunProducts
SELECT mrp.MaterialRunId, rp.RunProductId, p.PropertyName, rp.PropertyValueCode
FROM MaterialRunProducts mrp
JOIN Materialrunproperties rp
ON rp.RunProductId = mrp.Id
JOIN Properties p ON p.Id = rp.PropertyId
top
IVRP#MaterialRuns
SELECT BlockCode, RunCode, WorkCentreCode, mr.Id, mr.StartDate, mr.FinishDate
FROM   MaterialRuns mr
JOIN   MaterialBlocks mb
ON     mr.Materialblockid = mb.Id
JOIN   Workcentres wc
ON     mr.Workcentreid = wc.Id
top
IVRP#OrderInformation
SELECT
oi.OrderLineId,
oi.Type,
i.Type ValueType,
i.Value,
oi.Type || '.' || i.Type DictionaryKey,
i.Value DictionaryValue
from OrderInformation oi
LEFT JOIN OrderInformationItems i
ON (oi.Id = i.OrderInformationId)
top
IVRP#OrderLines
SELECT OrderCode,
fcs.LocationCode FromConsignmentLocationCode,
tcs.LocationCode ToConsignmentLocationCode,
m.MaterialCode,
l.LocationCode,
l.LocationName,
tm.TransportMethodCode,
j.journeyCode,
s.SiteCode,
wc.WorkcentreCode,
ols.OrderLineStatusName,
mt.Materialtypename MaterialTypeName,
smt.Materialtypename SourceMaterialTypeName,
Round(ol.FinalWeight * DECODE(ol.UnitId, su.UnitId, COALESCE(ol.Dividend, su.Dividend, 0) / COALESCE(ol.Divisor, su.Divisor, 1), NVL(su.Dividend, 0) / NVL(su.Divisor, 1)), 0) as QuantityInUnits,
am.ExistingAlternateName AlternateProductCode,
su.UnitName,
ol.*
from OrderLines ol
join OrderBooks o ON (o.Id = ol.OrderBookId)
JOIN Locations l ON (ol.LocationId = l.ID)
JOIN Materials m ON (m.Id = ol.MaterialId)
LEFT JOIN Workcentres wc ON wc.Id = ol.WorkcentreId
LEFT JOIN Sites s ON s.Id = ol.SiteId
JOIN MaterialTypes mt ON (mt.ID = m.MaterialTypeId)
JOIN OrderLineStatuses ols ON (ols.Id = ol.OrderLineStatusId)
LEFT JOIN TransportMethods tm ON (tm.ID = ol.TransportMethodId)
LEFT JOIN (SELECT mu.*, u.UnitName FROM materialUnits mu JOIN Units u ON (u.Id = mu.UnitId) WHERE u.IsBaseUnit = 1) su on (ol.MaterialId = su.MaterialId)
LEFT JOIN Locations fcs ON (fcs.ID = ol.FromConsignmentlocationId)
LEFT JOIN Locations tcs ON (tcs.ID = ol.ToConsignmentlocationId)
LEFT JOIN Journeys j ON (j.ID = ol.JourneyId AND IsInternal = 0)
LEFT JOIN Materials sm ON (sm.Id = ol.SourceMaterialId)
LEFT JOIN MaterialTypes smt ON (smt.ID = sm.MaterialTypeId)
LEFT JOIN AlternateMaterialsIPlanView am ON am.Id = ol.SiteMaterialUsageId AND NVL(am.ConsignmentLocationId, 0) = NVL(ol.ToConsignmentLocationId, 0)

	
top
IVRP#OrderOperations
SELECT
wc.WorkcentreCode,
ols.OrderOperationStatusName,
ols.OrderOperationStatusCode,
BlockCode,
RunCode,
oo.*
from OrderOperations oo
JOIN Workcentres wc ON (wc.Id = oo.WorkcentreId)
JOIN OrderOperationStatuses ols ON (ols.Id = oo.OrderOperationStatusId)
LEFT JOIN MaterialRuns mr ON (mr.Id = oo.MaterialRunId)
LEFT JOIN MaterialBlocks mb ON (mb.Id = mr.MaterialBlockId)
top
IVSA#DemandAllocations

SELECT sa.SourceDate, sa.SourceDate SourceMonth, sa.DeliveryDate, sa.DeliveryDate DeliveryMonth, sa.ID, sa.ScenarioId, sa.SnapshotUserId, sd.Aggregated,
sd.nonmoveablefirm, sa.Allocation, WorkcentreId, SiteId,
sa.ProductionCost, sa.TransportCost, sa.InventoryCost
FROM   (
SELECT SourceDate, SourceDate SourceMonth, DeliveryDate, DeliveryDate DeliveryMonth, sa.ID, ScenarioId, SnapshotUserId, WorkcentreId, SiteId,
SUM(Allocation) Allocation,
SUM(ProductionCost) ProductionCost,
SUM(TransportCost) TransportCost,
SUM(InventoryCost) InventoryCost
FROM SourcingAllocation sa
GROUP BY SourceDate, DeliveryDate, sa.ID, ScenarioId, SnapshotUserId, WorkcentreId, SiteId
) sa
JOIN ScenarioSessions ss
ON ss.SnapshotUserId = sa.SnapshotUserId
JOIN SNoDemands sd
ON sd.SnapshotUserId = sa.SnapshotUserId
AND sd.ScenarioID = sa.ScenarioId
AND sd.Datefrom = sa.DeliveryDate
AND sd.Id = sa.Id
top
IVSA#PaperMachineCapacities

SELECT SnapshotUserId, ScenarioId, WorkcentreId, WorkcentreName, WorkcentreCode, DateFrom,
case when NominalCapacityHours - AllocationHours - OrdersHours - ShutHours > 0.01 then 1 else 0 end HasCapacity,
NominalCapacityHours - AllocationHours - OrdersHours - ShutHours AvailableCapacityHours
FROM  Machineinformation mi join Workcentres wc on wc.Id = mi.WorkcentreId
WHERE WorkcentreId IS NOT NULL
AND MachineType = 'PM'
top
IVSA#PMCapacities
WITH mc AS
 (SELECT SnapshotUserId, ScenarioId, WorkcentreId, SiteId, mi.DateFrom SourceDate, NominalCapacity NominalCapacity,
         CapacityHours, NominalCapacityHours, OrdersHours OrdersHours, ShutHours, Orders Orders, AllocationHours,
GREATEST(0, NominalCapacityHours - OrdersHours -  AllocationHours) UnallocatedHours,
         CASE
             WHEN OrdersHours > CapacityHours THEN
              CapacityHours
             ELSE
              OrdersHours
         END + AllocationHours AllocatedHours, MachineType
FROM   MachineInformation mi
WHERE  MachineType = 'PM'
)
,
a AS
 (SELECT SnapshotUserId, ScenarioId, WorkcentreId, SiteId, SourceDate,
         SUM(DECODE(Rate, 0, 0, Allocation / Rate * (100 / TimeEfficiency))) AllocationHours, SUM(Allocation) Allocation
FROM SourcingAllocation
WHERE Allocation > 0
  GROUP  BY SnapshotUserId, ScenarioId, WorkcentreId, SiteId, SourceDate)
SELECT mc.SnapshotUserId, mc.ScenarioId, mc.WorkcentreId, mc.SiteId, mc.SourceDate, NominalCapacity NominalCapacity,
       NominalCapacityHours, CapacityHours CapacityHours, UnallocatedHours UnallocatedHours,
       (CapacityHours - UnallocatedHours) AllocatedHours, NVL(a.AllocationHours, 0) AllocationHours,
       OrdersHours OrdersHours,
       CASE WHEN MachineType = 'ES' THEN NominalCapacity
       ELSE DECODE(NominalCapacityHours, 0, 0, NVL(Allocation, 0) + NVL(Orders, 0) + (NominalCapacity / NominalCapacityHours * UnallocatedHours)) END Capacity,
       GREATEST(0, DECODE(NominalCapacityHours, 0, 0, NVL(Allocation, 0) + NVL(Orders, 0) + (NominalCapacity / NominalCapacityHours * UnallocatedHours))
               - (NVL(Allocation, 0) + NVL(Orders, 0))) ExtraCapacity,
       NominalCapacity / 168 * UnallocatedHours UnallocatedCapacity, ShutHours ShutHours, NVL(Allocation, 0) Allocation,
Orders  Orders
FROM   mc
LEFT   JOIN a
ON     mc.SnapshotUserId = a.SnapshotUserId
AND mc.ScenarioId = a.ScenarioId
AND mc.WorkcentreId = a.WorkcentreId
AND mc.SourceDate = a.SourceDate
ORDER BY 1,2,3,4,5

top
IVSA#ProductionRates
SELECT pr.*, wc.SiteName, wc.WorkcentreName,
       d.Code1, d.Code2, d.Code3, d.Code4, d.Code5, d.Code6, d.Code7, d.Code8, d.Code9, d.Code10,
       d.Code11, d.Code12, d.Code13, d.Code14, d.Code15, d.Code16, d.Code17, d.Code18, d.Code19, d.Code20,
       d.Code21, d.Code22, d.Code23, d.Code24, d.Code25, d.Code26, d.Code27, d.Code28, d.Code29, d.Code30
  FROM ProductionRateSnapshots pr
  JOIN   HierarchyPropertyDetails d
  ON     (d.Id = pr.DetailId)
  JOIN IH#Workcentres wc
  ON wc.WorkcentreId = pr.WorkcentreId
top
IVSA#SourcingAllocations
 SELECT ScenarioId, t.SnapshotUserId, DeliveryDate, SourceDate,
       AllocationId, StageNo, SeqNo, IsLastStage, ConversionFactor, Rate, PropertyValueId,
       SourcePropertyValueId, SourceMaterialId, OperationTypeId, NextOperationTypeId,
       SUM(Allocation) Allocation, SUM(Orders) Orders, SUM(NVL(AllocationHours,0)) AllocationHours,
       SUM(NVL(OrderHours,0)) OrderHours,
       SUM(RemainingSourceWeight) RemainingSourceWeight, SUM(RemainingWeight) RemainingWeight, WorkcentreId,
       SourceLocationId, DestinationType, SourceType, IsFirm, t.ID, t.CoProductId, t.SiteId,
       SUM(Revenue) Revenue, SUM(ProductionCost) ProductionCost,
       SUM(TransportCost) TransportCost, SUM(InventoryCost) InventoryCost, SUM(TransportCost + ProductionCost + InventoryCost) TotalCost,
       SUM(Margin) Margin,
       SUM((Allocation + Orders) / (MaterialEfficiency/ 100) - Allocation - Orders) Losses,
       SUM(DECODE(IsLastStage, 1, (Allocation + Orders) * Price, 0)) PriceVolume,
       SUM(DECODE(IsLastStage, 1, (Allocation + Orders), 0)) TotalAllocation,
       DECODE(NULLIF(SUM(Allocation / ConversionFactor / NULLIF(Rate,0)), 0), 0, 0, NVL(SUM(Margin) / NULLIF(SUM(Allocation / ConversionFactor / NULLIF(Rate,0)), 0),0)) Profitability
  FROM (

          SELECT ScenarioId, SnapshotUserId, DeliveryDate, SourceDate, AllocationId, StageNo, SeqNo, IsLastStage, sa.Sourcematerialid, sa.SourcePropertyValueId,
                 OperationTypeId, NextOperationTypeId,
                 ConversionFactor, Rate,
                 Allocation, 0 Orders,
                 DECODE(Rate, 0, 0, (Allocation / Rate) * (100 / TimeEfficiency)) AllocationHours,
                 0 OrderHours, 0 RemainingSourceWeight,
                 0 RemainingWeight, wc.WorkcentreId, wc.LocationId SourceLocationId, sa.ID, sa.CoproductId, sa.Siteid,
                 'customer' DestinationType,
                 DECODE(HasInventory, 1, 'stock', 'production') AS SourceType, 1 IsFirm,
                 Revenue, ProductionCost, TransportCost, InventoryCost,
                 Margin, MaterialEfficiency,
                 Price
            FROM SourcingAllocation sa
            JOIN IH#Workcentres wc ON wc.WorkcentreId = sa.WorkcentreId

           UNION ALL

          SELECT s.Id ScenarioId, so.SnapshotUserId, so.DeliveryPeriod AS DeliveryDate,
                 SourcePeriod AS SourceDate,
                 -OrderLineId as AllocationId, StageNo,
                 MAX(StageNo) OVER(PARTITION BY so.SnapshotUserId, OrderLineId) + 1 - StageNo seqNo, IsLastStage,
                 NULL Sourcematerialid, PropertyValueId SourcePropertyValueId,
                 NULL OperationTypeId, NULL NextOperationTypeId,
                 ConversionFactor, Rate,
                 0 Allocation,
                 so.Weight AS Orders, 0 AllocationHours,
                 CASE WHEN so.Duration != 0 THEN so.Duration / 60
                      WHEN NVL(so.Rate,0) != 0 THEN so.RemainingSourceWeight / Rate
                      ELSE 0
                 END OrderHours,
                 so.RemainingSourceWeight, so.RemainingWeight, so.WorkcentreId, wc.LocationId SourceLocationId,
                 so.SnoItemId, CoProductId, SiteId, DestinationType, SourceType, IsFirm, Revenue, ProductionCost, TransportCost,
                 InventoryCost, Margin, MaterialEfficiency,
                 Price
            FROM SNOAllOrderSnapshots so, Scenarios s, Workcentres wc
           WHERE so.snapshotUserId = s.Snapshotuserid
             AND wc.Id = so.WorkcentreId
             AND so.RemainingSourceWeight > 0
             AND so.SourcePeriod IS NOT NULL
       ) t
  JOIN SNoItemsShort SI ON (si.SnapshotUserId = t.SnapshotUserId
                            AND si.Id = t.Id
                            AND NVL(si.CoProductId,0) = NVL(t.CoProductId,0)
                            )
 GROUP BY ScenarioId, t.SnapshotUserId, DeliveryDate, SourceDate, AllocationId, StageNo, seqNo, IsLastStage, t.ID, t.CoProductId, WorkcentreId,
       SourceLocationId, SiteId, DestinationType, SourceType, IsFirm,
       PropertyValueId, SourcePropertyValueId, SourceMaterialId, ConversionFactor, Rate,
      OperationTypeId, NextOperationTypeId
top
IVSA#TransportAllocations
SELECT ScenarioId, t.SnapshotUserId, DeliveryDate, DeliveryDate DeliveryMonth, SourceDate, SourceDate SourceMonth,
       PropertyValueId, SUM(Allocation) Allocation, SUM(Orders) Orders, SUM(RemainingSourceWeight) RemainingSourceWeight,
       SUM(RemainingWeight) RemainingWeight, MasterRouteId, WorkcentreId, SourceLocationId, DestinationType, SourceType,
       IsFirm, t.ID, t.CoProductId, SiteId, SUM(Revenue) Revenue, SUM(ProductionCost) ProductionCost, SUM(TransportCost) TransportCost,
       SUM(InventoryCost) InventoryCost, SUM(ProductionCost + InventoryCost + TransportCost) TotalCost,
       SUM(Margin) Margin
FROM   (SELECT ScenarioId, SnapshotUserId, DeliveryDate, SourceDate, Allocation, 0 Orders, 0 RemainingSourceWeight,
                0 RemainingWeight, MasterRouteId, wc.WorkcentreId, wc.LocationId SourceLocationId, sa.ID, sa.CoProductId, wc.Siteid,
                'customer' DestinationType, DECODE(HasInventory, 1, 'stock', 'production') AS SourceType, 1 IsFirm,
                Revenue, ProductionCost, TransportCost, InventoryCost, Margin
         FROM   SourcingAllocation sa
         JOIN   IH#Workcentres wc
         ON     wc.WorkcentreId = sa.WorkcentreId
         UNION ALL
         SELECT s.Id ScenarioId, so.SnapshotUserId, so.DeliveryPeriod AS DeliveryDate,
                SourcePeriod AS SourceDate, 0 Allocation,
                so.Weight AS Orders, so.RemainingSourceWeight, so.RemainingWeight, so.MasterRouteId, so.WorkcentreId,
                wc.LocationId SourceLocationId, so.SnoItemId, so.CoProductId, SiteId, DestinationTYpe, SourceType, IsFirm, Revenue, ProductionCost,
                TransportCost, InventoryCost, Margin
         FROM   SNOAllOrderSnapshots so, Scenarios s, Workcentres wc
         WHERE  so.snapshotUserId = s.Snapshotuserid
         AND    wc.Id = so.WorkcentreId
         AND    so.SourcePeriod IS NOT NULL) t
JOIN   SNoItemsShort SI
ON     (si.SnapshotUserId = t.SnapshotUserId AND si.Id = t.Id AND NVL(si.CoProductId,0) = NVL(t.CoProductId, 0))
GROUP  BY ScenarioId, t.SnapshotUserId, DeliveryDate, SourceDate, t.ID, t.CoProductId, MasterRouteId, WorkcentreId, SourceLocationId,
          SiteId, DestinationType, SourceType, IsFirm, PropertyValueId
top
IVSN#CustomerSourcePriorities

SELECT * FROM
(
SELECT sp.Id, sp.DestinationLocationID, sp.DestinationMaterialId, sl.SiteId, l.LocationCode, l.LocationName, sp.Priority,
       NVL(j.JourneyCode, j2.JourneyCode) JourneyCode, NVL(j.TimePeriod, j2.TimePeriod) Duration, mg.GroupId,
       ROW_NUMBER() OVER(PARTITION BY sp.DestinationLocationID, sp.DestinationMaterialId, sl.SiteId ORDER BY sp.Priority) RankLevel
  FROM SourcePriorities sp
  JOIN Locations l
    ON sp.Destinationlocationid = l.Id
  JOIN Locations sl
    ON sp.SourceLocationId = sl.Id
  LEFT JOIN JourneysIPlanView j
    ON sp.JourneyId = j.JourneyId
  LEFT JOIN JourneysIPlanView j2
    ON j2.FromLocationId = sl.Id AND j2.ToLocationId = NVL(l.TransportLocationId, l.Id)
  LEFT JOIN MaterialGroups mg
    ON mg.MaterialId = sp.DestinationMaterialId
 WHERE NOT EXISTS (SELECT 1 FROM Workcentres wc WHERE wc.LocationId = l.Id)
)
WHERE RankLevel = 1

top
IVSN#SiteSourcePriorities
SELECT * FROM
(
SELECT sp.Id, ss.Id SourceSiteId, NVL(ds.id,0) TargetSiteId, m.Id MaterialId, sp.Priority, ds.SiteName TargetSiteName, ss.SiteName SourceSiteName,
smu.Replenished IsReplenished,
ROW_NUMBER() OVER(PARTITION BY ss.Id, ds.Id, m.Id ORDER BY Priority) RankLevel
FROM   SourcePriorities sp
JOIN   Locations dl
ON     dl.Id = sp.DestinationLocationId
JOIN   Locations sl
ON     sl.Id = sp.SourceLocationId
JOIN   Materials m
ON     m.Id = sp.SourceMaterialId
LEFT JOIN   Sites ds
ON     ds.Id = dl.SiteId
JOIN   Sites SS
ON     ss.Id = sl.SiteId
JOIN SiteMaterialUsages smu ON sp.SiteMaterialUsageId = smu.Id
WHERE  sp.SourceMaterialId = sp.DestinationMaterialId
AND    ConsignmentLocationId IS NULL
)
WHERE RankLevel = 1
top
IVT#Inventories
SELECT l.LocationCode LOCATION, m.MaterialCode Product,  smu.Id, i.DateFrom, i.Weight
FROM   Inventories i
JOIN SiteMaterialUsages smu ON smu.Id = i.SiteMaterialUsageId
JOIN   Locations l
ON     (l.Id = smu.LocationId)
JOIN   Materials m
ON     (m.Id = smu.MaterialId)
top
IVT#InventoryProfiles
SELECT l.LocationCode LOCATION, m.MaterialCode Product, smu.Id, rip.Opening,rip.DateFrom,
rip.Consumption, rip.ConsumptionOrders, rip.TentativeOrdersIn, rip.PlannedInventory,
rip.MinOpening, rip.SafetyStock
FROM   InventoryProfiles rip
JOIN SiteMaterialUsages smu ON smu.Id = rip.SiteMaterialUsageId
JOIN   Locations l
ON     (l.Id = smu.LocationId)
JOIN   Materials m
ON     (m.Id = smu.MaterialId)
top
IVT#OrderLines
SELECT l.LocationCode LOCATION, m.MaterialCode Product, wc.WorkcentreCode Workcentre, ol.Id,
ol.DeliveryDate, ol.ConsumptionDate, ol.DespatchDate, ol.FinalWeight, OrderLineStatusCode, OrderLineStatusName

FROM   OrderLines ol
JOIN OrderLineStatuses ols ON (ols.Id = ol.OrderLineStatusId)

JOIN   Locations l
ON     (l.Id = ol.LocationId)
JOIN   Materials m
ON     (m.Id = ol.MaterialId)
JOIN Workcentres wc ON wc.Id = ol.WorkcentreId
top
IVT#RealInventoryProfiles
SELECT l.LocationCode LOCATION, m.MaterialCode Product, smu.Id, rip.Opening,rip.DateFrom, rip.Closing,
rip.OrdersIn, rip.OrdersOut, rip.TentativeOrdersIn, rip.TentativeOrdersOut, rip.MinOpening, rip.SafetyStock
FROM   RealInventoryProfilesIPlanView rip
JOIN SiteMaterialUsages smu ON smu.Id = rip.SiteMaterialUsageId
JOIN   Locations l
ON     (l.Id = smu.LocationId)
JOIN   Materials m
ON     (m.Id = smu.MaterialId)
top
IVT#Skus
SELECT l.LocationCode Location,
       m.MaterialCode Product,
       eu.EndUseCode EndUse,
       NVL(ec.LocationCode, l.LocationCode) EndCustomer,
       smu.Id,
       eu.Id EndUseId,
       ec.Id EndCustomerId,
       smu.Status
FROM   SiteMaterialUsages smu
JOIN   Locations l
ON     (l.Id = smu.LocationId)
JOIN   Materials m
ON     (m.Id = smu.MaterialId)
LEFT JOIN   endUses eu
ON     (eu.Id = smu.EndUseid)
LEFT JOIN   Locations ec
ON     (ec.Id = smu.EndCustomerId)
top
IVT#TentativeOrderLines
SELECT l.LocationCode LOCATION, m.MaterialCode Product, wc.WorkcentreCode Workcentre, ol.Id,
ol.DeliveryDate, ol.ConsumptionDate, ol.DespatchDate, ol.FinalWeight, OrderLineStatusCode, OrderLineStatusName

FROM   OrderLines ol
JOIN OrderLineStatuses ols ON (ols.Id = ol.OrderLineStatusId)

JOIN   Locations l
ON     (l.Id = ol.LocationId)
JOIN   Materials m
ON     (m.Id = ol.MaterialId)
JOIN Workcentres wc ON wc.Id = ol.WorkcentreId
WHERE ols.OrderLineStatusCode = 'System'
top
JourneyRoutsIPlanView
SELECT j.JourneyKey,
       j.JourneyId,
       RANK() OVER (PARTITION BY j.JourneyKey ORDER BY j.OrderNo) OrderNo,
       j.TransportRouteId
  FROM (
 	 SELECT j.JourneyKey,
	        j.JourneyId,
	        jr.OrderNo,
	        jr.TransportRouteId
	   FROM JourneysIPlanView j, JourneyRoutes jr
	  WHERE j.JourneyId = jr.JourneyId
	  UNION
	 SELECT j.JourneyKey,
	        j.JourneyId,
	        DECODE(tr.Id, j.FromTransportRouteId, 0, j.ToTransportRouteId, 9999) OrderNo,
	        tr.Id TransportRouteId
 	   FROM JourneysIPlanView j, TransportRoutes tr
	  WHERE tr.Id IN (j.FromTransportRouteId, j.ToTransportRouteId)
	  ORDER BY JourneyKey, OrderNo
      ) j
top
JourneysIPlanView

SELECT j.JourneyId, j.JourneyCode, j.FromLocationId, j.ToLocationId, j.FromTransportRouteId, j.ToTransportRouteId,
       j.Cost, j.TimePeriod, j.QuantityLegs, j.IsDefault, j.IsInternal, tm.TransportMethodCode, tm.TransportMethodName,
       j.TransportMethodId, sl.SiteId SourceSiteId, tl.SiteId TargetSiteId, Priority, NVL(ScheduleId, DefaultScheduleId) ScheduleId,
       RANK() OVER(PARTITION BY FromLocationId, ToLocationId ORDER BY IsDefault DESC, DECODE(SIGN(Priority), -1, ABS(Priority) * 999, Priority), Cost, QuantityLegs, TimePeriod) JourneyRank,
j.JourneyId||'-'||j.FromLocationId||'-'||j.ToLocationId AS JourneyKey
FROM (
SELECT j.Id AS JourneyId, j.JourneyCode, ftr.FromLocationId, ttr.ToLocationId, ftr.Id AS FromTransportRouteId,
                ttr.Id AS ToTransportRouteId, ftr.Cost + j.Cost + ttr.Cost AS Cost,
                ftr.TimePeriod + j.TimePeriod + ttr.TimePeriod AS TimePeriod, j.QuantityLegs + 2 AS QuantityLegs,
                j.IsDefault, j.IsInternal, ttr.TransportMethodId, ttr.Priority, ttr.ScheduleId
FROM TransportRoutes ftr, Journeys j, TransportRoutes ttr, Locations ftl, Locations ttl
WHERE ftr.TransportMethodId = j.FirstTransportMethodId
AND j.LastTransportMethodId = ttr.TransportMethodId
AND ftr.ToLocationid IN (ftl.Id, ftl.TransportLocationId)
AND ftl.Id = j.FromLocationId
AND j.ToLocationId IN (ttl.Id, ttl.TransportLocationId)
AND ttl.Id = ttr.FromLocationId
UNION ALL
         SELECT j.Id AS JourneyId, j.JourneyCode, j.FromLocationId, j.ToLocationId, NULL AS FromTransportRouteId,
                NULL AS ToTransportRouteId, j.Cost, j.TimePeriod, j.QuantityLegs, j.IsDefault, j.IsInternal,
                tr.TransportMethodId, tr.Priority, tr.ScheduleId
FROM Journeys j, JourneyRoutes jr, TransportRoutes tr
WHERE j.FirstTransportMethodId IS NULL
AND j.LastTransportMethodId IS NULL
AND j.IsInternal = 0
AND j.Id = jr.JourneyId
AND jr.TransportRouteId = tr.Id
AND jr.OrderNo = (SELECT MAX(jr2.OrderNo) FROM JourneyRoutes jr2 WHERE jr2.JourneyId = jr.JourneyId)
UNION ALL
         SELECT j.Id AS JourneyId, j.JourneyCode, j.FromLocationId, j.ToLocationId, NULL AS FromTransportRouteId,
                NULL AS ToTransportRouteId, j.Cost, j.TimePeriod, j.QuantityLegs, j.IsDefault, j.IsInternal,
                tr.TransportMethodId, tr.Priority, tr.ScheduleId
FROM Journeys j, JourneyRoutes jr, TransportRoutes tr
WHERE j.FirstTransportMethodId IS NULL
AND j.LastTransportMethodId IS NULL
AND j.IsInternal = 1
AND j.Id = jr.JourneyId
AND jr.TransportRouteId = tr.Id
				 ) j
JOIN   TransportMethods tm
ON     j.TransportMethodId = tm.Id
LEFT   JOIN Locations sl
ON     sl.Id = j.FromLocationId
LEFT   JOIN Locations tl
ON     tl.Id = j.ToLocationId
CROSS JOIN IH#DefaultParameters p

top
JourneyView
SELECT JourneyCode, JourneyId, StartLocation || Route Route
from
(
SELECT JourneyId, JourneyCode, f.LocationName FromLocation, t.LocationName ToLocation, OrderNo, f.Id FromId, t.Id ToId,
CONNECT_BY_ISLEAF AS IsLeaf,
CONNECT_BY_ROOT f.LocationName StartLocation, SYS_CONNECT_BY_PATH(t.LocationName, ' -> ' ) Route
from JourneyRoutes jr, TransportRoutes tr,Locations f, Locations t, Journeys j
WHERE tr.FromLocationId = f.Id
AND tr.ToLocationId = t.Id
AND jr.transportrouteid = tr.Id
AND j.ID= jr.JourneyId
connect by f.ID = PRIOR t.Id AND JourneyId = PRIOR JourneyId
start with OrderNo = 1
order by JourneyId, OrderNo
)
WHERE IsLEAF = 1
top
LocationsIPlanView
SELECT l.Id, LocationName, t.WorkcentreTYpeId, wct.WorkcentreTypeName,
Capacity, LocationCode, CompanyId, CustomerrankId,
SafetyStockMethodId, CalendarId, HierarchyId,
TransportLocationId, SiteId,
DECODE(WorkcentreTypeId, NULL, 1, DECODE(WorkcentreTypeName, 'Warehouse', 1, 'SemiFinishingWarehouse', 1, 'Virtual Warehouse', 1, 0)) IsConsumer,
DECODE(WorkcentreTypeId, NULL, 1, 0) IsEndCustomer,
SIGN(NVL(WorkcentreTypeId,0)) IsSupplier,
DECODE(WorkcentreTypeId, NULL, 1, DECODE(WorkcentreTypeName, 'Warehouse', 1, 'SemiFinishingWarehouse', 1, 'Virtual Warehouse', 1, 0)) HasSku
FROM Locations l LEFT JOIN
(
SELECT LocationId, MIN(WorkcentreTypeId) WorkcentreTypeId
FROM Workcentres
GROUP BY LocationId
) t
ON l.Id = t.LocationId
LEFT JOIN WorkcentreTypes wct
ON (t.WorkcentreTYpeId = wct.Id)
top
MaterialRunsView

   Select wc.WorkcentreName, wct.WorkcentreTypeName, SiteName,
   SiteId, mr.*, mrp.ID as
   RunProductId, mrp.ProductName
   from MaterialRuns mr,
   MaterialBlocks mb, Workcentres wc, WorkcentreTypes wct,
   MaterialRunProducts
   mrp, Locations l, Sites s
   WHERE mr.MaterialBlockId = mb.Id
   AND mb.WorkcentreId
   = wc.ID
   AND wc.WorkcentreTypeId = wct.Id
   AND mrp.MAterialRunID (+) = mr.ID
   AND
   wc.LocationId = l.Id
   AND l.SiteId = s.Id

top
MaterialsIPlanView
SELECT MaterialId, MaterialTypeId, MaterialTypeName, MaterialCode, MaterialName,
       MAX(DECODE(OrderNo, 1, PropertyValueCode, NULL)) Code1, MAX(DECODE(OrderNo, 1, VALUE, NULL)) Value1,
       MAX(DECODE(OrderNo, 2, PropertyValueCode, NULL)) Code2, MAX(DECODE(OrderNo, 2, VALUE, NULL)) Value2,
       MAX(DECODE(OrderNo, 3, PropertyValueCode, NULL)) Code3, MAX(DECODE(OrderNo, 3, VALUE, NULL)) Value3,
       MAX(DECODE(OrderNo, 4, PropertyValueCode, NULL)) Code4, MAX(DECODE(OrderNo, 4, VALUE, NULL)) Value4,
       MAX(DECODE(OrderNo, 5, PropertyValueCode, NULL)) Code5, MAX(DECODE(OrderNo, 5, VALUE, NULL)) Value5,
       MAX(DECODE(OrderNo, 6, PropertyValueCode, NULL)) Code6, MAX(DECODE(OrderNo, 6, VALUE, NULL)) Value6,
       MAX(DECODE(OrderNo, 7, PropertyValueCode, NULL)) Code7, MAX(DECODE(OrderNo, 7, VALUE, NULL)) Value7,
       MAX(DECODE(OrderNo, 8, PropertyValueCode, NULL)) Code8, MAX(DECODE(OrderNo, 8, VALUE, NULL)) Value8,
       MAX(DECODE(OrderNo, 9, PropertyValueCode, NULL)) Code9, MAX(DECODE(OrderNo, 9, VALUE, NULL)) Value9,
       MAX(DECODE(OrderNo, 10, PropertyValueCode, NULL)) Code10, MAX(DECODE(OrderNo, 10, VALUE, NULL)) Value10,
       MAX(DECODE(OrderNo, 11, PropertyValueCode, NULL)) Code11, MAX(DECODE(OrderNo, 11, VALUE, NULL)) Value11,
       MAX(DECODE(OrderNo, 12, PropertyValueCode, NULL)) Code12, MAX(DECODE(OrderNo, 12, VALUE, NULL)) Value12,
       MAX(DECODE(OrderNo, 13, PropertyValueCode, NULL)) Code13, MAX(DECODE(OrderNo, 13, VALUE, NULL)) Value13,
       MAX(DECODE(OrderNo, 14, PropertyValueCode, NULL)) Code14, MAX(DECODE(OrderNo, 14, VALUE, NULL)) Value14,
       MAX(DECODE(OrderNo, 15, PropertyValueCode, NULL)) Code15, MAX(DECODE(OrderNo, 15, VALUE, NULL)) Value15,
       MAX(DECODE(OrderNo, 16, PropertyValueCode, NULL)) Code16, MAX(DECODE(OrderNo, 16, VALUE, NULL)) Value16,
       MAX(DECODE(OrderNo, 17, PropertyValueCode, NULL)) Code17, MAX(DECODE(OrderNo, 17, VALUE, NULL)) Value17,
       MAX(DECODE(OrderNo, 18, PropertyValueCode, NULL)) Code18, MAX(DECODE(OrderNo, 18, VALUE, NULL)) Value18,
       MAX(DECODE(OrderNo, 19, PropertyValueCode, NULL)) Code19, MAX(DECODE(OrderNo, 19, VALUE, NULL)) Value19,
       MAX(DECODE(OrderNo, 20, PropertyValueCode, NULL)) Code20, MAX(DECODE(OrderNo, 20, VALUE, NULL)) Value20,

       MAX(DECODE(OrderNo, 21, PropertyValueCode, NULL)) AS Code21, MAX(DECODE(OrderNo, 22, VALUE, NULL)) AS Value22,
       MAX(DECODE(OrderNo, 23, PropertyValueCode, NULL)) AS Code23, MAX(DECODE(OrderNo, 24, VALUE, NULL)) AS Value24,
       MAX(DECODE(OrderNo, 25, PropertyValueCode, NULL)) AS Code25, MAX(DECODE(OrderNo, 26, VALUE, NULL)) AS Value26,
       MAX(DECODE(OrderNo, 27, PropertyValueCode, NULL)) AS Code27, MAX(DECODE(OrderNo, 29, VALUE, NULL)) AS Value28,
       MAX(DECODE(OrderNo, 29, PropertyValueCode, NULL)) AS Code29, MAX(DECODE(OrderNo, 30, VALUE, NULL)) AS Value30

FROM   (SELECT em.MaterialId, MaterialTypeId, MaterialTypeName, MaterialCode, MaterialName, pv.PropertyValueCode,
                pv.Value, pv.PropertyId, p.OrderNo
         FROM   ExpandedMaterials em, PropertyValues pv, Materials m, MaterialTypes mt,
                (SELECT Id, PropertyName, ROW_NUMBER() Over(ORDER BY Id) OrderNo FROM Properties) p
         WHERE  pv.Id = em.PropertyValueId
         AND    pv.PropertyId = p.Id
         AND    em.MaterialId = m.Id
         AND    mt.Id = m.MaterialTypeId)
GROUP  BY MaterialId, MaterialTypeId, MaterialTypeName, MaterialCode, MaterialName

top
MaterialTypesIPlanView

Select MaterialTypeName, PropertyName, PropertyDesc, ProductionStageNo, HierarchyLevelNo,
PropertyId, MaterialTypeId, mt.Isfinishedgoods, mt.Issinglestage
from MaterialTypeProperties mtp, MaterialTypes mt, Properties p
WHERE mtp.PropertyId = p.Id
AND mtp.MaterialTypeId = mt.Id
order by MaterialTypeName,HierarchyLevelNo

top
MaterialUnitsIPlanView
select u.MaterialTypeId, mu.MAterialId, u.Id, mu.Dividend, mu.Divisor, 1 /  mu.Dividend * mu.Divisor OneUnit
from MaterialUnits mu, MaterialTypes mt, Units u, UnitTypes ut, Materials m
WHERE u.MaterialTypeId = mt.Id
AND ut.Id = u.UnitTypeId
AND ut.UnitTypeName = 'Quantity'
AND mu.UnitId= NVL(mt.RoundingUnitId, u.Id)
AND m.Id = mu.MaterialId
and m.MaterialTypeId = mt.Id
and u.IsBaseUnit = 1
top
OrderInventoryIPlanView
SELECT ob.Id, ol.SiteMaterialUsageId, ob.OrderLineId, ol.ToConsignmentLocationId, ol.SKUKey, ol.SourceSkuKey, ol.locationId,
       ob.StockWeight, ob.DeliveryDate, ol.ConsumptionDate, ob.LocationId WarehouseId, ol.SourceSiteMaterialUsageId, ol.WorkcentreId,
       ob.IsDelivered, ob.IsSameSource,
       OrderLineStatusCode, v.WarehouseLocationId
FROM   OrderBookInventories ob, OrderLines ol, OrderLineStatuses ols, IH#SkuWarehouseLocations v
WHERE  ob.IsLatest = 1
AND    ol.Id = ob.OrderLineId
AND    ols.Id = ol.OrderLineStatusId
AND    ol.SkuKey = v.SkuKey
top
OrderLineReasonsIPlanView

SELECT r.Id, r.Reason ReasonName, t.ReasonDesc, LanguageId
  FROM Reasons r
  LEFT JOIN IT#OrderLineReasons t ON t.ReasonId = r.Id
 WHERE ReasonType = 'OrderLine'
top
PackageVersionsView

   Select 'analysis' PackageName, analysis.packageVersion Version
   from dual
   UNION  ALL
   Select 'bs' PackageName, bs.packageVersion Version from
   dual
   UNION ALL
   Select 'dc' PackageName, dc.packageVersion Version from dual
   UNION ALL
   Select 'ddq' PackageName, ddq.packageVersion Version from dual
   UNION ALL
   Select 'ext' PackageName, ext.packageVersion Version from dual
   UNION ALL
   Select 'forecasting' PackageName, forecasting.packageVersion
   Version from dual
   UNION ALL
   Select 'fg' PackageName, fg.packageVersion Version
   from dual
   UNION ALL
   Select 'ip' PackageName, ip.packageVersion Version from
   dual
   UNION ALL
   Select 'core' PackageName, core.packageVersion Version from
   dual
   UNION ALL
   Select 'mp' PackageName, mp.packageVersion Version from dual
   UNION ALL
   Select 'og' PackageName, og.packageVersion Version from dual
   UNION  ALL
   Select 'reports' PackageName, reports.packageVersion Version from dual
   UNION ALL
   Select 'rp' PackageName, rp.packageVersion Version from dual

top
ProcessStatusesIPlanView
WITH p AS (SELECT t.Id AS TaskId,
                  t.TaskName,
                  t.Description AS TaskDesc,
                  t.IsSystemTask,
                  pp.Id AS ProcessPartId,
                  pp.ProcessPartName,
                  pp.ProcessPartDesc,
                  pp.OrderNo,
                  ps.UserId,
                  ps.Done,
                  ps.Total,
                  DECODE(ps.Total, 0, 0, Round(ps.Done / ps.Total * 100, 0)) AS Percentage
             FROM ProcessStatuses ps
             JOIN ProcessParts pp ON pp.Id = ps.ProcessPartId
             JOIN Tasks t ON t.Id = pp.TaskId
            UNION ALL
           SELECT t.Id AS TaskId,
                  t.TaskName,
                  t.Description AS TaskDesc,
                  t.IsSystemTask,
                  NULL AS ProcessPartId,
                  ps.ProcessPartName,
                  ps.ProcessPartName AS ProcessPartDesc,
                  ps.OrderNo,
                  ps.UserId,
                  ps.Done,
                  ps.Total,
                  DECODE(ps.Total, 0, 0, Round(ps.Done / ps.Total * 100, 0)) AS Percentage
             FROM ProcessStatuses ps
             JOIN Tasks t ON t.Id = ps.TaskId
            WHERE NVL(ps.ProcessPartId,0) = 0)

SELECT p.TaskId,
       p.TaskName,
       NVL(tt.TaskDesc, p.TaskDesc) AS TaskDesc,
       p.IsSystemTask,
       p.ProcessPartId,
       p.ProcessPartName,
       NVL(tpp.ProcessPartDesc, p.ProcessPartDesc) AS ProcessPartDesc,
       p.OrderNo,
       p.UserId,
       p.Done,
       p.Total,
       p.Percentage,
       NVL(tt.LanguageId, tpp.LanguageId) AS LanguageId
FROM p
LEFT JOIN IT#Tasks tt ON tt.TaskId = p.TaskId
LEFT JOIN IT#ProcessParts tpp ON tpp.ProcessPartId = p.ProcessPartId
                             AND tpp.LanguageId = tt.LanguageId
top
PropertiesIPlanView

SELECT Id, PropertyName OriginalPropertyName, REGEXP_REPLACE(PropertyDesc, '[^[:alnum:]_\s]', '') AS PropertyName,
PropertyDesc, DataType,
UPPER('P_' || REGEXP_REPLACE(PropertyDesc, '[^[:alnum:]_\s]', '')) PropertyViewName,
UPPER('P_' || REGEXP_REPLACE(PropertyDesc, '[^[:alnum:]_\s]', '') || 'CODE') PropertyViewCode,
'Code' || ROW_NUMBER() Over(ORDER BY Id) FieldPropertyCode,
'Value' || ROW_NUMBER() Over(ORDER BY Id) FieldPropertyValue,
ROW_NUMBER() Over(ORDER BY Id) OrderNo
FROM  Properties

top
RealInventoryProfilesIPlanView
SELECT SiteMaterialUsageId, ConsignmentLocationId, SKUKey, DateFrom, OverallOpening, Opening,
       OpeningNonForecasted, OrdersIn, TentativeOrdersIn, OrdersOut, TentativeOrdersOut, ClosingNonForecasted, Closing,
       OverallClosing, FirmClosing, MinOpening, Consumption, SafetyStock, MaxSafetyStock
FROM   Realinventoryprofiles r
WHERE  NOT EXISTS (SELECT 1 FROM GroupRealInventoryProfiles g WHERE g.SkuKey = r.SkuKey)
UNION ALL
SELECT SiteMaterialUsageId, ConsignmentLocationId, SKUKey, DateFrom, OverallOpening, Opening,
       OpeningNonForecasted, OrdersIn, TentativeOrdersIn, OrdersOut, TentativeOrdersOut, ClosingNonForecasted, Closing,
       OverallClosing, FirmClosing, MinOpening, Consumption, SafetyStock, MaxSafetyStock
FROM   GroupRealInventoryProfiles
top
ReplenishmentChainsView
SELECT PointId Id , ChainNo, LevelNo, MaterialCode, IsSingleStage, IsFinishedGoods, LTRIM(Chain, ' <- ' ) Chain
FROM   (SELECT PointId, ChainNo, LevelNo, CONNECT_BY_ROOT MaterialCode MaterialCode, CONNECT_BY_ROOT IsSingleStage IsSingleStage, CONNECT_BY_ROOT IsFinishedGoods IsFinishedGoods,
                SYS_CONNECT_BY_PATH(LocationName || '-' || ConsignmentLocation || '(' || NVL (SourceType, xSourceType) || ')',
                                     ' <- ') chain, xSourceType, CONNECT_BY_ISLEAF AS IsLEAF
         FROM   ( SELECT PointId, ChainNo, LevelNo, l.LocationName, MaterialId,
                         NVL(cl.LocationName, 'Free') ConsignmentLocation, SourceType,
                         Replenished, IsSingleStage, r.IsFinishedGoods,
                         LAST_VALUE(SourceType IGNORE NULLS ) OVER(PARTITION BY PointId, ChainNo ORDER BY PointId, ChainNo, LevelNo ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) xSourceType
                  FROM   ReplenishedSKU r, Locations l, Locations cl
                  WHERE  r.LocationId = l.Id
                  AND    r.PointId IN (SElect Id from ReplenishedPoints)
                  AND    r.Consignmentlocationid = cl.Id(+)
                  ORDER  BY 1 , 2 , 3 ) t, Materials m
         WHERE m.Id =  t.MaterialId
         CONNECT BY (LevelNO = PRIOR LevelNo + 1 AND PointId = PRIOR PointId AND
                    ChainNO = PRIOR ChainNO)
         START  WITH (LevelNo = 1 And Replenished = 1))
WHERE  IsLeaf = 1
top
SafetyStockMethodsIPlanView

SELECT s.Id, s.SafetyStockMethodName, t.SafetyStockMethodDesc, LanguageId, IsMaxMethod
  FROM SafetyStockMethods s
  LEFT JOIN IT#SafetyStockMethods t ON t.SafetyStockMethodId = s.Id

top
ScenarioAllocationIPlanView
SELECT x.ScenarioId, x.SnapshotUserId, x.WorkcentreId, x.SnpItemId, x.CoProductId, x.sourcePropertyValueId, x.SourceMaterialId,
       x.DeliveryWeek, x.DeliveryMonth,
       x.SourceWeek, x.SourceMonth,
       DECODE(SUM(x.Allocation +x.NonMoveableWeight), 0, 0, SUM(x.Price * (Allocation + x.NonMoveableWeight)) / SUM(x.Allocation + x.NonMoveableWeight)) Price,
       SUM(DECODE(IsLastStage, 1, (x.Allocation + x.NonMoveableWeight) * x.Price, 0)) PriceVolume,
       SUM(DECODE(IsLastStage, 1, x.Allocation + x.NonMoveableWeight, 0)) TotalAllocation,
       SUM(x.NonMoveableWeight) AS NonMoveableWeight,
       SUM(x.Allocation) AS Allocation,
       SUM(Revenue) AS Revenue,
       SUM(Margin) AS Margin,
       SUM(COST) AS COST
FROM   (
       SELECT a.ScenarioId, a.SnapshotUserId, a.Id SnpItemId, a.CoProductId, a.SourcePropertyValueId, a.SourceMaterialId, a.WorkcentreId,
			          a.DeliveryDate DeliveryWeek, a.DeliveryDate DeliveryMonth, a.SourceDate SourceWeek, a.SourceDate SourceMonth,
								0 AS NonMoveableWeight, a.Allocation AS Allocation, a.Price,
                a.Revenue, (a.ProductionCost + a.InventoryCost + a.TransportCost)   AS COST,
                a.Margin AS margin, isLastStage
         FROM   SourcingAllocation a
         WHERE  a.WorkcentreId IS NOT NULL
         UNION ALL
         SELECT s.Id ScenarioId, so.SnapshotUserId, so.SnoItemId AS SNPItemId, so.CoProductId,
                 NULL SourcePropertyValueId, NULL SourceMaterialId, so.WorkcentreId AS WorkcentreId,
                TRUNC(so.DeliveryPeriod, 'IW') AS DeliveryWeek,
                TRUNC(so.DeliveryPeriod, 'month') AS DeliveryMonth,
                TRUNC(so.SourcePeriod, 'IW') AS SourceWeek,
                TRUNC(so.SourcePeriod, 'month') AS SourceMonth,
                so.Weight AS NonMoveableWeight, 0 AS Allocation, so.Price,
                so.Revenue, so.TotalCost Cost, so.Margin, IsLastStage
         FROM   SNOAllOrderSnapshots so, Scenarios s,
                (SELECT StartWeek Datefrom, SnapshotUserId FROM ScenarioSessions) SS
         WHERE  ss.snapshotuserid = so.SnapshotUserId
         AND    s.SnapshotUserId = so.SnapshotUserId
         AND    so.IsFirm = 1
         AND    so.PropertyValueId IS NOT NULL
         AND    so.SourceType IN ('stock', 'production')
         AND    (so.DeliveryPeriod >= ss.DateFrom OR so.SourcePeriod >= ss.DateFrom)
         AND    so.SourcePeriod IS NOT NULL
         ) x
WHERE x.Allocation + x.NonMoveableWeight > 0
GROUP  BY x.ScenarioId, x.SnapshotUserId,  x.SnpItemId, x.CoProductId, x.sourcePropertyValueId, x.SourceMaterialId, x.DeliveryWeek, x.DeliveryMonth, x.SourceWeek,
          x.SourceMonth, x.WorkcentreId
top
SemiFinishingWarehousesView
   SELECT LocationName, LocationCode, WorkcentreName,
   WorkcentreCode, SiteCode,
   SiteName, wc.Id WorkcentreId, l.Id LocationId, s.Id
   SiteId
   FROM Locations l, Workcentres wc, WorkcentreTypes wct, Sites s
   WHERE
   WorkcentreTypeName IN ('SemiFinishingWarehouse')
   AND wc.WorkcentreTypeId =
   wct.Id
   AND wc.LocationId = l.Id
   AND l.SiteId = s.Id
top
SessionParametersIPlanView
SELECT s.UserId, NVL(u.Value, s.Value) as VALUE, s.Id, ParameterName, ParameterType, ParameterArea, DataType, MINVALUE,
       MAXVALUE, CATEGORY, DependOn, ParameterDescription, Cloud
FROM   IH#UserParameters s
LEFT   JOIN UserSessionParameters u
ON     (s.Id = u.SystemParameterId AND u.UserId = s.UserId)
top
SitePropertiesIPlanView
	SELECT Id,
	REGEXP_REPLACE(PropertyName, '[^[:alnum:]_]', '') AS PropertyName,
	PropertyName AS PropertyDesc,
	UPPER('STP_' || REGEXP_REPLACE(PropertyName, '[^[:alnum:]_]', '')) PropertyViewName,
	'SiteProperty' || ROW_NUMBER() Over(ORDER BY Id) FieldProperty,
	HierarchyLevelNO OrderNo
	FROM SiteProperties
top
SkuPropertiesIPlanView
SELECT Id,
       REGEXP_REPLACE(PropertyName, '[^[:alnum:]_]', '') AS PropertyName,
       PropertyName AS PropertyDesc,
       UPPER('SP_' || REGEXP_REPLACE(PropertyName, '[^[:alnum:]_]', '')) PropertyViewName,
       'SkuProperty' || ROW_NUMBER() Over(ORDER BY Id) FieldProperty,
       HierarchyLevelNO OrderNo
  FROM SkuProperties
top
SKUView
   Select LocationName, MaterialName, smu.*
   from SiteMaterialUsages
   smu, Locations l, Materials m
   WHERE smu.MaterialId = m.Id
   AND smu.LocationId =
   l.Id

top
SKUWorkcentresDFIPlanView
SELECT smu.Id AS SiteMaterialUsageId,
       smu.LocationId,
       smu.MaterialId,
       d.ToLocationName AS LocationName,
       d.ToLocationCode AS LocationCode,
       d.FromWorkCentreId AS SourceWorkCentreId,
       d.FromWorkCentreName AS SourceWorkCentreName,
       d.fromWorkCentreCode AS SourceWorkCentreCode
FROM IH#WorkCentreDestinations d
JOIN SiteMaterialUsages smu ON smu.LocationId = d.ToLocationId
LEFT JOIN SourcePriorities sp ON sp.SourceLocationId IN (d.FromLocationId, d.MainWHLocationId) AND sp.SiteMaterialUsageId = smu.Id
WHERE 1=1
AND (d.IsDefault = 1 OR sp.Id IS NOT NULL)
top
SourcePrioritiesView

   Select l.LocationName CustomerName, m.MaterialName,
   l2.LocationName SupplierName,
   Priority
   from
   SourcePriorities sp, SiteMaterialUsages smu, Locations l, Materials m,
   Workcentres wc, Locations l2
   WHERE sp.SiteMaterialUsageId =
   smu.Id
   AND smu.LocationId = l.Id
   AND smu.MaterialId = m.Id
   AND sp.WorkcentreId =
   wc.Id
   AND wc.LocationId = l2.Id

top
SourcePriorityView
   Select c.LocationName CustomerName, s.LocationName SupplierName,
   MaterialName, sp.*
   FROM SourcePriorities sp, Materials m, Workcentres wc,
   SiteMaterialUsages
   smu, Locations s, Locations c
   WHERE sp.SiteMaterialUsageId =
   smu.Id
   AND smu.MaterialId = m.Id
   AND wc.ID = sp.WorkcentreId
   AND wc.LocationId =
   s.Id
   AND smu.LocationId = c.Id

top
StockLocationSKUIPlanView
SELECT smu.LocationId, smu.Id SiteMaterialUsageId, l.StockLocationId, smu2.Id StockSiteMaterialUsageId
FROM   SiteMaterialUsages smu, SiteMaterialUSages smu2, locations l
WHERE  smu.LocationId = l.Id
AND    smu2.LocationId = l.StockLocationId
AND    l.StockLocationID IS NOT NULL
AND    smu.MaterialId = smu2.MaterialId
top
SystemDashboardsIPlanView
WITH sd AS
(SELECT d.Name, d.Description, u.Id UserId, d.id FROM Dashboards d, USERS u
 WHERE UserId = 1)
SELECT sd.Name, NVL(d.Description, sd.Description) Description, NVL(d.Id, sd.Id) ID, NVL(d.UserId, sd.userId) UserId
FROM sd LEFT JOIN Dashboards d
ON (d.Name = sd.Name AND d.UserId = sd.UserId)
top
TransportRoutesView

   Select f.LocationName FromLocation, t.LocationName ToLocation,
   tr.*
   from TransportRoutes tr, Locations f, Locations t
   Where tr.FromLocationId
   = f.Id
   AND tr.ToLocationId = t.Id

top
UnitsIPlanView

SELECT u.Id, u.UnitName, t.UnitDescription, UnitTypeId, UnitTypeName, UnitTypeDesc, IsBaseUnit, FromBaseUnit, Dividend, Divisor, LanguageId,
 MaterialTypeId, DividendProductPart, DivisorProductPart, 0 IsConverted
FROM   Units u
JOIN   UnitTypes ut
ON     (ut.Id = u.UnitTypeID)
JOIN IT#Units t
ON     (t.Id = u.Id)
UNION ALL
SELECT u.Id, u.UnitName, t.UnitDescription, UnitTypeId, UnitTypeName, UnitTypeDesc, IsBaseUnit, FromBaseUnit, Dividend, Divisor, LanguageId,
 MaterialTypeId, DividendProductPart, DivisorProductPart, 1 IsConverted
FROM   Units u
JOIN Unittypeconverts uc
ON (uc.ToUnitTypeid = u.Unittypeid)
JOIN   UnitTypes ut
ON     (ut.Id = uc.FromUnitTypeID)
LEFT   JOIN IT#Units t
ON     (t.Id = u.Id)

top
UploadTemplateIPlanView
  SELECT ProcessId,
    MAX(DECODE(Name, 'CorrectMessages', VALUE, NULL)) AS CorrectMessages,
    MAX(DECODE(Name, 'WrongMessages', VALUE, NULL)) AS WrongMessages
  FROM
    ProcessResults
GROUP BY ProcessId
top
UserPermissionsIPlanView
SELECT U.ID UserId, UserName, PageDescription, ActionName, ActionDescription, ActionHint, 
       listagg(RoleDescription, ', ') within group(order by RoleDescription) ROLES
  FROM RolesActions ra
  JOIN ROLES r
    ON (r.Id = ra.roleId)
  JOIN Actions a
    ON (a.Id = ra.ActionId)
  JOIN Usersroles ur
    ON (ur.RoleId = ra.RoleID)
  JOIN Pages p
    ON (p.Id = a.PageId)
  JOIN USERS u
    ON (u.Id = ur.UserID)
 WHERE cloud > 0
 GROUP BY u.Id, UserName, PageDescription, ActionName, ActionHint, ActionDescription
top
UserWidgetsIPlanView
-- System widgets per user roles 
SELECT w.Id, ur.UserId, WidgetName, WidgetDescription, WidgetCategory, WidgetTemplateId, 1 IsSystem 
    FROM  Widgets w, RolesWidgets rw, UsersRoles ur
    WHERE w.id = rw.widgetid
          AND    rw.roleid = ur.roleid
          AND    w.UserId = 1
UNION
-- Actual user widgets
SELECT w.Id, w.UserId, WidgetName, WidgetDescription, WidgetCategory, WidgetTemplateId, 0 IsSystem
    FROM  widgets w
top
WeeklyMonthMapIPlanView
  SELECT DISTINCT DateFromIW AS dateFromWeek, DateFromMonth, WeeklyCoef FROM
(
SELECT DateFrom, DateFromIw, DateFromMonth, COUNT(1) OVER (PARTITION BY DateFromIW, DateFromMonth) / 7  WeeklyCoef
FROM Calendarsources CS, Calendars c, SystemPArameters sp
WHERE cs.CalendarId = c.Id
AND c.Id = sp.Value
AND sp.ParameterName = 'DefaultCalendar'
)
top