'DESPAT_3 - (was $inv1.PF3) lists all uninvoiced orders which have
'           [Completed]="Y" status; pick from list to prepare invoice.

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
external  _SWIP_Crystal() scbtm()

public    ptval ptstr dsa jobnr invdate psa $nextinvnr #vat #net #gross
public    #receipts #due custdet[1,1] ftrarray[1] $dateftr $ftrcode

global    x $index $file InvDetails() EnterOrder() 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
'  Distribution()
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    PrintSchedules() 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 PrintCustCopy()
global    SetupDetails2() str1 p5
global    ReplaceSoftSpace() ClearHardSpaces() $pdf


MAIN
single-step off					'message "Using SW2K_NEW"
  Background()
  file unload all
  bot = 7
  clb = 13
  clf = 10
  p5  = 1
  redimension custdet[11,2]

  while true
    Background()
    x = popuplist(9,30,13,"ListedÿInvoices InvoiceÿbyÿJobÿNr Schedules","",1,0)
    if x = -1
      exit while
    end if

    if ptstr = "Schedules"
      x = SelectDate()                     ' message "invdate is:"&date3(invdate)
      if x = -1
        exit while
      end if
      PrintSchedules()
      continue while

    elseif ptstr = "ListedÿInvoices"
      while true
        x = SelectDate()                     ' message "invdate is:"&date3(invdate)
        if x = -1
          exit while
        end if
        x = ChooseOrder()
        if x = -1
          exit while
        end if
      end while

    else
      x = SelectDate()                     ' message "invdate is:"&date3(invdate)
      if x = -1
        exit while
      end if
      x = EnterOrder()
    end if
  end while
  ReturnToMenu()
END MAIN


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)
    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
      $line = 2
      custdet[2,1] = Update(custdet[2,1],custdet[2,2])

    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
      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 UpdateCustomer()
  #invrecnr = precord
  vloadif(dpath|"inv_1.vw")
  order change physical
  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)
  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 Titles()
  y2 = format(" Order Name & Delivery Address                  Ftg Date    Inv Val    Bal o/s","L78")
  y3 = format(" {P}rint invoice - {O}rder status - {Esc} to exit ","M78")
  screen print 2 2 fgp bgp y2
  screen print 21 2 fgp bgp y3
  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 ProcessInvoice(n)
local currjobnr
  repaint off
  #uninv = record                      'message "#uninv) is:"&str(#uninv)
  fopen dpath|"inv_nrs.dat" as 1       ' get next inv nr
  fread 1 into ptval
  fclose 1
  $nextinvnr = right("000000"|str(ptval),6)
  clear ptval                          '

  x=UpdateCustomer()
  if x = -1
    return (1)
  end if

  UpdateVariations()

  vloadif(dpath|"inv_1.vw")
  x = PrintInvoice()
  if x = 1
    return (1)
  end if
' message "jobnr is:"&str(jobnr)
  Background()
  messbox(" Has invoice nr"&$nextinvnr&"printed correctly? (y/n) ",1,1,1)
  if ptstr == "y"                      '  store file & exit
    currjobnr = [Job_Nr]
' message "currjobnr is:"&str(currjobnr)
    if currjobnr<>jobnr
      messboxwait(" Invoice Nr entered against WRONG job!! ",0,0,1)
      return (1)
    end if
    increment(dpath|"inv_nrs.dat",1)   ' increase counter
    lock-record                        ' update record with inv nr & date
      [Inv_Nr] = $nextinvnr
      [Invoice_Date] = invdate
      [DateTB_Inv] = invdate
    write-record
    if n = 1
      return (1)
    end if
    vloadif(dpath|"despat_3.vw")
    order change physical
    x = delidxrec("2invoice.idx",#uninv,2)   ' remove from index
    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
  else                                 ' did not print properly
    return (1)
  end if
END FUNCTION ' ProcessInvoice()


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)
      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()


FUNCTION Titles_Upd()
  y2 = format("Update Variation Descriptions","M52")
  y3 = format(" {Enter} to alter - {F10} to exit ","M52")
  screen print 8 15 fgp bgp y2
  screen print 22 15 fgp bgp y3
  scbtm()
END FUNCTION ' Titles_Upd()


FUNCTION PrintSchedules()
local $sch
  x = popuplist(9,35,13,"Collections Allocations","",1,0)
  if x = -1
    return (-1)
  end if

  if ptstr = "Collections"
    while true
      x = fentrybox(" Enter Collection reference ",8,"*8#","")
      if x = -1
        return (-1)
      end if
      $sch = ptstr
      if left($sch,1)="T"
        $schref = gdsoutpath|$sch|".inv"
      else
        $schref = gdsoutpath|$sch|".out"
      end if
      if file($schref) = 0
        messboxwait(" Schedule ref:"&$sch&"not found ",0,0,1)
        continue while
      end if
      tools text-editor $schref
      keys Alt-P
      keys F10
      return (0)
    end while

  else
    while true
      x = fentrybox(" Enter Job Nr for allocated items ",6,shopmask,"")
      if x = -1
        return (-1)
      end if
      $sch = ptstr
      $schref = gdsoutpath|$sch|".sch"
      if file($schref) = 0
        messboxwait(" Schedule ref:"&$sch&"not found ",0,0,1)
        continue while
      end if
      tools text-editor $schref
      keys Alt-P
      keys F10
      return (0)
    end while
  end if
END FUNCTION ' PrintSchedules()


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 "job_reqn.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' ³ QUERY is:  [Job_Nr] = jobnr                                        ³
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
  if cerror
    vunloadif("variat_n.vws")
  end if
  vloadif(dpath|"upd_varn.vw")
  order change index "job_reqn.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 EnterOrder()
  while true
    Background()
    vloadif(dpath|"despat_2.vw")
    order change key "[Job_Nr]"
    x = fentrybox(" Enter Order Nr or {Esc} to exit ",6,shopmask,"")
    if x = -1
      return (-1)
    elseif x = 0
      jobnr = ptstr
      data find "[Job_Nr]" equal jobnr options ""
      if cerror                               '   if none - then return
        messboxwait(" Job Nr"&jobnr&"not found ",0,0,1)
        return (1)
      end if

      x = SetupDetails()
      if x = -1
        return (-1)
      elseif x = 1
        continue while
      end if

      x = MarkDespatched()
      if x <> 0
        continue while
      end if

      x=ProcessInvoice(1)
      if x = -1
        repaint off
        return (-1)
      end if

    end if
  end while
END FUNCTION ' EnterOrder()


FUNCTION MarkDespatched()
  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)
      screen clear box 1 1 sch scw 0 0 no-border
      repaint off
      return (1)
    end if
  else
    messbox(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)
        screen clear box 1 1 sch scw 0 0 no-border
        repaint off
        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 = 60
  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 15
        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 .1
        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 15
        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 .1
        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 ChooseOrder()
  progress(15,10," Searching for uninvoiced orders ",0)
  vloadif(dpath|"despat_4.vw")
  order change key "[Inv_Nr]"
  remove("invoice0.idx")
  makeidx("cust_ord","invoice0.idx","0",1)
  while true
    if [Inv_Nr]<>blank
      exit while
    end if
    if [SalesAnalysis]="X"
      data goto record next
      continue while
    elseif [SalesAnalysis]=blank
      data goto record next
      continue while
    elseif [Completed]="N"
      data goto record next
      continue while
    end if

    if len([Inv_Nr])=0    'message "[Inv_Nr] is:"&str([Inv_Nr])
      x = addidxrec("invoice0.idx",str(precord),7)  'message "x is:"&str(x)
    end if
    data goto record next
  end while
  order change index "invoice0.idx"

  x = popuplist(11,29,13,"Allowÿforÿdelay InvoiceÿALLÿselected","",1,0)
  if ptstr = "Allowÿforÿdelay"
    data query execute "despat_3.dfq" index "invoice1.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' [Completed]="Y"
' and
' days([DateTB_Inv])<=days(today)
' and
' [SalesAnalysis]<>"X"
' and
' not (deleted)
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
    if cerror
      messboxwait(" No orders awaiting invoicing ",0,0,1)
      return (-1)
    end if
  elseif ptstr = "InvoiceÿALLÿselected"
    data query execute "despat3A.dfq" index "invoice1.idx"
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
' [Completed]="Y"
' and
' days([DateTB_Inv])<>blank
' and
' [SalesAnalysis]<>"X"
' and
' not (deleted)
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
    if cerror
      messboxwait(" No orders awaiting invoicing ",0,0,1)
      return (-1)
    end if
  end if
  data query execute "despat_5.dfq" index "invoice2.idx" ' exclude orders for shops
' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
'   [Customer_Code]<>"T11068"
'   and
'   [Customer_Code]<>"T11072"
'   and
'   [Customer_Code]<>"T02762"
'   and
'   [Customer_Code]<>"T02221"
' ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
  if cerror
    messboxwait(" No orders awaiting invoicing ",0,0,1)
    return (-1)
  end if
  order sort now dictionary "2invoice.idx" fields "[Job_Nr;Fitting_Date]" ascending
  vunloadif("despat_4.vw")

  while true
    vloadif(dpath|"despat_3.vw")
    order change index "2invoice.idx"
'   while true
    repaint on
    repaint
    ptval=0
    Titles()

    ptval = navrecs()

    if ptval = {p} or ptval = {P}
      jobnr = [Job_Nr]
      x=ProcessInvoice(0)
      if x = -1
        repaint off
        return (-1)
      elseif x = 1
        continue while
      end if
      vloadif(dpath|"despat_3.vw")
      Titles()

    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 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 PrintCustCopy()   ' 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("Invoice total"&currency([Invoice_Total])&"- print ONLY the Office copy? (y/n) ",1,1,1)
    if ptstr == "y"
      return (0)
    else
      return (1)
    end if
  end if
' routine to decide whether to print customer's copy
' i.e o/s balance; diff invoice & delivery addresses;
END FUNCTION ' PrintCustCopy()


FUNCTION InvDetails()
local #sumgross
  #due = [Balance_Due]                 'message "#due is:"&str(#due)
  #gross = [Invoice_Total]             'message "#gross is:"&str(#gross)
  #sumgross = tablesum([Amount_Gross]) 'message "#sumgross is:"&str(#sumgross)
' message "#gross is:"&str(#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])'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 "#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

  #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 PrintInvoice()
  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)    '   message "x is:"&str(x)
  order change index $index
  $cn=0
  if [Invoice_Total] < 0               ' Credit Notes
    $cn=1                              ' set marker
  end if
    remove(X_path|"X_inv_a.*")
    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.*")
repaint on
repaint
single-step on
    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=invpath|$nextinvnr|".pdf"        'message "$pdf is:"&str($pdf)
    if $cn=0
      if PrintCustCopy()=1               ' print BOTH copies
        _SWIP_Crystal(Xreppath|"inv_cust","P",0,1,"")
      end if
      _SWIP_Crystal(Xreppath|"inv_offc","P",0,1,"")
      _SWIP_Crystal(Xreppath|"inv_offc","EP",0,1,$pdf)
    else                               ' Credit Note
      _SWIP_Crystal(Xreppath|"crn_cust","P",0,1,"")
      _SWIP_Crystal(Xreppath|"crn_offc","P",0,1,"")
      _SWIP_Crystal(Xreppath|"crn_offc","EP",0,1,$pdf)
    end if
  vloadif(dpath|"despat_3.vw")
  order change key "[Job_Nr]"
  data find "[Job_Nr]" equal jobnr options ""
END FUNCTION ' PrintInvoice()


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")
  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
  vunloadif("X_inv_b.vws")
END FUNCTION ' ClearHardSpaces()

