'DESPAT_3 - (was $inv1.PF3) lists all uninvoiced orders which have
'           [Completed]="Y" status; pick from list to prepare invoice.
'		used in Office Menu to print all Sales Invoices as at Jan 2011

external  vloadif() dpath sch scw messboxwait() navrecs() fgp bgp cpath
external  increment() PrintReport() messbox() progress() delidxrec() bgi
external  chkdate() fentrybox() entryline() bgs fgi fgs chkfname() gdsoutpath
external  makeidx() remove() vunloadif() vatrate Background() invpath
external  getidxrecs() shopmask userid addidxrec() progtag() colpopup()
external  chkstr() strcount() bpopdb() colpoplines() X_path Xreppath OC_invpath
external  _SWIP_Crystal() scbtm() _GEMS_ShellEx() popuplistcnt() $owner $company

public    ptval ptstr dsa jobnr invdate psa $nextinvnr #vat #net #gross #rcvdnet #rcvdvat
public    #receipts #due custdet[1,1] ftrarray[1] $dateftr $ftrcode #SWIP_Error $reptitle

global    x $index $file InvDetails() S_status
global    ChooseOrder() ProcessInvoice() Titles() y2 y3 ReturnToMenu() c $cn
global    #uninv PrintInvoice() SelectDate() blen Titles_Upd()
global    mth ld from_date last_m_e cm CheckDirectory() sym l c2 r2
global    ReplaceHardSpace() $title custname addr1 addr2 custcity custcode
global    popuplist() Update() uistrcnt() recs plist[1,1] mr dc lc sc pl i
global    pc rec drows k pg tr udelstr() refresh() UpdateCustomer() Approve()
global    abbrv_name #invrecnr #prec Key t1 t5 t6 S_details PrintCustCopy_NEW()
global    w_$title t3 w_addr1 t4 w_addr2 y1 z UpdateVariations() $schref
global    w_custname w_custcity w_custcode w_abbrv_name $line ShowAllReqs()
global    SetupDetails() MarkDespatched() slotrec $ordstat
global    $invoice $invnr $invdate ShowStatus() cr_status bot clf clb
global    ShowFittings2() S_all ShowReceipts() ShowOrders() $dfa1 $ftrappts
global    #ftrappts $day_1 $fitter $fname ftrname ReplaceHardSpace2()
global    $ftgstr ShowDeliveries() #amount varndes SALESINV_entered() BR_Date() $status
global    SetupDetails2() str1 p5 #vatreclaim NextInvNr() $cntr y4  SelectOrders() PrintingInvoice()
global    ReplaceSoftSpace() ClearHardSpaces() $pdf_OC $pdf_inv #calcgross $prior y y5 #BRDinv
global	#newinvrec $serialnr $pcc $swip #balos


MAIN
single-step off					'message "Using SW2K_NEW"
  	Background()
  	bot = 7
  	clb = 13
  	clf = 10
  	p5  = 1
  	redimension custdet[11,2]

  	while true
    		Background()
	  	file unload all
         	x = SelectDate()                     ' message "invdate is:"&date3(invdate)
         	if x = -1
         		exit while
         	end if

         	x=ChooseOrder()					'@L229' message "L87 s.b. 2 from selection:"&str(x)
         	if x = -1
     		continue while
		end if
 		x=PrintingInvoice()							'L111
  	end while
 	ReturnToMenu()
END MAIN


FUNCTION ChooseOrder() 				' select JobNr from DESPAT_3.VW
local k
 	x=SelectOrders()		'Ownership and ALL orders which are marked as: (a) [Completed]="Y" AND (b) len([BRDate])=0
    	if x = -1
     	return (-1)
    	end if
   	vloadif(dpath|"despat_4.vw")
   	order change index "1unproc.idx"		' from Select Orders - includes all CUST_ORD records which
	Background()

'elseif ptstr = "InvoiceÿALLÿselected"					' message "remove REM'ing when finished"
  	data query execute "despat3B.dfq" index "invoice1.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' [Completed]="Y"
' and
' days([DateTB_Inv])<>blank
' and
' len([BRDate])=0
' and
' [SalesAnalysis]<>"X"
' and
' not (deleted)
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
    	if cerror
     	messboxwait(" No orders awaiting invoicing ",0,0,1)
     	return (-1)
    	end if

  	data query execute "despat_5.dfq" index "invoice2.idx" ' exclude orders for shops
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
'   [Customer_Code]<>"T11068" - no record in file
'   and
'   [Customer_Code]<>"T11072" - no record in file
'   and
'   [Customer_Code]<>"T02762" - no record in file
'   and
'   [Customer_Code]<>"T02221" - Fulham Shop Use
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
  	if cerror
    		messboxwait(" No orders awaiting invoicing ",0,0,1)
    		return (-1)
  	end if
  	order sort now dictionary "2invoice.idx" fields "[Fitting_Date;Job_Nr]" ascending
' k=records
' message "2invoice is:"&str(k)
  	vunloadif("despat_4.vw")
  	while true
    		vloadif(dpath|"despat_3.vw")
    		order change index "2invoice.idx"
    		repaint on
    		repaint
    		ptval=0
    		Titles()
    		ptval = navrecs()
	     if ptval = {p} or ptval = {P}
      		jobnr=[Job_Nr]							'message "L321 jobnr selected is:"&str(jobnr)
			$prior=[Prior]							'message "L299 $prior is:"&str($prior)
			#uninv=precord							' message "L317 #uninv is:"&str(#uninv)
 			x=PrintingInvoice()							'L111
' 			return (2)

    		elseif ptval = {o} or ptval = {O}          ' Order Status
      		jobnr = [Job_Nr]
      		repaint off
      		vloadif(dpath|"ordstat4.vw")
      		x=SetupDetails2()
      		vloadif(dpath|"despat_3.vw")
      		Titles()

    		elseif ptval = {Esc}
      		repaint off
      		return (-1)
    		end if
  	end while
END FUNCTION ' ChooseOrder


FUNCTION  SelectOrders()
local ld
'select ALL orders which are marked as: (a) [Completed]="Y" AND (b) len([BRDate])=0
  	vloadif(dpath|"cust_ord.vws")
  	progress(15,10," Searching for Unprocessed orders ",0)
  	data query execute "despat2C.dfq" index "0unproc.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' [Ownership]=$owner
' and
' [BRDate]=blank
' and
' not (deleted)
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
  	if cerror
 	     messboxwait("DP3 L231 - No unprocessed orders ",0,0,1)
    		return (-1)
  	end if
   	progress(15,10," Searching for Completed but Unprocessed orders ",0)
   	data query execute "despat_6.dfq" index "1unproc.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' [Completed]="Y"
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
   	if cerror
 	     messboxwait("DP3 L289 - No unprocessed orders ",0,0,1)
    		return (-1)
   	end if
END FUNCTION ' SelectOrders()


FUNCTION PrintingInvoice()
' message "L225 in PrintingInvoice"
' message "L107 #uninv is:"&str(#uninv)
' message "$prior is:"&str($prior)	
' message "L227 $status is:"&str($status)
' in DESPAT_3.vw
	Background()
	repaint off
    	vloadif(dpath|"despat_4.vw")
	data goto record record-number #uninv
	$status=[Credit_Status]							'message "L234 $status is:"&str($status)
	#balos=[Balance_Due]							'message "#balos is:"&str(#balos)
    	vloadif(dpath|"despat_3.vw")

	if $status="A"									'message "L118 Account Status"
		x=ProcessInvoice()							'L320		
		if x = -1
     		repaint off
        		return (-1)
    		else
			y=BR_Date()
        		return (0)
		end if

	elseif $status="C"				'message "L260 Cash Status - mark as Completed only if Balance=0 otherwise mark as Incomplete"
		if #balos>0				'mark CUST_ORD as Completed="N"
			lock-record
				[Completed]="N"
			write-record
			messboxwait(" This Order has a balance OS - collect balance before invoicing/completing ",0,0,1)
        		return (0)
		end if
		x=messbox(" RETAIL CASH status - mark Job Nr"&jobnr&"as processed? (y/n) ",1,1,1)
		if x=0
		  	if ptstr == "y"                      '  store file & exit
				#BRDinv=record					'message "L152 #BRDinv is:"&str(#BRDinv)
				y=BR_Date()
			else	
				repaint off
        			return (-1)
			end if
      	elseif x = 1
	     	return (0)
      	end if
 	end if
END FUNCTION ' PrintingInvoice


FUNCTION ProcessInvoice()   				' ACCOUNT status only
local currjobnr #currrec
message "L254 $status is:"&str($status)
	repaint off
  	#BRDinv=record                      '
	x=UpdateCustomer()
  	if x = -1
    		return (1)
  	end if
  	x=UpdateVariations()
  	vloadif(dpath|"inv_1.vw")
  	order change key "[Job_Nr]"			'message "jobnr is:"&str(jobnr)
     data find "[Job_Nr]" equal jobnr options ""
	#currrec=record
	x=SALESINV_entered()						' @L1433
	if x=1
   		return (1)
	end if
  	x = PrintInvoice()
  	if x = 1
    		return (1)
  	end if
'   	messbox(" Has invoice nr"&$nextinvnr&"printed correctly? (y/n) ",1,1,1)
'   	if ptstr == "y"                      '  store file & exit
		data goto record record-number #currrec
    		currjobnr=[Job_Nr]			'
' message "L364 currjobnr is:"&str(currjobnr)' message "jobnr is:"&str(jobnr)
    		if currjobnr<>jobnr
		     messboxwait(" Invoice Nr entered against WRONG job!! ",0,0,1)
      		return (1)
    		end if
END FUNCTION ' ProcessInvoice()


FUNCTION Titles_Upd()
  	y2 = format("Update Variation Descriptions","M52")
  	y3 = format(" {Enter} to alter - {F10} to exit ","M52")
  	screen print 7 31 fgp bgp y2
  	screen print 8 31 fgp bgp y3
'   scbtm()
END FUNCTION ' Titles_Upd()


FUNCTION BR_Date()
local $jobnr1 $brdate
' message "L159 in BR_Date()"
    	vloadif(dpath|"despat_3.vw")
	order change physical
	data goto record record-number #uninv
	$jobnr1=[Job_Nr]								'' message "L177 $jobnr1 is:"&str($jobnr1)
	if days([BRDate])<>0
		messboxwait(" Already marked as Processed for Commissions - report JobNr"&jobnr&"to DC or DG ",0,0,1)
		return (-1)
	end if
	lock-record
		[BRDate]=today
	write-record
	$brdate=[BRDate]								' message "L186 $brdate is:"&str($brdate)
	y=len(str($brdate))
	if y=0
		messboxwait("L204 - [BRDate] not written to file; inform Head Office ",0,0,1)
	end if
	repaint off
    	x=delidxrec("2invoice.idx",#BRDinv,2)   			' message "L181 delidxrec result for 2invoice.idx:"&str(x)
	if x <> 0                          ' did NOT delete from index
     	order change key "[Order_Status]"
      	data query execute "despat_3.dfq" index "2invoice.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
'   [Completed]="Y"
'   and
'   [Inv_Nr]=blank
'   and
'   [SalesAnalysis]<>"X"
'   and
'   not (deleted)
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
     	if cerror
     		messboxwait(" No orders awaiting invoicing ",0,0,1)
     		return (1)
     	end if
    	else
     	order change index "2invoice.idx"          ' did delete from index
     	if records = 0
     		messbox(" No more invoices to print ",0,0,1)
     		return (-1)
     	end if
    	end if
END FUNCTION ' BR_Date()


FUNCTION UpdateVariations()
local fentline $reas
	vloadif(dpath|"variat_n.vws")
  	order change key "[Job_Nr]"			'message "jobnr is:"&str(jobnr)
  	data query execute "job_reqn.dfq" index "jobreqn1.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' ³ QUERY is:  [Job_Nr] = jobnr                                        ³
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
  	if cerror
    		vunloadif("variat_n.vws")
  	end if
  	vloadif(dpath|"upd_varn.vw")
  	order change index "jobreqn1.idx"
  	order sort now dictionary "upd_varn.idx" fields "[Var_Nr]" ascending
  	while true
    		repaint on
	    	repaint
    		ptval=0
	    	Titles_Upd()
    		ptval = navrecs()
	    	if ptval = {Enter}
     		fentline = [Reason]
      		while true
        			x = fentrybox(" Amend as required ",50,"",fentline)
        			if x = -1
          			continue while
        			end if
        			$reas = ptstr
        			lock-record
          			[Reason]=$reas
        			write-record
        			exit while
      		end while

    		elseif ptval = {F10}
      		repaint off
      		return (-1)
    		end if
  	end while
END FUNCTION ' UpdateVariations()


FUNCTION MarkDespatched()
	Background()
  	vloadif(dpath|"despat_2.vw")
  	if [Completed] = "Y"
    		if [OrderUpdated]<>"Y"             'check OrderUpdated = "Y"
      		messboxwait(" Order details NOT yet entered - cannot process ",0,0,1)
			Background()
	      	return (1)
    		end if
  	else
    		messbox("L952"&jobnr&"-"&[CustOrd_Name]&"to be invoiced? (y/n) ",1,1,1)
    		if ptstr == "y"
'check Updated
      		if [OrderUpdated]<>"Y"             'check OrderUpdated = "Y"
        			messboxwait(" Order details NOT yet entered - cannot process ",0,0,1)
				Background()
		          return (1)
      		end if
      		lock-record
        			[Completed] = "Y"
        			[Last_Update]=today
      		write-record
      		return (0)
    		else
      		return (1)
    		end if
  	end if
END FUNCTION ' MarkDespatched()


FUNCTION SetupDetails()
  	progress(fgp,bgp," Checking for existing order ",0)
  	vloadif(dpath|"ordstat4.vw")
  	order change key "[Job_Nr]"
  	data find "[Job_Nr]" equal jobnr options "gw"
  	if cerror                               '   if none - then return
    		messbox(" Job not found ",1,0,0)
    		return (-1)
  	else
    		while true
      		slotrec  = [Appt_Slots]
	      	$ordstat = [Order_Status]
     	 	$invoice = [Completed]
      		$invnr   = [Inv_Nr]
	      	$invdate = [Invoice_Date]
     	 	repaint on
      		repaint
	      	ShowStatus()
     	 	screen save 1 1 8 scw S_details
      		repaint off
	      	screen shortrestore S_details
     	 	vunloadif("ordstat4.vw")
      		if $invnr<>blank
        			messboxwait(" Already invoiced ",0,0,1)
        			return (1)
      		end if
      		return (0)
    		end while
  	end if
END FUNCTION ' SetupDetails()


FUNCTION ShowStatus()
local mess1 r1 r2 c1 c2 cl1 cl2 i
'
  r1 = 5
  r2 = r1+3
  c1 = 80
  c2 = c1+20
  if $invoice = "Y"
    cl1 = 15
    cl2 = 10
    screen clear box r1 c1 r2 c2 cl1 cl2
    screen print r1+1 c1+5 cl1 cl2 "ÿÿINVOICED"
    screen print r1+2 c1+2 cl1 cl2 $invnr|" - "|date2($invdate)

  else
    mess1 = case $ordstat ("A","Initial only")("U","All details held")\
  ("R","To be authorised")("H","Held for check")("V","Rejected")("P","Authorised")\
  ("L","Being prepared")("D","Despatched") else "Missing"
    if $ordstat = "A"
      cl1 = 14
      cl2 = 0
      screen clear box r1 c1 r2 c2 cl1 cl2
      screen print r1+1 c1+5 cl1 cl2 "ORDER STATUS"
      screen print r1+2 c1+5 cl1 cl2 mess1
    elseif $ordstat = "U"
      cl1 = 14
      cl2 = 0
      screen clear box r1 c1 r2 c2 cl1 cl2
      screen print r1+1 c1+5 cl1 cl2 "ORDER STATUS"
      screen print r1+2 c1+3 cl1 cl2 mess1
    elseif $ordstat = "R"
      cl1 = 10
      cl2 = 0
      screen clear box r1 c1 r2 c2 cl1 cl2
      screen print r1+1 c1+5 cl1 cl2 "ORDER STATUS"
      screen print r1+2 c1+3 cl1 cl2 mess1
    elseif $ordstat = "V"
      for i = 1 to 5
        cl1 = 4
        cl2 = 0
        screen clear box r1 c1 r2 c2 cl1 cl2
        screen print r1+1 c1+5 cl1 cl2 "ORDER STATUS"
        screen print r1+2 c1+7 cl1 cl2 mess1
        wait .05
        cl1 = 0
        cl2 = 4
        screen clear box r1 c1 r2 c2 cl1 cl2
        screen print r1+1 c1+5 cl1 cl2 "ORDER STATUS"
        screen print r1+2 c1+7 cl1 cl2 mess1
        wait .1
      end for
    elseif $ordstat = "H"
      for i = 1 to 5
        cl1 = 4
        cl2 = 0
        screen clear box r1 c1 r2 c2 cl1 cl2
        screen print r1+1 c1+5 cl1 cl2 "ORDER STATUS"
        screen print r1+2 c1+4 cl1 cl2 mess1
        wait .05
        cl1 = 0
        cl2 = 4
        screen clear box r1 c1 r2 c2 cl1 cl2
        screen print r1+1 c1+5 cl1 cl2 "ORDER STATUS"
        screen print r1+2 c1+4 cl1 cl2 mess1
        wait .1
      end for
    elseif $ordstat = "P"
      cl1 = 10
      cl2 = 0
      screen clear box r1 c1 r2 c2 cl1 cl2
      screen print r1+1 c1+5 cl1 cl2 "ORDER STATUS"
      screen print r1+2 c1+6 cl1 cl2 mess1
    elseif $ordstat = "L"
      cl1 = 4
      cl2 = 0
      screen clear box r1 c1 r2 c2 cl1 cl2
      screen print r1+1 c1+5 cl1 cl2 "ORDER STATUS"
      screen print r1+2 c1+4 cl1 cl2 mess1
    elseif $ordstat = "D"
      cl1 = 10
      cl2 = 0
      screen clear box r1 c1 r2 c2 cl1 cl2
      screen print r1+1 c1+5 cl1 cl2 "ORDER STATUS"
      screen print r1+2 c1+6 cl1 cl2 mess1
    end if
  end if
  screen save r1 c1 r2 c2 S_status
END FUNCTION ' ShowStatus()


FUNCTION SetupDetails2()
local $chstr
  screen save 1 1 sch scw S_all
  data find "[Job_Nr]" equal jobnr options "gw"
  if cerror                               '   if none - then return
    messbox(" Job not found ",1,0,0)
    return (-1)
  else
    slotrec  = [Appt_Slots]
    $ordstat = [Order_Status]
    $invoice = [Completed]
    $invnr   = [Inv_Nr]
    $invdate = [Invoice_Date]
  end if

  $chstr = "Fittings Orders Requisitions Receipts"
  while true
    x = colpopup(8,31,20,$chstr,"",1,0,clf,clb,0,7)  'highlight date & press {Enter} to show deliveries
    if x = -1
      return (-1)
    end if
    if ptstr = "Receipts"
      ShowReceipts()
      screen shortrestore S_all

    elseif ptstr = "Fittings"
      x = ShowFittings2()
      screen shortrestore S_all

    elseif ptstr = "Orders"
      x = ShowOrders()
      inchar
      screen shortrestore S_all

    elseif ptstr = "Requisitions"
      x = ShowAllReqs()

    end if
  end while

END FUNCTION ' SetupDetails2()


FUNCTION ShowFittings2()
local $ftgstr $fname d
  $ftgstr = ""
  repaint off
  vloadif(dpath|"ftr_list.vws")
  vloadif(dpath|"appntmnt.vws")
  order change physical
  data query execute "job_reqn.dfq" index "job_reqn.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' ³ QUERY is:  [Job_Nr] = jobnr and not (deleted)                      ³
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
  if cerror
    messbox(" No appointments for this job ",0,0,1)
    return (1)
  end if
  $dfa1 = ""
  $ftrappts = ""

'--------------------------------------search to remove duplicate days
  if records > 1
    data goto record first
    for i = 1 to records
      $dfa1 = left([DFA],11)
      x = chkstr($dfa1,$ftrappts)
      if x = -1
        $ftrappts = $ftrappts&$dfa1
      end if
      data goto record next
    end for
    x=strcount($ftrappts)                'message "x is:"&str(x)
    #ftrappts = ptval                    '
  else
    $ftrappts = left([DFA],11)
    #ftrappts = 1                   '
  end if
  redimension ftrarray[#ftrappts]
  for i = 1 to #ftrappts
    d = days(left(group($ftrappts,i),5))
    $day_1 = left(date2([Date]),6)|right(date2([Date]),2) 'message "$day_1 is:"&str($day_1)
    $fitter = right(group($ftrappts,i),6) 'message "$fitter) is:"&str($fitter)
    $fname = filelookup([FTR_LIST.Fitter_Code],[FTR_LIST.Nickname],$fitter)
    ftrname = ReplaceHardSpace2($fname,len($fname))
    $ftgstr = $ftgstr&$day_1|"ÿ"|left(ftrname|"ÿÿÿÿÿÿÿÿ",8)     ' HARD space
    ftrarray[i] = $fitter
  end for

  while true
    x = colpopup(5,8,20,$ftgstr,"",1,0,clf,clb,0,7)  'highlight date & press {Enter} to show deliveries
    $dateftr = ptstr
    if x = -1
      repaint off
      exit while
    end if
    screen shortrestore dsa
    $ftrcode = ftrarray[ptval]
    ShowDeliveries()
  end while

  vunloadif("appntmnt.vws")
  vunloadif("delivr_1.vw")
  vunloadif("ftr_list.vws")
END FUNCTION ' ShowFittings2()


FUNCTION ShowDeliveries()
  progress(15,10," Please wait ... finding deliveries ",0)
  fgp = clf
  bgp = clb
  repaint off
  vloadif(dpath|"delivr_1.vw")
  order change key "[Job_Nr]"
  data query execute "job_reqn.dfq" index "sd1.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
'   [Job_Nr] = jobnr
'   and
'   not(deleted)
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
  if cerror
    screen shortrestore psa
    messboxwait(" NO deliveries booked ",0,0,1)
    fgp = fgpleasing
    bgp = bgpleasing
    return (1)
  end if
  data query execute "showdel1.dfq" index "sd2.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
'   [Date_Out] = date2(left($dateftr,8))
'   and
'   [Fitter_Code]=$ftrcode
'   and
'   not(deleted)
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
  if cerror
    screen shortrestore psa
    messboxwait(" NO deliveries booked ",0,0,1)
    fgp = fgpleasing
    bgp = bgpleasing
    return (1)
  end if
  screen shortrestore psa
'   x = bpopdb("delivr_1",6,"","[ScrollView]","L45","[FtrCode]","L6","[Job_Nr]",5,31,20,78,"",0)
  x = bpopdb("delivr_1",6,"","[ScrollView]","L53","[FtrCode]","L6","[Job_Nr]",5,27,20,79,"",0)
  fgp = fgpleasing
  bgp = bgpleasing
END FUNCTION ' ShowDeliveries()


FUNCTION ShowOrders()
local $ordstr
  $ordstr = ""
  repaint off
  vloadif(dpath|"variat_n.vws")
  order change physical
  data query execute "job_reqn.dfq" index "job_reqn.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' ³ QUERY is:  [Job_Nr] = jobnr and not (deleted)                      ³
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
  if cerror
    messbox(" Job Nr not found ",0,0,1)
    return (1)
  end if
  for i = 1 to records
    #amount=right("ÿÿÿÿÿÿÿÿÿÿ"|currency([Amount_Gross]),10)
    varndes = ReplaceHardSpace2(date2([Date])&format([Reason],"L50")&#amount,70)
    $ordstr = $ordstr&varndes          'message "$popstr is:"&str($popstr)
    data goto record next
  end for
  vunloadif("variat_n.vws")
  while true
    x = colpoplines(10,5,23,$ordstr,"",1,0,clf,clb,14,3)  'highlight date & press {Enter} to show deliveries
    if x = -1
      exit while
    end if
    screen shortrestore dsa
  end while
END FUNCTION ' ShowOrders()


FUNCTION ShowReceipts()
local rcptdes $rcpstr
  $rcpstr = ""
  repaint off
  ptval=0
  vloadif(dpath|"os_rcpts.vw")
  order change key "[Job_Nr]"
  data query execute "vu_cash" index  "#1stcash.idx"
' ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»
'   [Job_Nr] = jobnr
' ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ¼
  if cerror
    messbox(" No cash received for this order ",0,0,1)
    vunloadif("os_rcpts.vw")
    return (0)
  end if
  for i = 1 to records
    #amount=right("ÿÿÿÿÿÿÿÿÿÿÿÿ"|currency([Amount_Received]),12)
    rcptdes = ReplaceHardSpace(date2([Date_Of_Receipt])&format([Method_Of_Payment],"L6")&[Entered_By]&format([Authorisation],"L20")&#amount)
    $rcpstr = $rcpstr&rcptdes          'message "$popstr is:"&str($popstr)
    data goto record next
  end for
  vunloadif("os_rcpts.vw")
  x = colpoplines(10,3,20,$rcpstr,"",1,0,clf,clb,14,3)  'highlight date & press {Enter} to show deliveries
  screen shortrestore dsa
  inchar
END FUNCTION ' ShowReceipts()


FUNCTION ShowAllReqs()
local y2 y1 y4 $desc $reqstr
  vloadif(dpath|"allreqn2.vw")
  order change key "[JobNr]"
  data query execute "all_reqn.dfq" index "all_req1.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' ³ QUERY is:  [Job_Nr] = jobnr                                        ³
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
  if cerror
    x = remove("all_reqn.idx")                ' create temp index for allocation
    x = makeidx("requsn","all_reqn.idx","0",1)
    if x = -1
      message "makeidx() failed"
    end if
    y4 = format("ÿNo requisitions entered for this job ","M71")
    screen print 10 5 15 12 y4
  else                               ' order by ListOrder & prodMRC
    order sort now dictionary "all_reqn.idx" fields "[Lst_Stck;Product_MRC]" ascending
    data goto record first
    for i = 1 to records
      $desc = ReplaceHardSpace2([DesColor],len([DesColor]))   'message "$desc is:"&str($desc)
      $reqstr = $reqstr&$desc
'     ftrarray[i] = $fitter
      data goto record next
    end for
    vunloadif("allreqn2.vw")
    x = colpopup(8,5,20,$reqstr,"",1,0,clf,clb,0,7)  'highlight date & press {Enter} to show deliveries
    if x = -1
      return (-1)
    end if
  end if
END FUNCTION ' ShowAllReqs()


FUNCTION ReplaceHardSpace2(str1,bw)
local j r m l_last #addn
  m = ""
  for j = 1 to len(str1)
    r = mid(str1,j,1)
    if r = " "
      r = "ÿ"                          ' replace hard space
    end if
    m = m|r
  end for

  if len(m) < bw
    #addn = bw-len(m)
  else
    #addn = mod(len(m),bw)
  end if
  m = m|repeat("ÿ",#addn)
  return (m)
END FUNCTION ' ReplaceHardSpace2()


FUNCTION InvDetails()
' in view INV_1.VW
local #sumgross
  	vloadif(dpath|"inv_1.vw")
	#due=[Balance_Due]                 		'message "L964 #due is:"&str(#due)
  	#gross=[Invoice_Total]             		'message "#gross is:"&str(#gross)
  	#sumgross=tablesum([Amount_Gross]) 		'message "#sumgross is:"&str(#sumgross)
  	if abs(#gross-#sumgross)>.1
    		message " Gross Invoice value WRONG - inform Head Office "
    		return (1)
  	end if
  	#receipts = tablesum([Amount_Received],[Method_Of_Payment]<>"BACS")'message "#receipts is:"&str(#receipts)
  	if abs((#gross-#receipts)-#due)>.01
    		x=(#gross-#receipts) - #due 'message "x is:"&str(round(x,20))
    		messboxwait(" Cash receipts WRONG (diff of"&currency(x)|") - inform Head Office ",0,0,1)
    		return (1)
  	end if
  	#receipts = "ÿÿPayments received by"&date2(invdate)&"ÿÿ"&currency(tablesum([Amount_Received]))

'   #net = #gross/((100+vatrate)/100)    '
  	#net = [Net_Invoice]                          		'message "L1175 #net is:"&str(#net)
  	#vat = #gross - #net                 				'message "#vat is:"&str(#vat)
  	if abs(#gross-#net-#vat)>.01
    		x=(#gross - #net)-#vat 'message "x is:"&str(round(x,20))
    		messboxwait(" VAT WRONG (diff of"&currency(x)|") - inform Head Office ",0,0,1)
    		return (1)
  	end if
	#calcgross=#net*(100+vatrate)/100					'message "L1185 #calcgross is:"&str(#calcgross)
  	if abs(#calcgross-#gross)>.01
    		x=#gross-#calcgross						'message "x is:"&str(round(x,20))
    		messboxwait(" VAT WRONG (diff of"&currency(x)|") inform Head Office -"&jobnr,0,0,1)
    		return (1)
  	end if

  	#net = "ÿÿNet invoice value:"&currency(#net) 'message "#net is:"&str(#net)
'   #vat = "- VAT @"&str(vatrate)|"%"&currency(#vat) 'message "#vat is:"&str(#vat)
  	#vat = "(VAT @"&str(vatrate)|"%"&currency(#vat)|")"
  	if #due > 0
    		#due = "ÿBalance now due"&currency(#due)
  	elseif #due = 0
    		#due = "ÿÿÿInvoice paid in full"
  	else
    		#due = ""
  	end if
  	#gross = "- TOTAL Invoice value"&currency(#gross)
END FUNCTION ' InvDetails()


FUNCTION ReplaceSoftSpace(str1)
local j r m l_last #addn
  m = ""
  for j = 1 to len(str1)
    r = mid(str1,j,1)
    if r = "ÿ"
      r = " "                          ' replace with soft space
    end if
    m = m|r
  end for
  return (m)
END FUNCTION ' ReplaceSoftSpace()


FUNCTION ClearHardSpaces()		'message "ClearHardSpaces()"
  	vloadif(X_path|"X_inv_a.vws")
  	t1=dbget("[Title]")                'message "t1 is:"&str(t1)
  	t1=ReplaceSoftSpace(t1)            'message "t1 is:"&str(t1)
	lock-record
  		x=dbput("[Title]",t1)
	write-record
  	vunloadif("X_inv_a.vws")
  	vloadif(X_path|"X_inv_b.vws")
	if records>0
  		for i = 1 to records
    			t1=dbget("[Reason]")             'message "t1 is:"&str(t1)
    			t1=ReplaceSoftSpace(t1)          'message "t1 is:"&str(t1)
			lock-record
    				x=dbput("[Reason]",t1)
			write-record
  		end for
	  	order change physical
	end if
  	vunloadif("X_inv_b.vws")
END FUNCTION ' ClearHardSpaces()


FUNCTION SALESINV_entered()
local $salescode
' message "L1438 in screen - despat_3.vw"
	$salescode=case left(jobnr,1) ("R","RAY001")("S","SHN001")("T","TRA001")("P","PUT001")("F","FUL001")("W","WAR001") else "WAR001"
   	#gross=[Invoice_Total]             			'message "L1328 #gross is:"&str(#gross)
  	#net=[Net_Invoice]                          		'message "#net is:"&str(#net)
  	#vat=#gross-#net                 				'message "L1328 #vat is:"&str(#vat)
	custname=[CustOrd_Name]						'message "custname is:"&str(custname)
  	vloadif(dpath|"salesinv.vws")
    	data enter lock
      	[JobNr]=jobnr
		[Ownership]=$owner
     write-record
	#newinvrec=precord								'message "#newinvrec is:"&str(#newinvrec)
	$serialnr=[Serial]								'message "$serialnr in SALESINV is:"&str($serialnr)
	vloadif(dpath|$owner|"invnr.vws")      ' [invnr] is the Counter
	data enter lock
		[Serial]=$serialnr
		[JobNr]=jobnr
		[Date]=today
		[userid]=userid
		[Timed]=now
	write-record
  	$cntr=[invnr]									'message "D3 L1073 $cntr in #invnr.db is:"&str($cntr)
   	$nextinvnr = right("000000"|str($cntr),6)			'message "L1069 $nextinvnr is:"&str($nextinvnr)
	$salescode=case left(jobnr,1) ("R","RAY001")("S","SHN001")("T","TRA001")("P","PUT001")("F","FUL001")("W","WAR001") else "WAR001"
	#rcvdnet=#net
	#rcvdvat=#vat
  	vloadif(dpath|"salesinv.vws")
	data goto record record-number #newinvrec
' message "L1076 $nextinvnr is:"&str($nextinvnr)
    	lock-record
      	[Inv_Nr]=$nextinvnr
      	[InvoiceDate]=today
		[CustomerName]=custname
		[NET_Inv]=#rcvdnet
		[VATvalue]=#rcvdvat
		[SalesCode]=$salescode
     write-record
END FUNCTION 'SALESINV_entered()


FUNCTION UpdateCustomer()
  	#invrecnr = precord								'message "L1472 #invrecnr is:"&str(#invrecnr)
  	vloadif(dpath|"inv_1.vw")
    	order change key "[Job_Nr]"
    	data find "[Job_Nr]" equal jobnr options ""
	if cerror
		messboxwait(jobnr&"not found report to Head Office ",0,0,1)
    		return (-1)
	end if
'   	data goto record record-number #invrecnr

  	custdet[1,1] = [Title]
  	custdet[1,2] = dbfldinfo("[Title]",2)
  	custdet[2,1] = [Customer_Name]
  	custdet[2,2] = dbfldinfo("[Customer_Name]",2)
'   	custdet[2,1] = [CustOrd_Name]
'   	custdet[2,2] = dbfldinfo("[CustOrd_Name]",2)
  	custdet[3,1] = [Address_1]
  	custdet[3,2] = dbfldinfo("[Address_1]",2)
  	custdet[4,1] = [Address_2]
  	custdet[4,2] = dbfldinfo("[Address_2]",2)
  	custdet[5,1] = [City/Town]
  	custdet[5,2] = dbfldinfo("[City/Town]",2)   		'fm CUSTOMER
  	custdet[6,1] = [Postcode]
  	custdet[6,2] = dbfldinfo("[Postcode]",2)

  	x=Approve()				' message "l202/x is:"&str(x)
  	if x = -1
    		return (-1)
  	end if
  	abbrv_name = proper(left(custdet[2,1],7))
  	if len(custdet[2,1]) = 0
    		messboxwait(" Customer's name has been omitted - pls contact David @ HO ",0,0,1)
  	end if
  	if len(abbrv_name)=0
    		messboxwait(" Customer's abbrv'd name has been omitted - pls contact David @ HO ",0,0,1)
  	end if
  	if cr_status <> "T"
    		lock-record
      		[Title]         = custdet[1,1]
      		[Customer_Name] = custdet[2,1]
      		[CustOrd_Name]  = custdet[2,1]
      		[Address_1]     = custdet[3,1]
      		[Address_2]     = custdet[4,1]
      		[City/Town]     = custdet[5,1]
      		[Postcode]      = custdet[6,1]
      		[Abbrv_Name]    = abbrv_name
      		[CustOrdAbbrv]  = abbrv_name
    		write-record
  	end if
  	clear custdet[]
  	return (0)
END FUNCTION ' UpdateCustomer()


FUNCTION Approve()
local t1 t2 t3 t4 t5 t6 t7
  	repaint off
  	while true
    		t1 = ReplaceHardSpace(custdet[1,1])
    		t2 = ReplaceHardSpace(custdet[2,1])
    		t3 = ReplaceHardSpace(custdet[3,1])
    		t4 = ReplaceHardSpace(custdet[4,1])
    		t5 = ReplaceHardSpace(custdet[5,1])
    		t6 = ReplaceHardSpace(custdet[6,1])
'     		x = popuplist(10,20,20,t1&t2&t3&t4&t5&t6,chr(24)&chr(25)&"{Enter} amends - {F10} to continue",1,0)
    		x = popuplist(12,35,20,t1&t2&t3&t4&t5&t6,chr(24)&chr(25)&"{Enter} amends - {F10} to continue",1,0)
    		if x = -1
      		messbox(" Abandon this invoice? (y/n) ",1,0,1)
      		if ptstr == "y"
        			return (-1)
      		end if
    		elseif x = 1
      		return (0)
    		end if
    		screen shortrestore dsa
    		if rec = 1
      		$line = 1
      		custdet[1,1] = Update(custdet[1,1],custdet[1,2])

    		elseif rec = 2
			messboxwait(" Cannot alter Customer name - contact Head Office ",0,0,1)

    		elseif rec = 3
      		$line = 3
      		custdet[3,1] = Update(custdet[3,1],custdet[3,2])

    		elseif rec = 4
      		$line = 4
      		custdet[4,1] = Update(custdet[4,1],custdet[4,2])

    		elseif rec = 5
      		$line = 5
      		custdet[5,1] = Update(custdet[5,1],custdet[5,2])

    		elseif rec = 6
      		$line = 6
      		custdet[6,1] = Update(custdet[6,1],custdet[6,2])

    		elseif ptstr==p5					' "CORRECT" selected
       		screen clear box 1 1 sch scw 0 0 no-border
       		repaint off
      		exit while
    		end if
  	end while
END FUNCTION ' Approve()


FUNCTION Update(e,w)
local $m
  while true
    case $line
      when 5
       $m = "*20{[A-Za-z\ ]U}"
      when 6
       $m = "AU*7{[A-Za-z1234567890\ ]U}"
      otherwise
       $m = ""
    end case

    x = entryline(" Correct as necessary ",w,$m,e,19,21,43)
    if $line=5
      ptstr=UPPER(ptstr)
    end if
    return (ptstr)
  end while
END FUNCTION ' Update(e,w)


FUNCTION ReplaceHardSpace(str1)
local j r m bw l_last #addn
  bw = 39                              ' boxwidth
  m = ""
  for j = 1 to len(str1)
    r = mid(str1,j,1)
    if r = " "
      r = "ÿ"                          ' replace hard space
    end if
    m = m|r
  end for

  if len(m) < bw
    #addn = bw-len(m)
  else
    #addn = mod(len(m),bw)
  end if
  m = m|repeat("ÿ",#addn)
  return (m)
END FUNCTION ' ReplaceHardSpace()


FUNCTION PrintInvoice()							'
' message "L1253 PrintInvoice "
' message "L1616 screen?? is:"&str(x)
	x = InvDetails()
  	if x = 1
    		return (1)
  	end if
  	Background()
  	$index = "onlyone.idx"
  	$file = "cust_ord"
  	remove($index)
  	x = makeidx($file,$index,str(precord),3)    '
  	order change index $index
  	$cn=0
  	if [Invoice_Total] < 0               ' Credit Notes
    		$cn=1                              ' set marker
  	end if
    	remove(X_path|"X_inv_a.*")
' message "L1265 $nextinvnr is:"&str($nextinvnr)
    	data query execute "not_del.dfq" Smart4 X_path|"X_inv_a" fields "[1|"|str(dbinfo(db_fields))|"]"
    	vunloadif("X_inv_a.vws")
    	vloadif(dpath|"variat_n.vws")
    	remove(X_path|"X_inv_b.*")
    	data query execute "allVreqn.dfq" Smart4 X_path|"X_inv_b" fields "[1|"|str(dbinfo(db_fields))|"]"
    	vunloadif("X_inv_b.vws")
    	vloadif(X_path|"X_inv_a.vws")
    	lock-record
     	[Inv_Nr]=$nextinvnr
    	write-record
    	vunloadif("X_inv_a.vws")
    	ClearHardSpaces()
    	vloadif(dpath|"inv_1.vw")
    	$pdf_inv=invpath|$nextinvnr|".pdf"        	' message "L1524 $pdf_inv is:"&str($pdf_inv)
    	if $cn=0	'  PrintCustCopy_NEW()   ' returns 0 for Office copy only or 1 for both
		$pcc=PrintCustCopy_NEW()				' at L1073
' 		if $invtype="N"					' Normal i.e. not a deposit' message "L877  Showing invoice `S' - show only"
' message "D3 L1282 $owner is:"&$owner
			$reptitle=$owner|"nvcstLA"		'message "L159 $reptitle is:"&str($reptitle)
  			$swip=_SWIP_Crystal(Xreppath|$reptitle,"S",0,1,"")	'message "$swip is:"&str($swip)
 			$swip=_SWIP_Crystal(Xreppath|$reptitle,"EP",0,1,$pdf_inv)
' 		elseif $invtype="D"					' DEPOSIT no paper copy
' 			$reptitle=$owner|"nvdepLC"				' message "L181 $reptitle is:"&str($reptitle)
' 	      	$swip=_SWIP_Crystal(Xreppath|$reptitle,"S",0,1,$pdf_inv)
' 	      	$swip=_SWIP_Crystal(Xreppath|$reptitle,"EP",0,1,$pdf_inv)
'       	end if
	    	$pdf_OC=OC_invpath|$nextinvnr|"OC.pdf"        'message "L990 $pdf_OC is:"&str($pdf_OC)
      	_SWIP_Crystal(Xreppath|$owner|"OCdepLC","EP",0,1,$pdf_OC)
	else                               ' Credit Note
     	_SWIP_Crystal(Xreppath|"crn_cust","S",0,1,"")
      	_SWIP_Crystal(Xreppath|"crn_offc","EP",0,1,$pdf_inv)
    	end if
' 		x=PrintCustCopy_NEW()				'
'      	if x=0               			'YES - print PAPER inv	message "L1565  print PAPER copy"
'          		_SWIP_Crystal(Xreppath|"invcstLA","S",0,1,"")
' 	      	_SWIP_Crystal(Xreppath|"invcstLA","EP",0,1,$pdf_inv)
' 		else							'NO - do NOT print paper just store	message "L1569 do NOT print PAPER copy"
' 	      	_SWIP_Crystal(Xreppath|"invcstLA","EP",0,1,$pdf_inv)
'       	end if
' ' message "print Office Copy"
' 	    	$pdf_OC=OC_invpath|$nextinvnr|"OC.pdf"        'message "L1536 $pdf_OC is:"&str($pdf_OC)
' ' message "L1536 $pdf is:"&str($pdf)
'       	_SWIP_Crystal(Xreppath|"inv_offc","EP",0,1,$pdf_OC)
' 	else                               ' Credit Note
'      	_SWIP_Crystal(Xreppath|"crn_cust","S",0,1,"")
'       	_SWIP_Crystal(Xreppath|"crn_offc","EP",0,1,$pdf_inv)
'     	end if
'
' 	if file($pdf_inv)=TRUE
' 		_GEMS_ShellEx("open",$pdf_inv,"",8)
' 	else
' 		messboxwait("L1516\ Invoice `"|$nextinvnr|"' could not be found - report to DC ",0,0,1)
' 		screen clear box 1 1 sch scw 0 0 no-border
' 		repaint off
' 	end if

  	vloadif(dpath|"despat_3.vw")
  	order change key "[Job_Nr]"
  	data find "[Job_Nr]" equal jobnr options ""
END FUNCTION ' PrintInvoice()


' FUNCTION PrintCustCopy_NEW()   ' returns 0 for Office copy only or 1 for both
'   	if left([Job_Nr],1)="W"
'     		return (1)
'   	elseif [Balance_Due]>.1
'     		return (1)
'   	elseif [Delivery_Address_1]<>[Address_1]
'     		return (1)
'   	else
'     		messbox(" Print PAPER copy of the invoice? (y/n) ",1,1,1)
'     		if ptstr == "y"
'       		return (0)
'     		else
'       		return (1)
'     		end if
'   	end if
' END FUNCTION 'PrintCustCopy_NEW()


FUNCTION PrintCustCopy_NEW()   ' returns 0 for Office copy only or 1 for both
  	if left([Job_Nr],1)="W"
    		return (1)
  	elseif [Balance_Due]>.1
    		return (1)
  	elseif [Delivery_Address_1]<>[Address_1]
    		return (1)
  	else
    		return (1)
  	end if
END FUNCTION 'PrintCustCopy_NEW()






FUNCTION NextInvNr()
	vloadif(dpath|"inv_nr.vws")
	data enter lock
		[JobNr]=jobnr
		[Date]=today
		[userid]=userid
		[Timed]=now
	write-record
  	$cntr=[invnr]						'message "$cntr is:"&str($cntr)
   	$nextinvnr = right("000000"|str($cntr),6)
	vloadif(dpath|"despat_3.vw")
END FUNCTION ' NextInvNr()


FUNCTION Titles()
  y2 = format("  Order  Name & Delivery Address                          Ftg Date      Inv Val    Bal o/s  Action","L100")
  y3 = format(" {P}rint/Process Order or Invoice - {O}rder status - {Esc} exits ","M100")
  y4 = format(" Lines in RED are Customer orders PRIOR to 29 FEB 2020 - invoiced as previously ","M100")
  y5 = format(" Grey Lines are Customer orders AFTER 29 FEB 2020 - select to mark as COMPLETE ","M100")
  screen print 2 1 fgp bgp y2
  screen print 21 1 fgp bgp y3
'   screen print 22 1 12 0 y4
'   screen print 23 1 7 0 y5
'   scbtm()
END FUNCTION ' Titles()


FUNCTION ReturnToMenu()
  screen clear box 1 1 sch scw 0 0 no-border
  repaint off
  file unload all
  transfer cpath|"pm_menu.psl" in-memory
END FUNCTION ' ReturnToMenu()


FUNCTION SelectDate()
  	while true
    		x=fentrybox(" Confirm Date for Invoices ",10,"##\/##\/####",today)
    		if x=0
	     	invdate = ptstr
      		if chkdate(invdate,1) = -1
        			messbox(" Incorrect date - re-enter ",0,0,1)
        			continue while
      		end if
      		return (0)
    		elseif x = -1
	      	return (-1)
      	end if
  	end while
END FUNCTION ' SelectDate()


FUNCTION CheckDirectory()
local invpath
  invpath = left(dpath,1)|":\reports\invoices\"|mid(date1(invdate),4,3)|"-"|right(date1(invdate),2)|"\"
  x = chkfname(invpath|"*.*")
  if x = 0                             'message "Valid"
    return (0)
  elseif x = -6                        'message "Bad path"
    messboxwait(invpath&"not found ",0,0,1)
    return (1)
  elseif x = -5                        'message "Bad character at"&str(ptval)
    messboxwait(invpath&"not found ",0,0,1)
    return (1)
  end if
END FUNCTION ' CheckDirectory()


function popuplist(r1,c1,br,list,msg,num,mnu)
local t hml hm cnum mscn pad padc ret
  if exact(trim(list),NULL)=FALSE
     recs = uistrcnt(list)
     if recs = 0
          return (-3)
     end if
  else
     return (-2)
  end if

redimension plist[recs,3]
smartpeek $_l1 hml

if br-r1<1
     return (-4)
elseif br+1 > scrheight
     mr=scrheight-1
     msg = ""
else
     mr=br
end if
if br >= hml
     mnu = 0
end if

screen save hml 1 hml scrwidth mscn
if recs > scrheight
     if mnu = 1
          screen clear box hml 1 hml scrwidth 0 0 no-border
          screen print hml 1 bgi bgs "Building list..."
     end if
end if
ptstr=NULL
if mnu = 1
     hm =  case num (0,"Enter = select/unselect   F10 = done   Esc = exit") \
                    (1,"Enter = select   Esc = exit      (select: 1 item)") \
                    else "Enter = select/unselect   F10 = done   Esc = exit  " & \
                         "   (select up to:" & str(num) & "items)"
else
     hm = NULL
end if
sym = spsymmap(28)
cnum=0
blen=0
l=blen
for c=1 to recs
     plist[c,2]=group(list,c)
     l=len(plist[c,2])
     plist[c,1]=0
     if l>blen
        blen=l
     end if
end for
c2=c1+blen+2
r2=r1+recs
if r2>mr
     r2=mr
end if
dc=(c2-c1)
lc=c1+1
pad = case num (1,1) else 2
sc=c1+pad-1
pl=(r2-r1)
padc = repeat(chr(32),pad)
for i = 1 to recs
     pc = 1
     plist[i,2]=padc|format(plist[i,2],"l",dc-1)
     plist[i,3] = i
     if i = pl
          pc=pc+1
     end if
end for
if recs > scrheight
    screen shortrestore mscn
end if
screen save r1 c1 r2+2 c2+pad psa
screen clear box r1 c1 r2+1 c2+pad fgp bgp
pc=1
for c=1 to pl
     screen print c+r1 lc fgp bgp plist[c,2]
  end for
  if msg > null
    screen print r2+2 c1 fgi bgi str(format(left(msg,dc+pad+1),"M"|str(dc+pad+1)))
  end if
  if mnu = 1
    screen clear box hml 1 hml scrwidth fgs bgs no-border
    screen print hml 1 fgs bgs (format(hm,"L"|str(scrwidth)))
  end if

  c=1
  rec=1
  screen print r1+c lc fgi bgi plist[rec,2]
  drows = pl

  while TRUE
    k=inchar
    screen print r1+c lc fgp bgp plist[rec,2]
    if plist[rec,1]=1
      screen print r1+c sc fgp bgp sym
    end if

    if k={Down}
      if rec=recs
        if recs<=pl
          rec=1
          c=1
        else
          beep
        end if
      else
        if c = pl
          screen scroll up r1+1 lc r2 (c2+case num (1,0) else 1) fgp bgp 1
        end if
        c= case c (pl,c) else (c+1)
        rec=rec+1
      end if
    elseif k={Up}
      if rec=1
        if recs <= pl
          rec = recs
          c = pl
               else
                    beep
               end if
          else
               if c = 1
                    screen scroll down r1+1 lc r2 (c2+case num (1,0) else 1) fgp bgp 1
               end if
               c= case c (1,c) else (c-1)
               rec=rec-1
          end if
     elseif k={Home}
          if c>1
               if rec =(rec-c)+1
                    rec = 1
               else
                    rec =(rec-c)+1
               end if
               c=1
          else
               rec=1
               c=1
          end if
     elseif k={^Home}
          if rec = c
               rec = 1
               c=1
          else
               rec = 1
               c=1
               refresh(c,r1,c1,r2,c2,pad)
          end if
     elseif k={End}
          if rec < recs and c < pl
               if drows < pl
                    rec = recs-pl+1
                    refresh(c,r1,c1,r2,c2,pad)
                    rec = recs
                    c = pl
               else
                    if rec+(pl-c) < recs
                         rec = rec+(pl-c)
                         c = pl
                    else
                         rec = recs
                         c = pl
                    end if
               end if
          end if
     elseif k={^End}
          rec = recs-pl+1
          c = 1
          refresh(c,r1,c1,r2,c2,pad)
          c = pl
          rec = recs
     elseif k={PgDn}
          if rec = recs and c = pl
               beep
          elseif c <= pl
               if rec = recs or rec+pl >= recs
                    rec = recs-pl+1
                    c = 1
                    refresh(c,r1,c1,r2,c2,pad)
                    c = pl
                    rec = recs
               else
                    rec = rec+pl
                    refresh(c,r1,c1,r2,c2,pad)
               end if
          end if
     elseif k={PgUp}
          if rec = 1 and c = 1
               beep
          else
               if recs > pl
                    if (rec-pl)-c <= 1
                         c = rec-pl
                         if c < 1
                              c = 1
                         end if
                         rec = 1
                         refresh(1,r1,c1,r2,c2,pad)
                         rec = c
                    else
                         rec=(rec-pl)
                         refresh(1,r1,c1,r2,c2,pad)
                    end if
               else
                    if rec > 1
                         rec=1
                         c=1
                    end if
               end if
          end if
     elseif k={Enter}
       screen print r1+c lc fgi bgi plist[rec,2]
          if num = 1
                    ret=trim(plist[rec,2])
                    exit while
          end if
          if plist[rec,1] = 1
               if udelstr(trim(plist[rec,2]),ret) = 0
                    ret = ptstr
               end if
               plist[rec,1] = 0
               cnum=cnum-1
          else
               if cnum = num and not(num=0)
                    beep
               else
                    ret=trim(ret&plist[rec,2])
                    plist[rec,1] = 1
                    cnum=cnum+1
               end if
          end if
          if rec < recs
            smartpoke $_key {Down}
          end if
     elseif k={Esc}
       ret=null
       exit while
     elseif k={F10}
      return (1)
    end if
    if k <> {Enter}
      screen print r1+c lc fgi bgi plist[rec,2]
    end if
    if plist[rec,1]=1
      screen print r1+c sc fgi bgi sym
    end if
  end while
  screen save r1 c1 r2+2 c2+1+pad dsa
  screen shortrestore mscn
  screen shortrestore psa
'   clear c k dc lc sc recs c2 r2 l blen pl mr pc sym pg i rec tr drows
  clear c k dc lc sc recs c2 r2 l blen pl mr pc sym pg i tr drows
  redimension  plist[1,3]
  if trim(ret) = NULL
    ptstr = NULL
    if k={F10}
      return (0)
    else
      return (-1)
    end if
  else
    ptstr = trim(ret)
    return (0)
  end if
end function  'popuplist()


function uistrcnt(sl)
local i s lo hi c
s=20
while exact(group(sl,s),NULL)=FALSE
     s=s+20
end while
hi = s
lo = 1
while lo <= hi
     i = int((lo+hi)/2)
     c = group(sl,i)
     if c = NULL
          hi = i-1
     else
          lo = i+1
     end if
end while
while (exact(group(sl,i),NULL)=TRUE and i>0)
     i=i-1
end while
return (i)
end function  'uistrcnt()


function udelstr(s,sl)
local t i n f
  f=0
  i=0
  n=NULL
  ptstr = NULL
  while TRUE
    i=i+1
    t = group(sl,i)
    if exact(t,NULL)=TRUE
      exit while
    elseif t = s
      f=1
    else
      n=n&t
    end if
  end while
  if f = 1
    ptstr = trim(n)
    return (0)
  end if
  ptstr = sl
  return (-1)
end function  'udelstr()


function refresh(z,r1,c1,r2,c2,pad)
local x t
  screen clear box r1 c1 r2+1 c2+pad fgp bgp
  drows = 0
  for x=0 to pl-1
  t = rec-z+x+1
    if t > recs
      exit for
    else
      if t > 0
        screen print x+1+r1 lc fgp bgp plist[t,2]
        drows=drows+1
        if plist[t,1]=1
          screen print x+1+r1 sc fgp bgp sym
        end if
      end if
    end if
  end for
end function  'refresh()

