COMPILE SUBROUTINE Print_Demand(ReportParm)
#pragma precomp SRP_PreCompiler

/*
	Print Material Demand Report
	10/27/2016 - John C Henry, J.C. Henry & Co., Inc. - Initial Coding
	10/05/2017 - Donald Bakke - No longer select SCHED_DET rows with an end date specified.
	10/24/2018 - Daniel Stieber - Patch added to resolve scheduling conflicts on the same day
*/

DECLARE SUBROUTINE Utility, ErrMsg, Set_Status, Set_Printer, RList, SRP_Stopwatch
DECLARE FUNCTION Set_Printer, Get_Printer, Msg, Get_Status, Printer_Select, obj_Install, Dialog_Box, obj_Location
DECLARE FUNCTION Schedule_Services

$INSERT OIPRINT_EQUATES
$INSERT SCHED_DET_EQUATES
$INSERT WO_LOG_EQUATES
$INSERT APPCOLORS
$INSERT MSG_EQUATES
$INSERT LOGICAL
$INSERT SCHEDULE_EQU

EQU TAB$				TO \09\
EQU TARGET_ACTIVELIST$	TO 5

ErrorTitle  =  'Error in stored procedure Print_Demand'
ErrCode		= ''
ErrorMsg	= ''
SRP_Stopwatch('Reset')
SRP_Stopwatch('Start', 'Initializing')
OPEN 'SCHED_DET' TO SchedDetTable ELSE
	ErrorMsg  =  'Unable to open "SCHED_DET" table.'
	ErrMsg(ErrorTitle:@SVM:ErrorMsg)
	RETURN
END

OPEN 'DICT.SCHED_DET' TO @DICT ELSE
	ErrorMsg = 'Unable to open "SCHED_DET" table.'
	ErrMsg(ErrorTitle:@SVM:ErrorMsg)
	RETURN
END

// Two full week
Today = OCONV(Date(),'D4/')
*Today = OCONV(Date()-60,'D4/')
EndDate	= OCONV(Date()+13,'D4/')


ReactList 		= ''
WOList			= ''
SchedDetKeys	= ''

* SelectSent  = 'SELECT SCHED_DET WITH SCHED_DT GE ':QUOTE(Today):' AND WITH SCHED_DT LE ':QUOTE(EndDate):' BY REACT_NO'
SelectSent  = 'SELECT SCHED_DET WITH SCHED_DT GE ':QUOTE(Today):' BY REACT_NO'
*SelectSent  = 'SELECT SCHED_DET WITH SCHED_DT GE ':QUOTE(Today):' BY REACT_NO'


SRP_Stopwatch('Stop', 'Initializing')
SRP_Stopwatch('Start', 'Data Select')
RList(SelectSent,TARGET_ACTIVELIST$,'','','')
IF Get_Status(errCode) THEN
	ErrMsg(errCode)
	RETURN
END
SRP_Stopwatch('Stop', 'Data Select')
SRP_Stopwatch('Start', 'Build Key List')
Done = 0

LOOP
	READNEXT @ID ELSE Done = 1
UNTIL Done
	ReactNo = @ID[1,'*']
	SchedDt	= @ID[COL2()+1,'*']
	SeqNo	= @ID[COL2()+1,'*']
	
	READ SchedDetRec FROM SchedDetTable,@ID THEN
	
		WONo = SchedDetRec<SCHED_DET_WO_NO$>
	
		LOCATE ReactNo IN ReactList BY 'AR' USING @FM  SETTING Pos ELSE
			ReactList = INSERT(ReactList,Pos,0,0,ReactNo)
		END
		
		LOCATE WONo IN WOList<Pos> USING @VM SETTING WPos ELSE
            WOList 			= INSERT(WOList,Pos,-1,0,WONo)
            // Patch added on 10/24/18 to resolve scheduling conflicts on the same day for
            // the material track report. - djs
            PrevSchedDetKey = SchedDetKeys[-1, 'B':@FM]
            PrevReactNo = Field(PrevSchedDetKey, '*', 1)
            PrevSchedDt = Field(PrevSchedDetKey, '*', 2)               
            If (PrevReactNo EQ ReactNo) and (PrevSchedDt EQ SchedDt) then
                PrevSeqNo   = Field(PrevSchedDetKey, '*', 3)
                NumWO       = DCount(WOList<Pos>, @VM)
                PrevWONo    = WOList<Pos, NumWO - 1>
                SchedEvents = Schedule_Services('GetScheduleEventSummary', ReactNo, WONo, SchedDt, SeqNo, True$)
                StartDt     = IConv(SchedEvents<SCHEDULE_ENTRY_DATE$>, 'D')
                PrevSchedEvents = Schedule_Services('GetScheduleEventSummary', ReactNo, PrevWONo, PrevSchedDt, PrevSeqNo, True$)
                PrevStartDt = IConv(PrevSchedEvents<SCHEDULE_ENTRY_DATE$>, 'D')
                If StartDt GT PrevStartDt then
                    // This is the common case
                    SchedDetKeys = INSERT(SchedDetKeys,-1,0,0,@ID)
                end else
                    // Scheduling irregularity - Insert this key in the second to last position.
                    NumKeys      = DCount(SchedDetKeys, @FM)
                    InsertPos    = NumKeys
                    SchedDetKeys = INSERT(SchedDetKeys,InsertPos,0,0,@ID)
                end
            end else
                SchedDetKeys = INSERT(SchedDetKeys,-1,0,0,@ID)
            end
		END
	END
	
REPEAT

CALL Make.List(0,SchedDetKeys,SchedDetTable,@DICT)
SRP_Stopwatch('Stop', 'Build Key List')	
SRP_Stopwatch('Start', 'Build Report')
IF ReportParm = 'T' THEN

	* Tracking Report
	
	Header		= "'D'":@VM:obj_Install('Get_Prop','CompTitle'):' Material Tracking by Reactor':@VM:"Page  'P'"
	MinDemand	= 0
	
END

IF ReportParm = 'D' THEN

	* Demand Report
	
	MinDemand	= Msg(@WINDOW,'','MIN_DEMAND_QTY')
	Header		= "'D'":@VM:obj_Install('Get_Prop','CompTitle'):' Material Demand with Reactor Queue < ':MinDemand:' Cassettes':@VM:"Page  'P'"
	
END

Set_Status(0)

/*
	Today		= OCONV(Date(),'D4/')
	Tomorrow	= OCONV(Date()+1,'D4/')

	SelectSent  = 'SELECT SCHED_DET WITH SCHED_DT = ':QUOTE(Today):' BY REACT_NO'

	RList(SelectSent,TARGET_ACTIVELIST$,'','','')
	IF Get_Status(errCode) THEN
		ErrMsg(errCode)
		RETURN
	END
*/

* Start of printing process

FileName		= 'Print Material Demand'
Title			= 'Printing Material Demand'

TopMargin		= 1.0
BottomMargin	= 0.75
LeftMargin		= 0.25
RightMargin		= 0.25

Margins = LeftMargin:@FM:TopMargin:@FM:RightMargin:@FM:BottomMargin

PageSetup	= '1'		;* LandScape
PrintSetup	= '2'		;* Preview Normal
PrintSetup<1,2> = '0'	;* All buttons
PrintSetup<1,5> = '1'	;* Page Range
PrintSetup<1,6> = 7		;* full mouse and keyboard support

If @UserName EQ 'MESCATXMUSER' then
    PageSetup	= '1' 							;* Landscape
    PrintSetup  = '0'							;* Print to specific location
    PrintPath	= Printer_Select(PrinterID)		;* Select printer - Displays popup if PrinterPort not found
end else
    * PrintPath = Printer_Select('',1)		;* Get Default printer path
    PrintPath = ''
end
stat = Set_Printer('INIT',FileName,Title,Margins,PageSetup,PrintSetup,PrintPath)

IF stat < 0 THEN
	ErrorMsg	= 'Stat = ' : Stat : ', PrintPath = ' : PrintPath
	GOTO OIPrintErr
end
DateRange = 'Effective ':OCONV(Date(),'D4')


*Header = "'D'":@VM:obj_Install('Get_Prop','CompTitle'):' Material Tracking by Reactor':@VM:"Page  'P'"
Header<-1> = "'T'"
Header<-1> = ''																;* Blank line following heading

font	= 'Arial'
font<2>	= '10'
font<4>	= '0'		;* Bold

stat = Set_Printer('FONTHEADFOOT',font)	; IF stat < 0 THEN GOTO OIPrintErr
stat = Set_Printer('HEADER',Header)		; IF stat < 0 THEN GOTO OIPrintErr

Footer = " 'D' 'T'":@VM:@VM:"Page:  'P'"
stat = Set_Printer('FOOTER',Footer)		; IF stat < 0 THEN GOTO OIPrintErr

* 
@RECCOUNT	= 0
FirstPass	= 1
LastRecord	= 0
FirstLine 	= 1
fontSpacing	= 100

* Make Column Heading

ColHead = ''										; ColFmt = ''
ColHead<1,1>	= 'React No'						; ColFmt<1,1>	= '+^720'
ColHead<1,2>    = 'React Type'                      ; ColFmt<1,2>	= '+<^720'
ColHead<1,3>    = 'Wafer Size'                      ; ColFmt<1,3>	= '+^1000'
ColHead<1,4>	= 'WO No'							; ColFmt<1,4>	= '+^1000'
ColHead<1,5>	= 'Sub Part No'						; ColFmt<1,5>	= '+<1200'
ColHead<1,6>	= 'Epi Part No'						; ColFmt<1,6>	= '+<1200'
ColHead<1,7>	= 'WO Qty'							; ColFmt<1,7>	= '+>720'
ColHead<1,8>	= 'RX Qty'							; ColFmt<1,8> 	= '+>720'
ColHead<1,9>	= 'UnRel Qty'						; ColFmt<1,9> 	= '+>720'
ColHead<1,10>	= 'Kit Location'					; ColFmt<1,10>	= '+^1260'
ColHead<1,11>	= 'Kit Qty'							; ColFmt<1,11> 	= '+^720'
ColHead<1,12>	= '1K Stage Location'				; ColFmt<1,12>	= '+^1260'
ColHead<1,13>	= 'Stage Qty'						; ColFmt<1,13>	= '+^1260'
ColHead<1,14>	= 'PTI Location'					; ColFmt<1,14>	= '+^1260'
ColHead<1,15>	= 'PTI RO'							; ColFmt<1,15>	= '+^1260'


* Zero Accumulators For Each Break

Prev.ReactNo	 	= ''
Last.ReactNo.Break	= 1


* * * * * * *
ReadRecord:
* * * * * * *

* Zero Break Flags To False

ReactNo.Break=0


READNEXT @ID, Which.Value ELSE
	LastRecord		= 1
	ReactNo.Break	= 1
	ReactNo			= Prev.ReactNo
END

S.ATID = @ID

IF FirstPass AND LastRecord THEN
	GOTO Bail
END
 
IF LastRecord THEN GOTO BREAKS


READO @RECORD FROM SchedDetTable,@ID ELSE
	GOTO ReadRecord
END

@RECCOUNT += 1
 
* Calculate Value(s) For Column(s)

S.ATID			= {@ID}
I.ATID			= S.ATID
S.ReactNo		= {REACT_NO}
I.ReactNo		= S.ReactNo
S.WoNo			= {WO_NO}
I.WoNo			= S.WoNo
S.SubPartNo		= XLATE('WO_LOG',S.WoNo,'ORD_SUB_PART_NO','X')
I.SubPartNo		= S.SubPartNo
S.EpiPartNo		= XLATE('WO_LOG',S.WoNo,WO_LOG_EPI_PART_NO$,'X')
I.EpiPartNo		= S.EpiPartNo
S.WO_Qty		= {WO_QTY}
I.WO_Qty		= S.WO_Qty
S.WO_RX_Qty 	= {WO_RX_QTY}
I.WO_RX_Qty 	= S.WO_RX_Qty
S.WO_UnRel_QTY	= {WO_UNREL_QTY}
I.WO_UnRel_QTY	= S.WO_UnRel_QTY
S.Sched_DT		= {SCHED_DT}
I.Sched_DT		= S.Sched_DT
*Changed Here JRO
S.REACT_TYPE    = {REACTOR_TYPE}
S.WAFER_SIZE    = {WAFER_SIZE}

KitData = obj_Location('KitLocations',S.WONo)

SWAP CRLF$ WITH @VM IN KitData

S.KitLocation	= KitData<1>
I.KitLocation	= S.KitLocation

S.KitQty		= OCONV(SUM(KitData<2>) * 25,'MD0,Z')
I.KitQty		= S.KitQty

S.KitCassCnt	= COUNT(KitData<3>,',') + (KitData<3> NE '')
I.KitCassCnt	= S.KitCassCnt

StageData		= obj_Location('StageLocations',S.WONo)

SWAP CRLF$ WITH @VM IN StageData

S.StageLocation	= StageData<1>
I.StageLocation	= S.StageLocation

S.StageQty		= StageData<3>
I.StageQty		= S.StageQty

S.StageCassCnt	= COUNT(S.StageQty,',') + (S.StageQty NE '')
I.StageCassCnt	= S.StageCassCnt

PTIData		= obj_Location('PTILocations',S.WONo)

SWAP CRLF$ WITH @VM IN PTIData

S.PTILocation	= PTIData<1>
I.PTILocation	= S.PTILocation

S.PTIQty		= PTIData<3>
I.PTIQty		= S.PTIQty

S.PTICassCnt 	= COUNT(S.PTIQty,',') + (S.PTIQty NE '')
I.PTICassCnt	= S.PTICassCnt


CassQueueCnt = I.KitCassCnt + I.StageCassCnt + I.PTICassCnt


* TEST FOR CONTROL BREAK(S)
 
 
IF (S.ReactNo NE Prev.ReactNo) OR ReactNo.Break THEN
	ReactNo			= Prev.ReactNo
	Prev.ReactNo	= S.ReactNo
	ReactNo.Break  += 1
END

IF FirstPass THEN
	FirstPass=0
	GOTO DETAIL
END

* * * * * * *
BREAKS:
* * * * * * *

* Print Break Total(s) And Accumulate Total(s)

IF ReactNo.Break THEN
	
	IF ReportParm = 'D' ELSE
		stat = Set_Printer('TEXT')
	END

/*
	ColData = ''
	ColData<1,1> = ''
	ColData<1,2> = ''
	ColData<1,3> = ''
	ColData<1,4> = ''
	ColData<1,5> = ''
	ColData<1,6> = ''
	ColData<1,7> = ''
	ColData<1,8> = ''
	ColData<1,9> = ''
	ColData<1,10> = ''
	
	GOSUB PrintTable
*/	
	

END


* Perform Last Record Output If Done

IF LastRecord THEN
	
	colData = ''
	
	
	GOTO Bail
	
END


* * * * * * *
DETAIL:
* * * * * * *

* Do Conversion If Any


IF ReportParm = 'T' OR CassQueueCnt < MinDemand THEN
	  
	IF S.REACTNO NE "" 		THEN S.REACTNO		= OCONV(S.REACTNO,"MD0,")
	IF S.WONO NE "" 		THEN S.WONO			= OCONV(S.WONO,"MD0")
	IF S.WO_QTY NE "" 		THEN S.WO_QTY		= OCONV(S.WO_QTY,"MD0,")
	IF S.WO_RX_QTY NE ""	THEN S.WO_RX_QTY	= OCONV(S.WO_RX_QTY,"MD0,")
	IF S.WO_UNREL_QTY NE "" THEN S.WO_UNREL_QTY	= OCONV(S.WO_UNREL_QTY,"MD0,")
	IF S.SCHED_DT NE "" 	THEN S.SCHED_DT		= OCONV(S.SCHED_DT,"D4/")

	* PRINT DETAIL LINE
	
* 	If @User4 EQ 'FRANCOIS_R' then
	    
	    COLDATA = ''
	    RowNumber        = 0
	    For each Location in S.PTILocation using @VM setting fPos
	        LocationCassNos  = S.PTIQty<0, fPos>
	        FilteredCassList = ''
	        
	        For each CassNo in LocationCassNos using ','
	            WOMatKey = S.WoNo:'*':CassNo
	            InvActions = Xlate('WO_MAT', WOMatKey, 'INV_ACTION', 'X')
	            NumActions = DCount(InvActions, @VM)
	            CurrAction = InvActions<0, NumActions>
	            If CurrAction EQ 'PLACE' then	                
	                FilteredCassList<0, -1> = CassNo	                
	            end
	        Next CassNo
	        If ( (FilteredCassList NE '') and (Location NE '') ) or ( (FilteredCassList EQ '') and (Location EQ '') ) then
 
	            RowNumber += 1      
	            Convert @VM to ',' in FilteredCassList
                COLDATA<RowNumber,1>  = S.ReactNo
                COLDATA<RowNumber,2>  = S.React_Type
                COLDATA<RowNumber,3>  = S.Wafer_Size
                COLDATA<RowNumber,4>  = S.WoNo
                COLDATA<RowNumber,5>  = S.SubPartNo
                ColData<RowNumber,6>  = S.EpiPartNo
                COLDATA<RowNumber,7>  = S.WO_Qty
                COLDATA<RowNumber,8>  = S.WO_RX_Qty
                COLDATA<RowNumber,9>  = S.WO_UnRel_Qty
                COLDATA<RowNumber,10>  = S.KitLocation
                COLDATA<RowNumber,11>  = S.KitQty				; *ColFmt<1,9>	= '_<1260'
                COLDATA<RowNumber,12> = S.StageLocation
                COLDATA<RowNumber,13> = S.StageQty				; *ColFmt<1,11>	= '_<1260'
                COLDATA<RowNumber,14> = S.PTILocation<0, fPos>
    *            COLDATA<fPos,13>  = S.PTIQty<0, fPos>				; *ColFmt<1,13>	= '_<1260'
                COLDATA<RowNumber,15> = FilteredCassList
	        end
	    Next Location
* 	end else
* 
*        COLDATA = ''
*        COLDATA<1,1>  = S.ReactNo
*        COLDATA<1,2>  = S.WoNo
*        COLDATA<1,3>  = S.SubPartNo
*        ColData<1,4>  = S.EpiPartNo
*        COLDATA<1,5>  = S.WO_Qty
*        COLDATA<1,6>  = S.WO_RX_Qty
*        COLDATA<1,7>  = S.WO_UnRel_Qty
*        COLDATA<1,8>  = S.KitLocation
*        COLDATA<1,9>  = S.KitQty				; *ColFmt<1,9>	= '_<1260'
*        COLDATA<1,10>  = S.StageLocation
*        COLDATA<1,11>  = S.StageQty				; *ColFmt<1,11>	= '_<1260'
*        COLDATA<1,12>  = S.PTILocation
*        COLDATA<1,13>  = S.PTIQty				; *ColFmt<1,13>	= '_<1260'
*    end
    
*    If @User4 EQ 'FRANCOIS_R' then
        If COLDATA NE '' then GoSub PrintTable
*    end else
*	    GOSUB PrintTable
*    end
    
END


GOTO ReadRecord
 

* * * * * * *
Bail:
* * * * * * *

stat = Set_Printer('TERM',1)
SRP_Stopwatch('Stop', 'Build Report')
* If @UserName EQ 'FRANCOIS_R' then SRP_Stopwatch('ShowAll')
RETURN
debug



* * * * * * *
OIPrintErr:
* * * * * * *

ErrMsg(ErrorTitle:@SVM:ErrorMsg)
ErrMsg(ErrorTitle:@SVM:'Set_Printer returned errorcode ':stat)
stat = Set_Printer('TERM',1)

RETURN


* * * * * *
PrintTable:
* * * * * * 

PageHeight			= Get_Printer('PAGESIZE')<2>
PrintableHeight		= PageHeight - TopMargin - BottomMargin
PrinterHeight		= Get_Printer('POS')<2>

stat			= Set_Printer('CALCTABLE',ColFmt:@FM:ColData)
TableSize		= Get_Printer('CALCTABLE')


TableHeight		= TableSize<2>

fontSpacing			= 120

IF ( TableHeight + PrinterHeight >= PrintableHeight ) OR FirstLine THEN
	IF NOT(FirstLine) THEN
		stat = Set_Printer('PAGEBREAK')
	END
	FirstLine = 0
	font<2> = 10
	font<4> = 1		;* Bold
	stat = Set_Printer('FONT',font,'100')

	stat = Set_Printer('ADDTABLE',colFmt,colHead,'',LTGREY$,'',0,TB_ALL)
	
	
	font<4> = 0
	stat = Set_Printer('FONT',font,fontSpacing)
	
	stat = Set_Printer('ADDTABLE',colFmt,'',colData,LTGREY$,'',0,7)
	
END ELSE
	font<2> = 10
	font<4> = 0
	stat = Set_Printer('FONT',font,fontSpacing)
	stat = Set_Printer('ADDTABLE',colFmt,'',colData,LTGREY$,'',1,TB_ALL)

END
	
							
RETURN	 




