'new version of SALORD03 to handle pre-entry of BACS receipts
'A)  BACS entered in the same way as CASH/CHQS/PDQ but is given a [Branch] of "B" (?)
'    and [Method] of "BACS" - NO change is made to the CUST_ORD record

'B)  when payment recvd at Bank, a list of the "unconverted" BACS is shown and one selected
'    the record in CASHRCVD is updated to show "Direct" and "H" for [Branch].
'    (This should then be picked up when the Cash Report is run at Head Office)
'	the CUST_ORD record is amended to adjust the Balance_OS.
'C)	the Branch is then sent an email confirming the receipt.


' initbalance = balance showing in CUST_ORD before any tranaction in this program
' L208 or 225 - initbalance = round([Balance_Due],2)

' #bal_os  = balance showing in CUST_ORD after a BACS due in record has been created
' balancedue = initbalance after payment (Actual NOT BACS) received
' newbalance = balance showing in CUST_ORD after a "BACS due in record" has been created

' N.B. ONLY part A above will be done in SALORD03 - B & C will require another program.
'	that program wil also need to be able to handle conversions of BACS to PDQ and
'	removal of "promised" BACS payments.

' 210114 - PDF for ALL receipts added; CASH forced to print otherwise only PDF stored - L1565


external   fentrybox() messbox() vloadif() dpath shopmask scr findpopup() $drive
external   sch scw progress() increment() ptval fgp bgp keybox() arytostr()
external   makeidx() userid cpath jobnr vatrate vunloadif() strcount() nr6
external   chkdate() navrecs() entryline() messline() $cashent $menu base
external   popuplist() remove() exception() strtoary() fge bge _GEMS_Input()
external   messboxwait() colpopup() Background() colpoplines()
external   X_path _SWIP_Crystal() Xreppath

public     invtot ptstr custcode dsa abbrv_name $newcust $place psa #amount
public     ptary[6] jobs[6] $dayftr #netinv #total_entered invnr rcptpath $pdf

global     UpdApptRecs() $newstat $saltype CheckCorrect() PrintError() $invd y4
global     rcvd m4 PaymentMethod() Place_Paid() Approve() ReturnToMenu() $key
global     y lastbal $status custaddr1 EnterCustName() y1 y2 y3 $origin $payee
global     CheckJobNr() TransactRcvd() GetAuthCode() newrec deladdr1 $authcode
global     shop locn H_tel O_tel $type custname $method x datereceipt M_tel
global     recnr tel_locn telnr fentline $ordstat $jobstr AddVarn()
global     EnterDetails() TransactUpmt() rcvdnr balancedue initbalance NewJobNr()
global     Balance() ProcessEntry() PrintReceipt() receiptnr MakeReceiptNr()
global     $mess cat #totalrecd #inv_total newbalance i $sales #vat $sundrycash
global     p1 p2 p3 p4 p5 p6 $test AddToArray() $msg fj SelectOrigin() $allreas #bal_os
global     ReplaceHardSpace() $reas5 $free $reas1 $reas2 $reas3 $reas4 $reas
global     Job_Locn() s1 s2 s3 s4 s5 s6 s7 $locn PrintInterimOrder() EnterDetails2()
global     lastjob r1 c1 r2 c2 cl1 cl2 $PDQtype PDQ_Time() pdqtime $vat CheckOtherBACS()
global     $poplist $parent custpostcode EnterPhones() $nophone $mobile $hometel $offtel
global	 EnterEmailAddress() $email $emailaddress custrecnr #actrcpt #vat_amt


MAIN
  	single-step off
  	m4 = " Correct? (y/n) "
  	$authcode = ""
  	$sundrycash = "Y00000"
  	screen clear box 1 1 sch scw 0 0 no-border
  	repaint off
  	lock module invtot
  	$reas1="Originalÿorder"
  	$reas2="Asÿperÿattachedÿorder"
'   $reas3="Labourÿ&ÿmaterialsÿsuppliedÿperÿCustomer'sÿorder"
  	$reas3="Labour/materialsÿsuppliedÿtoÿCustomer'sÿorder"
  	$reas4="Asÿperÿsupportingÿdocuments"
  	$reas5="Freeÿtext"
  	$free ="Labour œxx,xxx - Materials œxx,xxx  (exc. VAT)"
	rcptpath=$drive|"reports\receipts\"     'stores receipts

  	while true
    		x=CheckJobNr()                   ' check Job Nr exists in CUST_ORD
    		if x = 0
      		x = EnterDetails()               ' sic
      		if x = 1
        			continue while
      		elseif x = -1
        			ReturnToMenu()
      		end if
    		elseif x = -1
      		exit while
    		elseif x = 1
      		$method = "Cheque"
    		end if

    		if $cashent = "Y"
      		x=ProcessEntry()                         ' enter cash received
      		x=PrintReceipt()                         ' L1647
    		end if
    		vunloadif("cust_ord.vws")
		if $ordstat="M"
'     		return (0)
		else
	    		x=CheckCorrect()                       'check that Balance is the same
		end if
  	end while
  	vloadif(dpath|"cust_ord.vws")
  	$ordstat = [Order_Status]            		'message "$ordstat is:"&str($ordstat)
  	ReturnToMenu()
END MAIN


FUNCTION CheckOtherBACS()
local rcptdes $rcpstr
' if DIRECT receipt i.e. BACS - show previous receipts for this jobnr to avoid double counting
  	$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
    		messboxwait(" No previous BACS/direct 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],"L18")&#amount)
    		$rcpstr = $rcpstr&rcptdes          '
    		data goto record next
  	end for
  	vunloadif("os_rcpts.vw")
   	x = colpoplines(18,26,22,$rcpstr,"",1,0,10,13,14,3)  'highlight date & press {Enter} to show deliveries
  	x = colpoplines(18,26,22,$rcpstr,"",1,0,fgp,bgp,14,3)  'highlight date & press {Enter} to show deliveries
	y1 = format(" Payments ALREADY logged on ","L28")
  	screen shortrestore dsa
	screen print 18 26 fgp bgp y1
  	inchar
END FUNCTION ' CheckOtherBACS()


FUNCTION CheckJobNr()                     ' checks for JobNr - if not found
  	fj = -1
  	jobnr = ""
  	screen clear box 1 1 sch scw 0 0 no-border
  	repaint off
  	newrec = 0
  	invtot = 0
  	telnr = ""
  	deladdr1 = ""
  	fentline = " Enter Customer's Name (or 1st SEVEN letters if existing customer)"
  	while true
    		Background()
'     		x=popuplist(10,48,23,"OrderÿNr InvoiceÿNr","Enter Cash",1,0)
'     		if x = -1
'       		return (-1)
'     		end if
'     		if ptstr = "OrderÿNr"

      		while true
        			if fj = -1
          			x = fentrybox(" Enter Job Nr or {Esc} for new order ",6,shopmask,jobnr)
          			if x = -1
             				x=NewJobNr()
						if x=0
	              				return (0)
    						elseif x = -1
	              				return (-1)
    						end if
          			elseif x = 0
            				if ptstr = ""
              					continue while
            				else
              					jobnr = ptstr
              					$key  = "Job"
              					exit while
            				end if
          			end if
        			end if
        			exit while
      		end while

'     		else
'       		while true
'         			if fj = -1
'           			x = fentrybox(" Enter Invoice Nr or {Esc} to exit ",6,nr6,invnr)
'           			if x = -1
'             				return (-1)
'           			elseif x = 0
'             				if ptstr = ""
'               					continue while
'             				else
'               					invnr = ptstr
'               					$key  = "Inv"
'               					exit while
'             				end if
'           			end if
'         			end if
'         			exit while
'       		end while
'     		end if
    		progress(fgp,bgp," Checking for existing order ",0)
    		vloadif(dpath|"cust_ord.vws")
    		if $key = "Job"
      		order change key "[Job_Nr]"
      		data find "[Job_Nr]" equal jobnr options "gw"
      		if cerror                               '   if none - then return
        			messboxwait("151/ Job Nr not found ",0,0,1)
        			continue while
      		else
        			screen clear box 1 1 sch scw 0 0 no-border
        			initbalance = round([Balance_Due],2)
        			custname = [CustOrd_Name]
        			deladdr1 = [Delivery_Address_1]
				$ordstat=[Order_Status]				'message "$ordstat is:"&str($ordstat)
        			x=Balance()
        			AddToArray()
        			return (1)
      		end if
    		elseif $key = "Inv"
      		order change key "[Inv_Nr]"
      		data find "[Inv_Nr]" equal invnr options "gw"
      		if cerror                               '   if none - then return
        			messboxwait(" Invoice Nr not found ",0,0,1)
        			continue while
      		else
        			screen clear box 1 1 sch scw 0 0 no-border
        			initbalance = round([Balance_Due],2)
        			jobnr       = [Job_Nr]
        			custname    = [CustOrd_Name]
        			deladdr1    = [Delivery_Address_1]
        			x = Balance()
        			AddToArray()
        			return (1)
      		end if
		else
			continue while
    		end if
  	end while
  	AddToArray()
  	return (1)
END FUNCTION ' CheckJobNr()


FUNCTION Balance()
local y
	if $ordstat="M"
    		return (0)
	end if
  	while true
    		y=abs(initbalance)
    		if round(initbalance,2) < 0
      		messboxwait(jobnr&"- "|currency(initbalance)&"o'pd by"&custname|"ÿ",0,1,1)
      		return (0)
    		elseif round(initbalance,2) = 0
      		messboxwait(jobnr&"- no balance due from"&custname|"ÿ",0,1,1)
      		return (1)
    		else
      		messboxwait(jobnr&"- "|currency(initbalance)&"due from"&custname|"ÿ",0,1,1)
      		return (0)
    		end if
  	end while
END FUNCTION 'Balance()


FUNCTION EnterCustName()
local s1 s2
	Background()
 	while true
		s1="ÿSurnames"
		s2="ÿPostcodes"
		x = popuplist(11,45,13,s1&s2," Search ",1,0)	'message "L210 x is:"&str(x)
    		if x = -1
       		return (-1)
    		end if
    		if ptstr =s1
    			while true
      			x = fentrybox(fentline,35,"","")
      			if x = 0
        				if ptstr = ""
          				continue while
        				end if
        				exit while
      			elseif x = -1
         				continue while
      			end if
    			end while
    			custname=proper(ptstr)
    			vloadif(dpath|"custsel4.vw")
    			order change key [Abbrv_Name]
    			abbrv_name = proper(left(custname,7))
    			data find "[Abbrv_Name]" equal abbrv_name options ""
    			if cerror
      			messbox(" Name not on file, is"&chr(34)|custname|chr(34)|" a new customer? (y/n)",1,0,1)
      			if ptstr == "y"
        				$newcust = "Y"
        				custcode = jobnr
					Background()
        				return (0)
      			end if
    			end if

    		else								' if ptstr = "ÿÿÿPostcode"
  			while true
    				x = fentrybox(" Enter Postcode ",8,"AU*7{[A-Za-z1234567890\ ]U}","")	'message "x) is:"&str(x)
    				if x = 0
      				custpostcode=ptstr	'message "custpostcode) is:"&str(custpostcode)
    				elseif x=-1
      				return (-1)
    				end if
				vloadif(dpath|"custsel4.vw")
     	 		order change key "[Postcode]"
      			data find "[Postcode]" equal custpostcode options "gw"
    				exit while
  			end while
		end if

    		repaint on
    		repaint
    		ptval=0
    		y1 = format(" CUSTOMERS ALREADY HELD ON FILE ","M88")
    		y2 = format(" {A}dd"&chr(34)|custname|chr(34)|" - {S}elect highlight - {R}etry - {Esc} exits ","M88")
    		screen print 4 11 fgp bgp y1
    		screen print 28 11 fgp bgp y2
    		while true
      		ptval = navrecs()
      		if ptval = {S} or ptval = {s}
        			if (deleted)
          			messboxwait(" Deleted record - choose another ",0,0,1)
          			continue while
        			end if
        			$origin  = [Source]            ' message "$origin is:"&str($origin)
        			$newcust = "N"
        			custname = [Customer_Name]
        			abbrv_name = [Abbrv_Name]
			  	custrecnr=precord					' message "L325 custrecnr) is:"&str(custrecnr)
        			if len([Address_1]) <> 0       ' Same name
	          		$msg = custname&"of"&[Address_1]|"?" 'message "len($msg)) is:"&str(len($msg))
     	     		messbox($msg,1,1,1)
          			if ptstr == "y"
						$email=[Email_Addr]
         					deladdr1=[Address_1]
     	       			custcode  = [Customer_Code]
          	  			custaddr1 = [Address_1]
            				$hometel=[Home_Tel]
            				$offtel=[Office_Tel]
						$mobile=[Mobile/Other_Nr]
	          		else
				    		y2 = format(" {A}dd"&chr(34)|custname|chr(34)|" - {S}elect highlight - {R}etry - {Esc} exits ","M88")
          	  			screen print 21 4 fgp bgp y2
            				continue while
          			end if
	          		repaint off
					vunloadif("custsel4.vw")
     	     		return (0)
        			else                           'if [Address_1] > 0
          			while true
            				x = fentrybox(" Enter Delivery Address - Line 1 ",35,"","")
            				if ptstr = ""
	              				continue while
     	       			end if
          	  			if x = 0
              					repaint off
              					deladdr1 = proper(ptstr)
              					custcode  = [Customer_Code]
							vunloadif("custsel4.vw")
              					return (0)
	            			elseif x = -1
     	         				continue while
          				end if
          			end while
        			end if

      		elseif ptval = {R} or ptval = {r} 		' retry
				Background()
				exit while

      		elseif ptval = {A} or ptval = {a}
        			x=messbox(" Add"&chr(34)|custname|chr(34)&"to list of Customers? (y/n)",1,1,1)
        			if ptstr ! "y"
          			$newcust = "Y"
				else
					continue while
         			end if
        			repaint off
				$email=""
				$mobile=""
				$hometel=""
				$offtel=""
				vunloadif("custsel4.vw")
        			return (0)

      		elseif ptval = {Esc}
				Background()
        			exit while
      		end if
    		end while
  	end while
END FUNCTION 'EnterCustName()


FUNCTION EnterDetails()
local  response prec# y
'   x = keybox("1Normal 1CashÿSales 1Zeroÿrate","Enter type of Sale")
	Background()
  	x = keybox("1Normal 1Zeroÿrate","Enter type of Sale")
  	if x = -1
    		return (-1)
  	end if
  	$saltype = ptstr
  	r1 = 8
  	r2 = r1+6
  	c1 = 17
  	c2 = c1+48
  	cl1 = 14
  	cl2 = 3
  	$newstat = "A"
  	$method = "Cheque"
  	if $saltype == "n"
    		#vat = vatrate
    		$vat = "S"
  	elseif $saltype == "z"
    		$vat = "Z"
    		#vat = 0
  	end if

  	x = EnterCustName()
  	if x = -1
    		return (1)
  	end if
'   progress(15,10," Please wait ... checking Job Nr ",0)
  	vloadif(dpath|"cust_ord.vws")
  	order change key "[Job_Nr]"
  	data find "[Job_Nr]" equal jobnr options ""
  	if cerror                               '   if none - then return
  	else
    		messbox(" Job Nr"&jobnr&"already used, creating another ",0,1,1)
    		while true
      		lastjob=right(jobnr,5)
      		jobnr=left(jobnr,1)|right("00000"|str(value(lastjob)+1),5) 'message "jobnr is:"&str(jobnr)
      		data find "[Job_Nr]" equal jobnr options ""
      		if cerror                               '   if none - then return
        			exit while
      		else
        			continue while
      		end if
    		end while
  	end if
  	data enter lock						' create new CUST_ORD record
    		[Job_Nr]             = jobnr
    		[Branch]             = left(jobnr,1)
    		[CustOrd_Name]       = custname
    		[Delivery_Address_1] = deladdr1
    		[Abbrv_Name]         = left(custname,7)
    		[Date_Of_Order]      = today
    		[VAT]                = $vat
    		[Updated_By]         = userid
    		[Last_Update]        = today
'     [Parent]             = $parent
  	write-record
  	recnr=precord
  	EnterDetails2()

  	vloadif(dpath|"cust_ord.vws")
  	$type  = case left(jobnr,1)("C","S")("R","S")("S","S")("F","S")("P","F")("W","H")("T","H")("Y","H")
  	$sales = case left(jobnr,1)("C","X")("R","R")("S","S")("F","F")("P","P")("W","W")("T","T")("Y","Y")
  	if len(custname) = 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
  	#netinv = round(invtot*100/(100+#vat),2)

  	data goto record record-number recnr
  	lock-record
    		[SalesAnalysis]      = $sales
    		[Type_Branch]        = $type
    		[Delivery_Address_1] = deladdr1
    		[Invoice_Total]      = 0
    		[Net_Invoice]        = 0
    		[Balance_Due]        = 0
    		[Customer_Code]      = custcode
    		[Updated_By]         = userid
    		[Last_Update]        = today
    		[Order_Status]       = $newstat
    		[PDA]                = "Y"
    		[Origin]             = $origin
    		[Completed]          = "N"
  	write-record
  	recnr = precord
  	$status = "A"
  	if $menu = "boss"
    		$allreas = $reas1&$reas2&$reas3&$reas4&$reas5
  	else
    		$allreas = $reas1&$reas2&$reas3&$reas4
  	end if
  	while true
'     		x = popuplist(18,33,28,$allreas,"",1,0) ' message "x) is:"&str(x)
    		x = popuplist(15,32,28,$allreas,"",1,0) ' message "x) is:"&str(x)
    		if x = -1
      		continue while
    		elseif x = 0
      		exit while
    		end if
  	end while
  	if ptstr = $reas5
    		while true
      		x = entryline(" Var'n description - the Customer reads this ",50,"",$free,17,33,50)
      		if x = -1
        			return (-1)
      		elseif x = 0
        			if ptstr = ""
          			continue while
        			end if
        			$reas = ptstr
        			exit while
      		end if
    		end while
  	else
    		$reas = ptstr
  	end if
  	AddVarn(jobnr|"-00",invtot,$reas,"Original","Original",today)
  	Background()
  	messbox(" Print interim confirmation? (y/n) ",1,1,1)
  	if ptstr == "y"
    		PrintInterimOrder()
  	end if
  	AddToArray()
END FUNCTION 'EnterDetails()


FUNCTION EnterDetails2()
'   	vloadif(dpath|"custsel4.vw")
  	@if(len(deladdr1)=0,"",deladdr1)
  	while true
    		while true
       		x = fentrybox(" Enter Delivery Address - Line 1 ",35,"",deladdr1)
      		if ptstr = ""
        			continue while
      		end if
      		if x = 0
        			deladdr1 = proper(ptstr)
        			if $newcust = "Y"
          			SelectOrigin()
        			end if
        			exit while
      		elseif x = -1
        			continue while
      		end if
    		end while

		x=EnterPhones()

 		x=EnterEmailAddress()						' message "L540 $email) is:"&str($email)

    		while true
      		x = fentrybox(" Enter Invoice total (inc VAT) - dec. point must be entered ",8,"*8{[-1234567890.]}","")
      		if x = 0
        			if ptstr = ""
          			continue while
        			end if
        			invtot = value(ptstr)
        			if $menu <> "boss"
          			if invtot = 0
            				messbox(" Cannot enter ZERO invoices ",0,0,1)
            				continue while
          			end if
        			end if
        			exit while
      		elseif x = -1
        			continue while
      		end if
    		end while
    		initbalance = invtot
 		Background()
    		y3 = format(" Order value:"&currency(invtot)&"(inc. VAT @"&str(#vat)|"%) ","L46")
' 	   	r1 =10
	   	r1 =8
  		r2 = r1+5
	  	c1 = 32
  		c2 = c1+48
	  	cl1 = 14
  		cl2 = 3
    		screen clear box r1 c1 r2 c2 cl1 cl2
    		y1 = format(" "|jobnr&"-"&custname|" ","M46")
    		screen print r1+1 c1+2 cl1 cl2 y1
    		y2 = format(" Email:"&$email,"L46")
    		screen print r1+3 c1+2 cl1 cl2 y2
    		y4 = format(" Fit at:"&deladdr1,"L46")
    		screen print r1+2 c1+2 cl1 cl2 y4
    		screen print r1+4 c1+2 cl1 cl2 y3
    		screen clear box 20 1 21 scw 0 0 no-border
    		x = messbox(" Confirm correct and continue with Order? (y/n) ",1,1,1)
    		if ptstr == "y"
      		repaint off
      		if $newcust = "Y"
        			custcode = jobnr
        			if len(custname) = 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
		    		vloadif(dpath|"custsel4.vw")
' message "SO3 L590 $email) is:"&str($email)
        			data enter lock
          			[Branch]        =left(custcode,1)
					[Email_Addr]	 =$email
          			[Customer_Name] =custname
          			[Abbrv_Name]    =abbrv_name
          			[Customer_Code] =custcode
          			[Profile]       ="A"
          			[Credit_Status] ="C"
					[Home_Tel]=$hometel
					[Mobile/Other_Nr]=$mobile
					[Office_Tel]=$offtel
          			[Updated_By]    = userid
          			[Last_Update]   = today
          			[ChkAddr]       = "Y"
          			[Source]        = $origin
        			write-record
        			$parent="M"
      		else
		    		vloadif(dpath|"custsel4.vw")
			  	data goto record record-number custrecnr
' message "SO3 L618 $email) is:"&str($email)
        			lock-record
					[Home_Tel]=$hometel
					[Mobile/Other_Nr]=$mobile
					[Office_Tel]=$offtel
					[Email_Addr]=$email
     	   		write-record
'         			$parent="M"
      		end if
      		return (0)
    		else
      		continue while
    		end if
    		repaint off
  	end while
END FUNCTION 'EnterDetails2()


FUNCTION EnterPhones()
local $mobnr $homenr $offnr c1 c2 c3
' 	Background()
' 	$mobile=""
' 	$hometel=""
' 	$offtel=""
	$mobnr="N"
	$homenr="N"
	$offnr="N"
  	$nophone="N"
  	while true
' 		Background()
    		y1 = format(" Phone ","M10")
    		screen print 10 45 15 1 y1
 		c1="Mobile"
		c2="Home"
		c3="Office"
    		y = popuplist(11,45,18,c1&c2&c3,"",1,0) ' message "y) is:"&str(y)
    		if ptstr = c1
    			while true
      			if $mobile="N/P"
        				$mobile=""
      			end if
      			x=fentrybox(" Mobile 'phone number - {Esc} if none ",15,"\0*14{[1234567890\-]}",$mobile)
      			if x = 0
        				if ptstr = ""
          				$mobile = ""
        				else
          				$mobile = ptstr
          				$nophone = "Y"
						$mobnr="Y"
          				exit while
        				end if
      			elseif x = -1
        				$mobile = ""
        				exit while
      			end if
    			end while

    		elseif ptstr = c2
			while true
    				if $hometel = "N/P"
    					$hometel = ""
   				end if
'     				x = entryline(" Home 'phone number - {Esc} if none ",15,"\0*14{[1234567890\-]}",$hometel,21,5,70)
    				x = fentrybox(" Home 'phone number - {Esc} if none ",15,"\0*14{[1234567890\-]}",$hometel)
    				if x = 0
   					if ptstr = "0"
         					$hometel = ""
    					else
        					$hometel = ptstr
         					$nophone = "Y"
						$homenr="Y"
         					exit while
    					end if
    				elseif x = -1
    					$hometel = ""
    					exit while
    				end if
			end while

    		elseif ptstr = c3
    			while true
      			if $offtel = "N/P"
        				$offtel = ""
      			end if
      			x = fentrybox(" Office 'phone number - {Esc} if none ",15,"\0*14{[1234567890\-]}",$offtel)
      			if x = 0
        				if ptstr = "0"
          				$offtel = ""
        				else
          				$offtel = ptstr
          				$nophone = "Y"
						$offnr="Y"
          				exit while
        				end if
      			elseif x = -1
        				$offtel = "N/P"
        				exit while
      			end if
    			end while
    		end if
    		exit while
  	end while

' enter other phones Y/N
 	x = messbox(" Enter other phone numbers? (y/n) ",1,1,1)
	if ptstr=="y"
		if $mobnr="N"
			while true
   				if $mobile="N/P"
    					$mobile=""
	    			end if
'     				x=entryline(" Mobile 'phone number - {Esc} if none ",15,"\0*14{[1234567890\-]}",$mobile,21,5,70)
    				x=fentrybox(" Mobile 'phone number - {Esc} if none ",15,"\0*14{[1234567890\-]}",$mobile)
    				if x = 0
    					if ptstr = "0"
         					$mobile = ""
	    				else
     	    				$mobile = ptstr
         					$nophone = "Y"
						$mobnr="Y"
         					exit while
	    				end if
    				elseif x = -1
   					$mobile = ""
   					exit while
	    			end if
			end while
		end if
	
		if $homenr="N"
			while true
				if $hometel = "N/P"
					$hometel = "0"
				end if
				x = fentrybox(" Home 'phone number - {Esc} if none ",15,"\0*14{[1234567890\-]}",$hometel)
    				if x = 0
					if ptstr = "0"
    						$hometel = ""
					else
    						$hometel = ptstr
    						$nophone = "Y"
						$homenr="Y"
	    					exit while
    					end if
    				elseif x = -1
    					$hometel = ""
    					exit while
				end if
			end while
		end if

		if $offnr="N"
    			while true
      			if $offtel = "N/P"
        				$offtel = ""
      			end if
      			x = fentrybox(" Office 'phone number - {Esc} if none ",15,"\0*14{[1234567890\-]}",$offtel)
      			if x = 0
        				if ptstr = "0"
          				$offtel = ""
        				else
          				$offtel = ptstr
          				$nophone = "Y"
						$offnr="Y"
          				exit while
        				end if
      			elseif x = -1
        				$offtel = ""
        				exit while
      			end if
    			end while
		end if
	end if
END FUNCTION 'EnterPhones()


FUNCTION EnterEmailAddress()							' from L470
local j r i n x $mess
' message "MO L1309 $email) is:"&str($email)
	if len($email)=0
		$email=""
	end if
	while true
   		while true
    			x = fentrybox(" EMAIL address - {Esc} if none ",50,"",$email)
	    		if x = 0
 			     $email=ptstr
       			exit while
	    		else
 			     $email = ""
     	  		return (0)
    			end if
	   	end while

		messbox(" Confirm"&$email|"? (y/n) ",1,1,1)
   		if ptstr == "n"
			continue while
		else
			exit while
		end if

' temporary rem out until keyboard mapping corrected
' 		if left($email,1)="@"
' 			messboxwait(" Invalid email address - 1st char is @ ",0,0,1)
' 			continue while
' 		end if

' 		if right($email,1)="."
' 			messboxwait(" Invalid email address - last char is .  ",0,0,1)
' 			continue while
' 		end if

' 		if right($email,1)="@"
' 			messboxwait(" Invalid email address - last char is @  ",0,0,1)
' 			continue while
' 		end if

' 		for j=1 to len($email)
' 			r = mid($email,j,1)						' message "r is:"&str(r)
' 			if r=chr(64)
' 				exit while
' 			end if
' 		end for
' 		messboxwait(" Invalid email address format - no @ sign ",0,0,1)
	end while
END FUNCTION 'EnterEmailAddress()


FUNCTION ReturnToMenu()
  	lock module $newcust
  	lock module jobnr
  	screen clear box 1 1 sch scw 0 0 no-border
  	repaint off
  	file unload all                      'message "$jobstr is:"&str($jobstr)
  	fopen dpath|userid|".jnr" as 1
  	fwrite 1 from $jobstr
  	fclose 1
  	if $ordstat = "A"
    		transfer "salord02.rf3" in-memory
  	else
    		transfer cpath|"pm_menu.psl" in-memory
  	end if
END FUNCTION ' ReturnToMenu()


FUNCTION EnterCash()
  	vloadif(dpath|"cashrcvd.vws")
  	smartpoke $_ins 0                      ' switch on OVR mode
  	order change physical
	Background()
  	while true
    		if initbalance < 0
			if $ordstat="M"
	      		x = fentrybox(" Unconverted MEASURE - "|currency(abs(initbalance))|" already received. Enter further Amount or {Esc} to exit ",8,"","")
     	 		if x = -1
        				messbox(" No Cash Receipt entered - returning to Menu ",0,0,1)
        				lock module jobnr
        				file unload all
	        			transfer cpath|"pm_menu.psl" in-memory
     	 		elseif x = 0
        				rcvd = value(ptstr)
        				if $menu <> "boss"
          				if rcvd < 0
            					messboxwait(" Refunds must be entered by Head Office ",0,0,1)
            					continue while
	          			end if
     	   			end if
        				exit while
      			end if
			end if

      		x = fentrybox(" Overpaid by "|currency(abs(initbalance))|". Enter Amount Received or {Esc} to exit ",8,"","")
      		if x = -1
        			messbox(" No Cash Receipt entered - returning to Menu ",0,0,1)
        			lock module jobnr
        			file unload all
        			transfer cpath|"pm_menu.psl" in-memory
      		elseif x = 0
        			rcvd = value(ptstr)
        			if $menu <> "boss"
          			if rcvd < 0
            				messboxwait(" Refunds must be entered by Head Office ",0,0,1)
            				continue while
          			end if
        			end if
        			exit while
      		end if

    		elseif initbalance = 0
			if $ordstat="M"
	      		x = fentrybox(" Currently only a MEASURE (unconverted) - enter Amount Received or {Esc} to exit ",8,"","")
     	 		if x = -1
        				messbox(" No Cash Receipt entered - returning to Menu ",0,0,1)
        				lock module jobnr
        				file unload all
	        			transfer cpath|"pm_menu.psl" in-memory
     	 		elseif x = 0
        				rcvd = value(ptstr)
        				if $menu <> "boss"
          				if rcvd < 0
            					messboxwait(" Refunds must be entered by Head Office ",0,0,1)
            					continue while
	          			end if
     	   			end if
        				exit while
      			end if
			end if
      		x = fentrybox(" No Balance outstanding - enter Amount Received or {Esc} to exit ",8,"","")
      		if x = -1
        			messbox(" No Cash Receipt entered - returning to Menu ",0,0,1)
        			lock module jobnr
        			file unload all
        			transfer cpath|"pm_menu.psl" in-memory
      		elseif x = 0
        			rcvd = value(ptstr)
        			if $menu <> "boss"
          			if rcvd < 0
            				messboxwait(" Refunds must be entered by Head Office ",0,0,1)
            				continue while
          			end if
        			end if
        			exit while
      		end if

    		else
      		while true
        			x = fentrybox(" "|currency(initbalance)&"due from"&trim(format(left(custname,20),"L20"))|" - enter Amount - {Esc} exits ",11,"","")
        			if x = -1
          			messbox(" No Cash Receipt entered - returning to Menu ",0,0,1)
          			lock module jobnr
          			file unload all
          			transfer cpath|"pm_menu.psl" in-memory    '         ReturnToMenu()
        			elseif x = 0
          			if ptstr = ""
            				continue while
          			end if
          			rcvd = value(ptstr)
          			if $menu <> "boss"
            				if rcvd < 0
              					messboxwait(" Refunds must be entered by Head Office ",0,0,1)
              					continue while
            				end if
          			end if
          			exit while
        			end if
      		end while
      		exit while
    		end if
  	end while
END FUNCTION ' EnterCash()


FUNCTION DateRcvd()
local m1
  	while true
    		if rcvd > 0
      		m1 = " Enter Date of Receipt "
    		else
      		m1 = " ÿEnter Date Refundedÿ "
    		end if
    		x = fentrybox(m1,10,"##\/##\/####",today)
    		if x = 0
      		datereceipt = ptstr
      		if chkdate(datereceipt,1) = -1
        			messbox(" Incorrect date - re-enter ",0,0,1)
        			continue while
      		end if
      		if days(datereceipt) > days(today)
        			messbox(" Future dates not allowed ",0,0,1)
        			continue while
      		elseif days(datereceipt) < (days(today)-2)
        			messbox(" Must be within last 2 days ",0,0,1)
        			continue while
      		end if
      		exit while
    		end if
  	end while
END FUNCTION ' DateRcvd()


FUNCTION Approve()
local y  p1 p2 p3 p4 p5 y1 chkbal p6
  	screen clear box 1 1 sch scw 0 0 no-border
  	repaint off
  	while true
    		y1 = format(left(" "|jobnr&"-"&custname|" ",44),"M44")
    		if rcvd < 0
      		screen print 10 26 fge bge y1
    		else
      		screen print 10 26 fgp bgp y1
    		end if
    		if rcvd > 0								' amount
 	     	if $method="BACS"
 	      		p1="BACSÿamountÿdue:ÿÿÿ"|right("ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"|format(str(rcvd),"2R,$"),22)
 	    		else
 	      		p1="Amountÿreceived:ÿÿÿ"|right("ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"|format(str(rcvd),"2R,$"),22)
	    		end if
    		else
      		p1="Amountÿpaid:ÿÿÿÿÿÿÿ"|right("ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"|format(str(rcvd),"2R,$"),22)
    		end if

    		if rcvd > 0								' Date recvd/processed
	     	if $method="BACS"
	      		p2 = "BACSÿenteredÿon:ÿÿ"|right("ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"|date2(datereceipt),22)
	    		else
	       		p2 = "Dateÿreceived:ÿÿÿÿ"|right("ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"|date2(datereceipt),22)
	    		end if
    		else
      		p2 = "Dateÿpaid:ÿÿÿÿÿÿÿÿ"|right("ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"|date2(datereceipt),22)
    		end if

    		p3 = "Paidÿby:ÿÿÿÿÿÿÿÿÿÿ"|right("ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"|$method,22)

    		$authcode=ReplaceHardSpace(str($authcode))
    		p6 = "Authority/comment:"|right("ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"|$authcode,22)

    		if rcvd > 0
	     	if $method="BACS"
	      		p4 = "BACSÿenteredÿat:ÿÿ"|right("ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"|$place,22)
	    		else
	      		p4 = "Moneyÿreceivedÿat:"|right("ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"|$place,22)
	    		end if
    		else
      		p4 = "Refundÿpaidÿfrom:ÿ"|right("ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"|$place,22)
    		end if

     	if $method="BACS"
' #bal_os  = balance showing in CUST_ORD after a BACS due in record has been created
    			chkbal = initbalance						'message "chkbal is:"&currency(chkbal)
'     		y1 = format(left(" "|jobnr&"-"&custname|" ",44),"M44")
    			p5 = "ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿCORRECT!ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"
 		else
    			chkbal = initbalance-rcvd          ' message "chkbal is:"&currency(chkbal)
			if $ordstat="M"				' DO NOT minus balances for deposits on Measures
	    			p5 = "ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿCORRECT!ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"
			else
    				p5 = "ÿCORRECT!ÿ(balanceÿWILLÿbeÿ"|currency(chkbal)|")ÿ"
	 		end if
 		end if
    		if rcvd < 0
      		x = colpopup(11,26,22,p1&p2&p3&p6&p4&p5,chr(24)&chr(25)&"and {Enter} to amend/accept",1,0,15,12,0,7)
    		else
      		x = colpopup(11,26,22,p1&p2&p3&p6&p4&p5,chr(24)&chr(25)&"and {Enter} to amend/accept",1,0,15,1,0,7)
    		end if
    		if x = -1
      		messbox(" Abandon this Cash Received entry? (y/n) ",1,0,1)
      		if ptstr == "y"
        			lock module jobnr
        			Background()
        			file unload all
        			transfer cpath|"pm_menu.psl" in-memory
      		end if
    		end if
    		if ptstr ! "Amount"
      		screen shortrestore dsa
      		if $saltype = "c"
        			rcvd = invtot
      		else
        			EnterCash()						'L859
      		end if
    		elseif ptstr ! date2(datereceipt)
      		screen shortrestore dsa
      		datereceipt = today
    		elseif ptstr ! $method
      		screen shortrestore dsa
      		PaymentMethod()						'L1091
    		elseif ptstr ! $place
      		screen shortrestore dsa
     		if $method="BACS"
 	     		locn="U"
 			else
	      		Place_Paid()
 			end if
    		elseif ptstr == p5
      		screen clear box 1 1 sch scw 0 0 no-border
      		repaint off
      		exit while
    		end if
  	end while
END FUNCTION ' Approve()


FUNCTION ReplaceHardSpace(str1)
local j r m bw 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
  return (m)
END FUNCTION ' ReplaceHardSpace()


FUNCTION TransactUpmt()
  vloadif(dpath|"cust_ord.vws")
  lastbal = round([Balance_Due],2)
  balancedue = lastbal - balancedue
  lock-record
    [Balance_Due] = balancedue
  write-record
END FUNCTION ' TransactUpmt()


FUNCTION MakeReceiptNr(receiptnr)
  increment(dpath|"receipts.dat",1)
  receiptnr = right("00000"|str(ptval),5)
  return (receiptnr)
END FUNCTION


FUNCTION PaymentMethod()
  	while true
    		screen shortrestore dsa
' message "base) is:"&str(base)
' if $ordstat="M"
		if base="O"
    			$poplist = "Cheque Cash PDQ Direct BACS"
		else
    			$poplist = "Cheque Cash PDQ BACS"
		end if
    		x=findpopup(11,12,19,$poplist,$method,"Payment",1,0)
    		$method = ptstr
    		if ptstr == "PDQ"
      		GetAuthCode()
      		PDQ_Time()
    		elseif ptstr == "BACS"
          	$authcode="Not yet received"
    		elseif ptstr == "Direct"
			CheckOtherBACS()
    		else
      		if jobnr = $sundrycash
        			while true
          			x = fentrybox(" Enter Payer's name & reference ",20,"",$authcode)
          			if ptstr = ""
            				continue while
          			end if
          			if x = 0
            				exit while
          			end if
        			end while
        			$authcode = ptstr
      		else
        			$authcode = "None"
      		end if
    		end if
    		exit while
  	end while
END FUNCTION  'PaymentMethod()


FUNCTION PDQ_Time()
  while true
    x = fentrybox(" Enter time of PDQ transaction ",5,"##\:##","")
    if ptstr = ""
      continue while
    end if
    pdqtime=ptstr
    if x = 0
      exit while
    end if
  end while
END FUNCTION  'PDQ_Time()


FUNCTION  GetAuthCode()
' local $poplist
'   	$poplist = "VISA Mastercard VISAÿDebit SwitchÿOther"			'   x = popuplist(8,53,13,"2/3days 7ÿdays 7/10ÿdays 14ÿdays Other","",1,0)
'  	$poplist = "Creditrcard VISAÿDebit SwitchÿOther"			'   x = popuplist(8,53,13,"2/3days 7ÿdays 7/10ÿdays 14ÿdays Other","",1,0)
   	$poplist = "Credit Debit Other"			'   x = popuplist(8,53,13,"2/3days 7ÿdays 7/10ÿdays 14ÿdays Other","",1,0)
  	x = popuplist(11,8,19,$poplist,"Card type",1,0)
'   	$PDQtype = case ptstr ("VISA","VISA")("Mastercard","MCRD")("VISAÿDebit","VISD")("Switch","SWTC")("Other","OTHR")
  	$PDQtype = case ptstr ("Credit","CRDT")("Debit","DEBT")("Other","OTHR")
  	if rcvd > 100
    		while true
      		x=fentrybox(" Enter Authorisation Code ",6,"*6{#}","")
      		if ptstr = ""
        			continue while
      		end if
      		if x = 0
        			exit while
      		end if
    		end while
    		$authcode = value(ptstr)
  	end if
END FUNCTION  ' GetAuthCode()


FUNCTION Place_Paid()
local s1 s2 s3 s4 s5 s6 s7 $locn
  	if $method = "Direct"
    		$place = "HeadÿOffice"
    		locn = left($place,1)
    		return (0)
  	end if
  	$locn = case left(jobnr,1) ("R","Raynes")("P","Putney")("S","Sheen")("T","Fulham")("F","Fulham") else "HeadÿOffice"
  	s1 = "Fulham"
  	s2 = "HeadÿOffice"
  	s3 = "Raynes"
  	s4 = "Sheen"
  	s7 = "Putney"
  	while true
    		x = findpopup(11,83,18,s1&s2&s3&s7&s4,$locn,"Place",1,0)
    		$place = ptstr
    		locn = left($place,1)
    		exit while
  	end while
END FUNCTION 'Place_Paid()


FUNCTION ProcessEntry()
  	while true
    		if $saltype = "c"
      		rcvd = invtot
      		datereceipt = today
    		else
      		EnterCash()							'L859
      		datereceipt = today
'       DateRcvd()
    		end if

    		PaymentMethod()
    		if $method="BACS"
     		locn="U"
		else
      		Place_Paid()
		end if

' 	     Place_Paid()

    		Approve()

' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' ³ Generate Receipt Nr & create new record                            ³
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
	     receiptnr = MakeReceiptNr(receiptnr)
    		vloadif(dpath|"new_cash.vw")
	     balancedue=initbalance-rcvd
		if $ordstat="M"
    			exit while
    		end if

    		if balancedue<0
      		y = messbox(" Job Nr"&jobnr&"overpaid by "|currency(abs(balancedue))|" - confirm (y/n) or {Esc} to abandon ",1,0,0)
      		if y = -1
        			messbox(" No Cash Receipt or Job entered - returning to Menu ",0,0,1)
        			lock module jobnr
        			file unload all
        			transfer cpath|"pm_menu.psl" in-memory
      		else
        			screen clear box 1 1 sch scw 0 0 no-border
        			if ptstr == "N"
          			continue while
        			end if
        			exit while
      		end if
		 else
      		if balancedue < 1
        			if balancedue = 0
          			exit while
        			end if
        			messbox(" Underpaid by"&str(abs(balancedue*100))|"p - entering as Underpayment",0,0,1)
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' ³  Create "cashrcvd" record for underpayment                         ³
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
        			$sales = case left(jobnr,1)("C","X")("R","R")("S","S")("F","F")("P","P")("W","W")("T","T")("Y","Y")
        			vloadif(dpath|"new_cash.vw")
        			data enter lock
          			[Date_Of_Receipt]   = datereceipt
          			[SalAnal]           = $sales
          			[Job_Nr]            = jobnr
          			[Method_Of_Payment] = "UNDPMT"
          			[Abbrv_M]           = "O"
          			[Receipt_Nr]        = receiptnr
          			[Amount_Received]   = balancedue
          			[Time]              = now
          			[Branch]            = locn
          			[Entered_By]        = userid
          			[Authorisation]     = ""
          			[PDQtype]           = $PDQtype
          			[Invoiced]          = "Y"
          			[PDQ_Time]          = pdqtime
        			write-record
        			TransactUpmt()
      		end if
      		exit while
    		end if
  	end while

  	progress(15,10," Please wait ... entering details ",0)
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' ³  Create new "cashrcvd" record                                      ³
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
  	$sales = case left(jobnr,1)("C","X")("R","R")("S","S")("F","F")("P","P")("W","W")("T","T")("Y","Y")
  	vloadif(dpath|"cust_ord.vws")
  	$invd = filelookup([Job_Nr],[Inv_Nr],jobnr)
  	if len($invd) = 0
    		$invd = "N"
  	else
    		$invd = "Y"
  	end if
  	vloadif(dpath|"new_cash.vw")
     if $method="BACS"
 	     locn="U"
 		newbalance=initbalance    ' lastbal        'message "L1240 BACS initbalance) is:"&str(initbalance)
' message "BACS newbalance is:"&str(newbalance)
 	else
' message "Non BACS initbalance) is:"&str(initbalance)
'  		lastbal=value([Balance_Due])     '' message "lastbal is:"&str(lastbal)
    		newbalance=initbalance-rcvd        '
' message "Non BACS newbalance is:"&str(newbalance)' message "Non-BACS newbalance is:"&str(newbalance)
 	end if
' message "BACS or non-BACS rcvd) is:"&str(rcvd)
' message "SO3 L1255 lastbal is:"&str(lastbal)
' message "initbalance) is:"&str(initbalance)
' message "SO3 L1269 newbalance is:"&str(newbalance)
' message "$method) is:"&str($method)
' message "locn) is:"&str(locn)
' message "$authcode) is:"&str($authcode)
while true
  	data enter lock
    		[Date_Of_Receipt]   = datereceipt
    		[SalAnal]           = $sales
    		[Job_Nr]            = jobnr
    		[Method_Of_Payment] = $method
    		[Abbrv_M]           = left($method,1)
    		[Receipt_Nr]        = receiptnr
    		[Amount_Received]   = rcvd
    		[Branch]            = locn
    		[Time]              = now
    		[Authorisation]     = $authcode
    		[PDQtype]           = $PDQtype
    		[Entered_By]        = userid
'  		lastbal             = value([Balance_Due])     'message "lastbal is:"&str(lastbal)
'     		newbalance          = lastbal - rcvd        'message "newbalance is:"&str(newbalance)
    		[Balance_Due]       = newbalance
    		[Invoiced]          = $invd
    		[PDQ_Time]          = pdqtime
  	write-record
  	rcvdnr = precord
  	x=TransactRcvd()
	if x=1				' do NOT enter any more potential BACS or receipt was Cash/Chq/Direct
		exit while
	elseif x=0
' enter add'n BACS for balance due
		continue while
	end if
end while
END FUNCTION ' ProcessEntry()


FUNCTION TransactRcvd()
    	if $method="BACS"
' calc balance still remaining after prev BACS has been received
' message "initbalance is:"&str(initbalance)
' message "rcvd is the previous receipt:"&str(rcvd)
'     		newbalance=initbalance-rcvd        '
' message "SO3 L1294 Non BACS newbalance is:"&str(newbalance)' message "Non-BACS newbalance is:"&str(newbalance)
' 		if newbalance>0
' 		  	messbox(" Enter the remaining"&currency(newbalance)&"as a future BACS receipt? (y/n) ",1,0,1)
'   			if ptstr == "n"

		return (1)
	else
		if $ordstat="M"
			return (1)
  		end if
	  	messbox(" Balance shown as remaining is"&currency([Balance_Due])&"- correct? (y/n) ",1,0,1)
  		if ptstr == "n"
    			screen clear box 1 1 sch scw 0 0 no-border
	    		repaint off
    			progress(15,10," Re-calculating balance ",0)
    			vloadif(dpath|"cust_ord.vws")
	    		#inv_total = [Invoice_Total]       'message "#inv_total is:"&str(#inv_total)
    			vloadif(dpath|"cash_bal.vw")
    			order change key "[Job_Nr]"
	    		data query execute "cash_bal.dfq" index "cash_bal.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' ³ QUERY is:  [Job_Nr] = jobnr                                        ³
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
    			if cerror
      			#totalrecd = 0                          ' message "#totalrecd is:"&str(#totalrecd)
	    		else
     	 		#totalrecd = filesum([Amount_Received]) ' message "#totalrecd is:"&str(#totalrecd)
    			end if                                    ' message "#inv_total is:"&str(#inv_total)
	    		newbalance = #inv_total - #totalrecd      ' message "newbalance is:"&str(newbalance)
    			screen clear box 1 1 sch scw 0 0 no-border
    			repaint off
	    		messbox(" Balance held in database is confirmed as"&currency(newbalance)&"- correct? (y/n) ",1,0,1)
    			if ptstr == "n"
      			screen clear box 1 1 sch scw 0 0 no-border
      			messbox(" Report details to Head Office ",0,1,1)
	      		$mess = jobnr&"- incorrect balance"&currency(newbalance)&"shown in CUST_ORD file"
     	 		cat="SUNDRY"
      			x=exception(userid,today,time24,cat,$mess)
      			vunloadif(dpath|"unread1.vw")
	      		vloadif(dpath|"cust_ord.vws")
    			end if
			return (1)
 		else									' YES balance is correct
			return (1)
  		end if
  	end if
END FUNCTION ' TransactcRcvd()


FUNCTION AddToArray()
local $new $newcust $hold h
  y = strtoary(custname)
  $newcust = ""
  for i = 1 to ptval
    if i = 1
      $newcust = ptary[i]                ' NB - space is Alt-255
    else
      $newcust = $newcust|"ÿ"|ptary[i]    ' NB - space is Alt-255
    end if
  end for
  $new = jobnr|"ÿ"|$newcust            ' HARD space
  for i = 1 to 6
    if left(jobs[i],6) = jobnr         ' jobnr already held
      $hold = jobs[i]
      for h = i-1 to 1 step -1
        if len(jobs[h]) = 0
          jobs[h+1] = ""
        else
          jobs[h+1] = jobs[h]
        end if
      end for
      jobs[1] = $hold
      return (0)
    end if
  end for
  for i = 5 to 1 step -1
    if len(jobs[i]) = 0
      jobs[i+1] = ""
    else
      jobs[i+1] = jobs[i]
    end if
  end for
  redimension ptary[6]
  jobs[1] = $new
  for i = 1 to 6
    ptary[i] = jobs[i]
  end for
END FUNCTION ' AddToArray()


FUNCTION UpdApptRecs()
local #apptnr
  repaint off
  vloadif(dpath|"bookappt.vw")
  order change key "[Job_Nr]"
  data query execute "job_reqn.dfq" index "job_reqn.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' ³ QUERY is:  [Job_Nr] = jobnr                                        ³
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
  if cerror                            ' if none - then return
    return (0)                         ' no appts made yet
  end if
  for i = 1 to records
    $dayftr = left([DFA],11)
    #apptnr = [Appointment_Order]
    lock-record
      [Entered_By] = userid
      [Date_Altered] = today
      [Time] = now
      [Status] = $newstat
    write-record

    repaint off
    vloadif(dpath|"apptdate.vws")         ' message "jobnr is:"&str(jobnr)
    order change key "[DayFitter]"
    data find "[DayFitter]" equal $dayftr options ""
    if cerror
      return (0)
    end if
    lock-record
      dbput("[B"|str(#apptnr)|"]",$newstat)
    write-record
    vloadif(dpath|"bookappt.vw")
    data goto record next
  end for
END FUNCTION 'UpdApptRecs()


FUNCTION CheckCorrect()
  	vloadif(dpath|"cust_ord.vws")
  	order change key "[Job_Nr]"
  	data find "[Job_Nr]" equal jobnr options ""
  	if cerror                               '   if none - then return
    		x = messboxwait(" Record "|jobnr|" not written to file - inform Head Office ",1,0,0)
    		return (1)
  	end if
  	#total_entered = [Invoice_Total]
  	messbox(" Confirm Sales value for"&jobnr&"should be"&currency(#total_entered)|"? (y/n) ",1,0,1)
  	if ptstr == "y"
    		return (0)
  	else
    		PrintError()
    		return (1)
  	end if
END FUNCTION 'CheckCorrect()


FUNCTION PrintError()
  	while true
    		x = fentrybox(" What should the Invoice total (inc VAT) have been? ",8,"*8{[-1234567890.]}","")
    		if x = 0
      		if ptstr = ""
        			continue while
      		end if
      		invtot = value(ptstr)
      		if $menu <> "boss"
        			if invtot = 0
          			messboxwait(" Cannot enter ZERO invoices ",0,0,1)
          			continue while
        			end if
      		end if
      		exit while
    		elseif x = -1
      		continue while
    		end if
  	end while
 	messboxwait(" Error in Invoice Value - contact Head Office ",0,0,1)
   	return (0)
END FUNCTION 'PrintError()


FUNCTION AddVarn(varnr,#gross,$reas,$ref,$notif,$varndate)
local lastbal newtotal oldtotal newnet oldnet #prec x
'   	vloadif(dpath|"addvarn3.vw")
  	vloadif(dpath|"addvarn4.vw")
  	data enter lock
    		[Var_Nr]        = varnr
    		[VarnJobNr]     = left(varnr,6)
    		[Amount_Gross]  = #gross
    		[Reason]        = $reas
    		[Customers_Ref] = $ref
    		[Notif_Method]  = $notif
    		[Date]          = $varndate
    		[Entered_By]    = userid
		[VarNr]    =varnr
		[Time_Entd]=now
		[Entd_By]  =userid
		[Date_Entd]=today				
  	write-record
  	lastbal=round([Balance_Due],2)
  	balancedue=lastbal + #gross
  	oldtotal =round([Invoice_Total],2)
  	newtotal =oldtotal + #gross
  	oldnet   =round([Net_Invoice],2)
  	newnet   =oldnet + round(#gross*100/(100+#vat),2)
	#vat_amt =newtotal-newnet
  	lock-record
    		[Balance_Due]   = balancedue
    		[Invoice_Total] = newtotal
    		[Net_Invoice]   = newnet
		[Inv_Total]=newtotal
		[Inv_Net]  =newnet
		[varngros] =#gross
		[VAT_amt]  =#vat_amt
  	write-record
END FUNCTION 'AddVarn()


FUNCTION SelectOrigin()
  	while true
    		x = popuplist(9,85,22,"ÿÿÿÿÿÿÿÿ Recommendation Notÿknown Other Advertisement Passing Exhibition","Source",1,0)
    		$origin = case ptstr ("Recommendation","R")("Notÿknown","N")("Other","O")("Advertisement","A")("Passing","P")("Exhibition","X")("TradeÿContact","T")("ÿÿÿÿÿÿÿÿ","$")
    		if $origin = "$"    ' HARD spaces
      		continue while
    		else
      		exit while
    		end if
  	end while
END FUNCTION 'SelectOrigin()


FUNCTION NewJobNr()
local leftjob currec
' message "L1547 base) is:"&str(base)
	while true
  		s1 = "Warehouse"
  		s2 = "Trade"
  		s3 = "Fulham"
  		s4 = "Raynes"
  		s5 = "Sheen"
  		s7 = "Putney"
  		if base="O"                         ' choice of Warehouse etc
    			leftjob=Job_Locn()
    			if leftjob=-1
	      		return (-1)
      		end if
	
	  	elseif base="F"
    			while true
      			x = popuplist(11,42,15,s3&S7&s2,"Order",1,0)
      			if x = -1
		      		return (-1)
	      		end if
     	 		$place = ptstr						'       messbox(" Confirm"&upper($place)&"job? (y/n) ",1,1,1)'       if ptstr == "y"
      			leftjob=left($place,1)
      			exit while
	    		end while

	  	elseif base="P"
    			while true
      			x = popuplist(11,42,15,s3&S7&s2,"Order",1,0)
      			if x = -1
		      		return (-1)
	      		end if
     	 		$place = ptstr						'       messbox(" Confirm"&upper($place)&"job? (y/n) ",1,1,1)'       if ptstr == "y"
      			leftjob=left($place,1)
      			exit while
	    		end while

	  	elseif base="S"
    			while true
      			x = popuplist(11,42,15,s5&s4,"Order",1,0)
      			if x = -1
		      		return (-1)
	      		end if
     	 		$place = ptstr
      			messbox(" Confirm"&upper($place)&"job? (y/n) ",1,1,1)
      			if ptstr == "y"
	        			leftjob=left($place,1)
     	   			exit while
      			else
        				continue while
	      		end if
    			end while

	  	elseif base="R"
    			while true
      			x = popuplist(11,42,15,s5&s4,"Order",1,0)
      			if x = -1
		      		return (-1)
	      		end if
     	 		$place = ptstr
      			messbox(" Confirm"&upper($place)&"job? (y/n) ",1,1,1)
      			if ptstr == "y"
	        			leftjob=left($place,1)
     	   			exit while
      			else
        				continue while
	      		end if
    			end while

	  	else
    			leftjob=Job_Locn()
    			if leftjob=-1
	      		return (-1)
      		end if
	  	end if
  		vloadif(dpath|"cust_ord.vws")
	  	data goto record last
  		while true
	    		if left([Job_Nr],1)=leftjob
      			lastjob=right([Job_Nr],5)
      			jobnr=leftjob|right("00000"|str(value(lastjob)+1),5)
     	 		currec=precord
	      		data find "[Job_Nr]" equal jobnr options "g"
      			if cerror                               '   if none - then return
        				exit while
     	 		else
	        			data goto record record-number currec
        				data goto record previous
      			end if
    			else
      			data goto record previous
    			end if
  		end while
		messbox(" This will create a new order"&jobnr&"- continue? (y/n) ",1,1,1)
		if ptstr == "y"
     		return (0)
	     else
     		continue while
	     end if
 	end while
END FUNCTION 'NewJobNr()


FUNCTION Job_Locn()
  	s1 = "Warehouse"
  	s2 = "Trade"
  	s3 = "Fulham"
  	s4 = "Raynes"
  	s5 = "Sheen"
  	s7 = "Putney"
   	while true
	  	x = popuplist(10,49,19,s3&s7&s4&s5&s2&s1,"Order",1,0)
   		if x = -1
			Background()
       		return (-1)
    		end if
    		$place = ptstr
	     return (left($place,1))
   	end while
END FUNCTION 'Job_Locn()


FUNCTION PrintReceipt()								'from L85
'print receipt - if Cash YES; Cheque YES; PDQ ask;BACS NO; Direct NO
  	vloadif(dpath|"cshrcvd1.vw")
  	order change physical
  	x=remove("cashrcpt.idx")							'message "x) is:"&str(x)
  	x=makeidx("cashrcvd","cashrcpt.idx",rcvdnr,5)		'message "x) is:"&str(x)
  	order change index "cashrcpt.idx"
  	screen clear box 1 1 sch scw 0 0 no-border			'message "L1655 $method is:"&str($method)

' 			exit while
' 	elseif $method="Cheque"
' 		elseif $method="PDQ"
' 		elseif $method="Direct"
' no receipt but Email	
' 		end if
' if method = cash force printing otherwise store PDF for ALL
' 		messbox(" Print Receipt? (y/n) ",1,1,1)
'   		if ptstr == "n"
' 			exit while
' 		end if

	if $method<>"BACS"
		Background()
	    	while true
		    	$pdf=rcptpath|receiptnr|".pdf"        'message "$pdf is:"&str($pdf)
			vunloadif("Xaddvarn.vws")
  			x=remove(X_path|"Xaddvarn.*")			'message "x) is:"&str(x)
  			data query execute "not_del.dfq" Smart4 X_path|"Xaddvarn" fields "[Customer_Code|Br_Fax]"
			_SWIP_Crystal(Xreppath|"cshrcpt2","S",0,1,"")
	      	_SWIP_Crystal(Xreppath|"cshrcpt2","EP",0,1,$pdf)
			vloadif(dpath|"cshrcvd1.vw")
			if $method="Cash"
	      		messbox(" Has Cash Receipt printed correctly? (y/n) ",1,1,1)
     	 		if ptstr == "y"                      '  store file & exit
        				return (0)
	     		else
     				messbox(" Abandon? (y/n) ",1,1,1)
	        			if ptstr == "y"                      '  store file & exit
     	     			return (0)
        				else
		     			continue while
	     			end if
     			end if
			else
    				return (0)
    			end if
    		end while
	end if
END FUNCTION ' PrintReceipt()


FUNCTION PrintInterimOrder()
local $index $file scrn
	scrn=apinfo(ap_filex)         'message "Screen is:"&str(x)
  	Background()
  	vloadif(dpath|"intorder.vw")
  	data goto record record-number recnr
  	$index = "onlyone.idx"
  	$file = "cust_ord"
  	remove($index)
  	x = makeidx($file,$index,str(precord),3)    '   message "x is:"&str(x)
  	order change index $index
  	vunloadif("X_intord.vws")
  	remove(X_path|"X_intord.*")
  	data query execute "not_del.dfq" Smart4 X_path|"X_intord" fields\
	"[Job_Nr;Customer_Name;Date_Of_Order;Customer_Name;Br_Addr1;Br_City;Br_Code;Br_Phone;Br_Fax;Delivery_Address_1;Invoice_Total]"
	_SWIP_Crystal(Xreppath|"X_intord","S",0,1,"")
  	vloadif(dpath|scrn)
END FUNCTION ' PrintInterimOrder()


' FUNCTION ProcessBACS()
'   	while true
'       	x = fentrybox(" Enter Amount received at NatWest ",8,"*8{[-1234567890.]}","")
'     		#actrcpt = value(ptstr)						' message "#actrcpt) is:"&str(#actrcpt)
' ' message "#expctrcpt) is:"&str(#expctrcpt)
' 	    	messbox(" Confirm Amount ACTUALLY received -"&str(#actrcpt)|"? (y/n) ",1,1,1)
'     		if ptstr == "N"
' 		     continue while
' 		end if
' 	  	while true
'      	 	x = fentrybox(" Name of Person sending BACS ",12,"","")
'     			$payee=upper(ptstr)
'  			if len($payee)=0
'  				$payee="Not known"
' 	 		    	messbox(" Confirm name of person sending BACS not known? (y/n) ",1,1,1)
'      			if ptstr == "N"
' 	 		     	continue while
' 				else
' 		       		exit while
'  				end if
' 			else
' 	       		exit while
' 			end if
' 		end while
'
' 		DateRcvd()
'
' message "SO8 L1135 datereceipt is:"&str(datereceipt)
' message "L1748 $payee is:"&str($payee)
'   		#initbal=value([Balance_Due])     'message "L99 initbal is:"&str(#initbal)
' message "#actrcpt) is:"&str(#actrcpt)
'     		newbalance=#initbal-#actrcpt        '
' message "newbalance is:"&str(newbalance)

' change [Method_Of_Payment] from BACS to Direct
' 		$author="From"&left($payee,15)
' ' message "L124 $author) is:"&str($author)
' 		lock-record
' 			[Date_Of_Receipt]=datereceipt
' 			[Method_Of_Payment]="Direct"
' 			[Amount_Received]=#actrcpt
' 			[Authorisation]=$author
' 			[Branch]="H"
' 			[Abbrv_M]="D"
' 			[Balance_Due]=newbalance
' 			[Entered_By]=userid
' 		write-record
' 		exit while
'   	end while
' 'send email
' 	custname=[CustOrd_Name]					'message "L136 custname) is:"&str(custname)
' 	deladdr1=[Delivery_Address_1]				'message "deladdr1) is:"&str(deladdr1)
' 	messboxwait(" Receipt Nr for Bank Statement is:"&str($receiptnr),0,0,1)
' 	vloadif(dpath|"branches.vws")			'
'  	$ownemail=filelookup([Br_Init],[Bremail],left(jobnr,1))
' 	vunloadif("branches.vws")			'message "$emailaddr) is:"&str($emailaddr)
' 	vloadif("oldpurch.vws")			'
'  	$emailaddr=filelookup([author],[OwnEmail],$originator)
' ' $userid)
' 	vunloadif("oldpurch.vws")			'  message "$ownemail) is:"&str($ownemail)
' 	x=Emails()
' END FUNCTION '	ProcessBACS()


' function Emails()
' 	#rcptdiff=#actrcpt-#expctrcpt
'   	if abs(#rcptdiff)<#allowdiff
' 	 	$emailtxt=jobnr&"-"&custname|","&deladdr1&"- BACS rcvd for GBP"&str(#actrcpt)&"- from"&$payee
' 	else
' $emailtxt=jobnr&"-"&custname|","&deladdr1&"- BACS rcvd was GBP"&str(#actrcpt)&"from"&$payee&"but"&str(#expctrcpt)&"was expected"
' 	end if
'  	_GEMS_Email($emailaddr,$ownemail,"BACS receipt",$emailtxt,"")
' end function   'Emails()

'
' FUNCTION DateRcvd()
' local m1
'   	while true
'     		m1 = " Enter Date Received at NatWest "
'     		x = fentrybox(m1,10,"##\/##\/####",today)
'     		if x = 0
'       		datereceipt = ptstr
'       		if chkdate(datereceipt,1) = -1
'         			messbox(" Incorrect date - re-enter ",0,0,1)
'         			continue while
'       		end if
'       		if days(datereceipt) > days(today)
'         			messbox(" Future dates not allowed ",0,0,1)
'         			continue while
' 		     end if
'       		exit while
'     		end if
'   	end while
' END FUNCTION ' DateRcvd()

