// Copyright (c) 1993-2005 "Компания БЭСТ". Все права сохраняются.
//Связь отгрузки и проплаты
//Компания БЭСТ
//только для БЭСТ-4+


#INCLUDE "inkey.ch"
#INCLUDE "s_public.ch"

#TRANSLATE HOT_ALT(<x>,<nKey>,<bKey>,<nSort>)   =>  AADD(aHotKey\[3\],{<x>,<nKey>,<bKey>,<nSort>})
#DEFINE COL_BROWS0  IF(INST_COLOR,'w/b,n/w,,,w+/b','w/n,n/w,,,w+/n')   //Комментариии невыделенные

#DEFINE R_KEY  UPPER(Sclad+Vid+Type+CodeDoc+NumDoc)
#DEFINE C_KEY  "UPPER(Sclad+Vid+Type+CodeDoc+NumDoc)"

STATIC sSumma0:=0
//STATIC sDocSumma

STATIC aShipKey:={;
{;
"RBookShip",;
{||LoadPath()+"REAL\RBook.DBF"},;
"TAG_OPER",;
{||PADR(" Заказ",6)},;
{||SPACE(3)},;
{||DopCode},;
{||Date},;
{||ROUND(SumOut+IF(FIELD->L_NDS,0,FIELD->SUM_NDS)+IF(FIELD->L_ACZ,0,FIELD->SUM_ACZ)+IF(FIELD->L_CSH,0,FIELD->SUM_CSH),3)},;
{||AgentName};
},;
{;
"ScladShip",;
{||LoadPath()+"SCLAD\MDoc.dbf"},;
"TAG_REAL",;
{||PADR(" Товар",6)},;
{||CodeDoc},;
{||NumDoc},;
{||Date},;
{||GetSumOpl(R_KEY)},;
{||AgentName};
},;
{;
"ZapasShip",;
{||LoadPath()+"Zapas\MDoc.dbf"},;
"TAG_REAL",;
{||PADR(" Запас",6)},;
{||CodeDoc},;
{||NumDoc},;
{||Date},;
{||GetSumOpl(R_KEY)},;
{||AgentName};
};
}


STATIC aPayKey:={;
{;
"BankPay",;
{||LoadPath()+"BANK\DOC51.DBF"},;
"TAG_MAIN",;
{||PADR(" Банк",6)},;
{||VDoc},;
{||NDoc},;
{||DOper},;
{||Summa},;
{||Agent_N},;
{||(Summa-PSumma0)},;
{||(Summa-PSumma0+ShipPay->PSumma)};
},;
{;
"CashPay",;
{||LoadPath()+"CASH\K_ORDER.DBF"},;
"TAG_MAIN",;
{||PADR(" Касса",6)},;
{||VType},;
{||NNDoc},;
{||DataOper},;
{||Summa},;
{||IF(EMPTY(An_Name),SUBSTR(Contragent,1,25),An_Name)},;
{||(Summa-PSumma0)},;
{||(Summa-PSumma0+ShipPay->PSumma)};
},;
{;
"ScladPay",;
{||LoadPath()+"SCLAD\MDOC.DBF"},;
"TAG_REAL",;
{||PADR(" Товар",6)},;
{||CodeDoc},;
{||NumDoc},;
{||Date},;
{||GetSumOpl(R_KEY)},;
{||AgentName},;
{||(GetSumOpl(R_KEY)-PSumma0)},;
{||(GetSumOpl(R_KEY)-PSumma0+ShipPay->PSumma)};
},;
{;
"ZapasPay",;
{||LoadPath()+"ZAPAS\MDOC.DBF"},;
"TAG_REAL",;
{||PADR(" Запас",6)},;
{||CodeDoc},;
{||NumDoc},;
{||Date},;
{||GetSumOpl(R_KEY)},;
{||AgentName},;
{||(GetSumOpl(R_KEY)-PSumma0)},;
{||(GetSumOpl(R_KEY)-PSumma0+ShipPay->PSumma)};
};
}






FUNCTION ShipPay(nShipType,cShipAlias,nSumma0,dDate0,lDelete)
LOCAL sScreen:=SAVESCREEN()
LOCAL cColor:=COL_HEADR
LOCAL cLastColor:=SETCOLOR(cColor)
LOCAL aSetKey:=SaveSetKey(),i
LOCAL nTop:=5,nBottom:=17
LOCAL cColHead
LOCAL aBlock := {}
LOCAL aHeads := {}
LOCAL aWhen,aValid,aPict,bSave
LOCAL cHelp24:="Esc/Tab:Выход F8:Удалить F9:Печать Enter:Правка <*>:Подравнять"
LOCAL bPostDel:={||PostDel(),ShipDispPSumma(nShipType,cShipAlias,cHelp24)}
LOCAL aPHeads
LOCAL nArea:=SELECT()
LOCAL aHotKey := {{},{},{}}
LOCAL aDoc:={}
//sDocSumma:=nDocSumma



IF !FILE(LoadPath()+"Cash\k_order.dbf")
   SETCOLOR(cLastColor)
   RestSetKey(aSetKey)
   RETURN 0
ENDIF




altd()



cColHead :=; 
"         Дата   Вид Номер         Партнер                Остаток    Разнесено "
*123456 12345678 123 123456 12345678901234567890123 1234567890123 1234567890123*
*0123456789012345678901234567890123456789012345678901234567890123456789012345678
aBlock := {}

AADD(aBlock,{{||IF(PayType=0,SPACE(6),EVAL(aPayKey[PayType,4]))},0})
AADD(aBlock,{{||MySay( 7,aPayKey,PayType)},7})
AADD(aBlock,{{||MySay( 5,aPayKey,PayType)},16})
AADD(aBlock,{{||MySay( 6,aPayKey,PayType)},20})
AADD(aBlock,{{||LEFT(MySay(9,aPayKey,PayType),23)},27})
AADD(aBlock,{{||MySay(10,aPayKey,PayType)},51})
AADD(aBlock,{{||StrS(PSumma,13,CURR_MAIN)},65})


IF lDelete==NIL
   ShadowBox("[ Карточка оплаты ] ",2,0,22,MAXCOL(),cColor)
   SAYSCREEN("[  к оплате ]",2,53)

   SAYSCREEN(MySay(4,aShipKey,nShipType,cShipAlias),3,1)
   SAYSCREEN(MySay(7,aShipKey,nShipType,cShipAlias),3,8)
   SAYSCREEN(MySay(5,aShipKey,nShipType,cShipAlias),3,17)
   SAYSCREEN(MySay(6,aShipKey,nShipType,cShipAlias),3,21)
   SAYSCREEN(MySay(9,aShipKey,nShipType,cShipAlias),3,28)
   SAYSCREEN(MySay(8,aShipKey,nShipType,cShipAlias),3,52)

   SAYSCREEN(REPLICATE("─",78),4,1)
   SAYSCREEN(REPLICATE("─",78),18,1)
   @ 19,2 SAY "Плат.документ 123 123456: сумма / всего разнесено:"
   SAYSCREEN(REPLICATE("─",78),20,1)
   @ 21,41 SAY "Всего осталось оплатить:"

//   ScrTitul(24,)
   ScrTitul(23,"Alt-1:Банк Alt-2:Касса Alt-3:Товар по бартеру Alt-4:Запас по бартеру")
ENDIF

FOR i:=1 TO LEN(aPayKey)
NetUse(aPayKey[i,1],EVAL(aPayKey[i,2]))
ORDSETFOCUS(aPayKey[i,3])
NEXT

NetUse("ShipPay","ShipPay.dbf")
ORDSetFocus("ShipKey")
SetScope("ShipType+ShipKey",STR(nShipType,2,0)+STR((cShipAlias)->(&(IndexKey(aShipKey[nShipType,3]))),17,0))

IF lDelete==NIL
   FOR i:=1 TO LEN(aPayKey)
   dbsetrelation(aPayKey[i,1],{||PayKey},"PayKey") 
   NEXT
ENDIF

DBGOTOP()
WHILE !EOF()
   AADD(aDoc,{PayType,PayKey}) //для пересчета PSumma0
   SKIP
ENDDO
DBGOTOP()


HOT_ALT({||"1:Банковские выписки"},K_ALT_1,{||NilNum(),PayReestr(nShipType,cShipAlias,1,MDoc->AgentName),dbGotop(),2},1)
HOT_ALT({||"2:Кассовые документы"},K_ALT_2,{||NilNum(),PayReestr(nShipType,cShipAlias,2,MDoc->AgentName),dbGotop(),2},2)
HOT_ALT({||"3:Приходные товарные накладные"},K_ALT_3,{||NilNum(),PayReestr(nShipType,cShipAlias,3,MDoc->AgentName),dbGotop(),2},3)
HOT_ALT({||"4:Приходные накладные на материалы"},K_ALT_4,{||NilNum(),PayReestr(nShipType,cShipAlias,4,MDoc->AgentName),dbGotop(),2},4)
SETKEY(K_RETURN,{||FIns()})
SETKEY(K_F4,{||1})
SETKEY(K_F9,{||PrintShipPay(nShipType,cShipAlias)})
SETKEY(ASC("*"),{||CutPSumma(nShipType,(cShipAlias)->(EVAL(aShipKey[nShipType,8])))})

aHeads := {{"Разнесено:","PSumma"}}
aPict := {Replicate('9',10)+'.'+'99'}

IF lDelete==NIL

   InitList(nTop,nBottom,cColHead,aBlock,;
   {||ShipDispPSumma(nShipType,cShipAlias,cHelp24)};
   ,aHeads,,aPict,aWhen,aValid,,,,,aPHeads,bSave,bPostDel,,,,,,,cColor,,,,,,aHotKey)
ELSE
   GO TOP
   WHILE !EOF()
      RecLock()
      DELETE
      UNLOCK
      SKIP
   ENDDO
ENDIF
SumPSum()
NilNum()

DBGOTOP()
nSumma0:=sSumma0 //возврат
IF !EOF()
   DbSelectArea(cShipAlias) 
   IF _REC_YES.AND.RecLock() //по первой записи запиcываем обощенные
     IF ShipPay->PayType>0.AND.ShipPay->PayType<=LEN(aPayKey)
        dDate0:=(aPayKey[ShipPay->PayType,1])->(EVAL(aPayKey[ShipPay->PayType,7])) //возврат
        REPLACE ;
        PayType WITH IF(ShipPay->PayType=1,"Банк",IF(ShipPay->PayType=2,"Касса","Прочие"))
     ENDIF
     UNLOCK
   ENDIF
   SELECT ShipPay
ELSE
   dDate0:=CTOD("") //для возврата
ENDIF

WHILE !EOF()
   IF ASCAN(aDoc,{|x|x[1]==FIELD->PayType.AND.x[2]==FIELD->PayKey})==0
      AADD(aDoc,{PayType,PayKey}) //для пересчета PSumma0
   ENDIF
   SKIP
ENDDO

SetScope()
ORDSETFOCUS("PayKey")
FOR i:=1 TO LEN(aDoc)
MakePaySumma0(aDoc[i,1],aDoc[i,2],aPayKey)
NEXT



DBCloseArea()


FOR i:=1 TO LEN(aPayKey)
(aPayKey[i,1])->(DbCloseArea())
NEXT

RestSetKey(aSetKey)
SELECT(nArea)
RESTSCREEN(,,,,sScreen)
SETCOLOR(cLastColor)
IF lDelete==NIL
   Keyb(K_CTRL_W)
ENDIF


RETURN 0


STATIC FUNCTION MySay(n,aKey,nType,cAlias)
LOCAL xVal,cType
LOCAL lBlank:=(nType!=NIL.AND.nType==0)
IF nType!=NIL.AND.nType=0
   nType:=1
ENDIF
IF cAlias==NIL
   cAlias:=aKey[nType,1]
ENDIF
xVal:=(cAlias)->(EVAL(aKey[nType,n],nType))

cType:=VALTYPE(xVal)
IF cType=="N"
   IF lBlank
      xVal:=0
   ENDIF
   RETURN STRS(xVal,13,CURR_MAIN)
ELSEIF cType=="D"
   RETURN IF(lBlank,SPACE(8),DTOC(xVal))
ENDIF
RETURN IF(lBlank,SPACE(LEN(xVal)),xVal)



FUNCTION MyPaySay(n,nPayType,cAlias)
RETURN MySay(n,aPayKey,IF(nPayType==NIL,FIELD->PayType,nPayType),cAlias)

FUNCTION MyShipSay(n,nShipType,cAlias)
RETURN MySay(n,aShipKey,IF(nShipType==NIL,FIELD->ShipType,nShipType),cAlias)






STATIC FUNCTION PostDel(nPay)
IF ShipPay->PayType>0
   DBSELECTAREA(aPayKey[ShipPay->PayType,1])
   RecLock()
   REPLACE PSumma0 WITH PSumma0-ShipPay->PSumma
   UNLOCK
   SELECT ShipPay
ENDIF
RETURN 1

STATIC FUNCTION FIns(nKey)
LOCAL GetList:={}
LOCAL nSumma:=PSumma,nSummaDop
LOCAL nSumma0:=PSumma
LOCAL aSetKey:=SaveSetKey()
LOCAL nPayType:=PayType

IF !EOF()

   SETKEY(K_RETURN,NIL)
   SETKEY(K_LEFT,NIL)
   SETKEY(K_RIGHT,NIL)
   NilNum()
   SETKEY(K_DOWN,{||Keyb(K_RETURN,K_DOWN)})
   SETKEY(K_UP,{||Keyb(K_RETURN,K_UP)})
   nSummaDop:=(aPayKey[nPayType,1])->(EVAL(aPayKey[nPayType,11]))
   SETKEY(ASC("*"),{||nSumma:=nSummaDop,Keyb(K_RETURN)})
   SELECT ShipPay
   @ ROW(),66 GET nSumma PICT "9999999999.99" COLOR COL_GET VALID {||IF(nSumma>nSummaDop,SayError("Сумма превышает допустимый остаток!"),.T.).AND.nSumma>=0}
   SETCURSOR(1)
   KEYBOARD nKey
   READ
   SETCURSOR(0)
   IF LASTKEY()!=K_ESC
      RecLock()
      REPLACE PSumma WITH nSumma
      UNLOCK
      DBSELECTAREA(aPayKey[nPayType,1])
      RecLock()
      REPLACE PSumma0 WITH PSumma0-nSumma0+nSumma
      UNLOCK
      SELECT ShipPay
   ENDIF
ENDIF
RestSetKey(aSetKey)
RETURN 2



STATIC FUNCTION SetNum()
SETKEY(ASC('0'),{||FIns('0')})
SETKEY(ASC('1'),{||FIns('1')})
SETKEY(ASC('2'),{||FIns('2')})
SETKEY(ASC('3'),{||FIns('3')})
SETKEY(ASC('4'),{||FIns('4')})
SETKEY(ASC('5'),{||FIns('5')})
SETKEY(ASC('6'),{||FIns('6')})
SETKEY(ASC('7'),{||FIns('7')})
SETKEY(ASC('8'),{||FIns('8')})
SETKEY(ASC('9'),{||FIns('9')})
RETURN(NIL)

STATIC FUNCTION NilNum()
SETKEY(ASC('0'),NIL)
SETKEY(ASC('1'),NIL)
SETKEY(ASC('2'),NIL)
SETKEY(ASC('3'),NIL)
SETKEY(ASC('4'),NIL)
SETKEY(ASC('5'),NIL)
SETKEY(ASC('6'),NIL)
SETKEY(ASC('7'),NIL)
SETKEY(ASC('8'),NIL)
SETKEY(ASC('9'),NIL)
RETURN(NIL)



STATIC FUNCTION ShipDispPSumma(nShipType,cShipAlias,cHelp)
LOCAL nPSumma:=SumPSum()
LOCAL nDocSumma:=(cShipAlias)->(EVAL(aShipKey[nShipType,8]))
LOCAL nDifSumma:=nDocSumma-nPSumma
LOCAL cColor:=IF(nDifSumma<0,"R+/B*","W+/B*")
LOCAL cColor1:="W+/B*"
SetNum()
@ 3,66 SAY StrS(nPSumma,13,CURR_MAIN) COLOR cColor

@ 19,16 SAY MySay(5,aPayKey,PayType)+" "+MySay(6,aPayKey,PayType) COLOR cColor1
@ 19,52 SAY MySay(8,aPayKey,PayType) COLOR cColor1
IF ShipPay->PayType>0.AND.ShipPay->PayType<=LEN(aPayKey)
   @ 19,66 SAY StrS((aPayKey[ShipPay->PayType,1])->PSumma0,13,2) COLOR cColor1
ENDIF

@ 21,66 SAY StrS(nDifSumma,13,CURR_MAIN) COLOR cColor
IF nDocSumma==sSumma0
   cHelp:=LEFT(cHelp,LEN(cHelp)-14)
ENDIF
ScrTitul(24,cHelp)

IF LASTKEY()==K_TAB
   RETURN 0
ENDIF
RETURN 1



STATIC FUNCTION PayDispPSumma(nPayType,cPayAlias)
LOCAL nPSumma:=SumPSum()
LOCAL nDocSumma:=(cPayAlias)->(EVAL(aPayKey[nPayType,8]))
LOCAL nDifSumma:=nDocSumma-nPSumma
LOCAL cColor:=IF(nDifSumma<0,"R+/B*","W+/B*")
LOCAL cColor1:="W+/B*"
@ 3,66 SAY StrS(nPSumma,13,CURR_MAIN) COLOR cColor
@ 21,66 SAY StrS(nDifSumma,13,CURR_MAIN) COLOR cColor
RETURN 1


STATIC FUNCTION SumPSum()
LOCAL nRec:=ShipPay->(RECNO())
LOCAL nSum:=0
ShipPay->(DbGoTop())
WHILE !ShipPay->(EOF())
   nSum+=ShipPay->PSumma
   ShipPay->(DBSKIP())
ENDDO
ShipPay->(DBGOTO(nRec))
sSumma0:=nSum
RETURN nSum


STATIC FUNCTION PayReestr(nShipType,cShipAlias,nPayType,cAgentName)
LOCAL cScreen:=SAVESCREEN()
LOCAL cHead,cTag,cScope,xScope,cFindMacro,aSortSeek
LOCAL cColor:=COL_BROWSE
LOCAL cLastColor:=SETCOLOR(cColor)
LOCAL cAlias:=aPayKey[nPayType,1]
LOCAL nPayOrder,nArea:=SELECT()
LOCAL cOborot:="0"
LOCAL aKey:=SaveSetKey()
LOCAL nTop := 6,nBottom := 15
LOCAL cColHead 
LOCAL aBlock 
LOCAL cInsDBF := TempFile(m->GlobalTmpPath,"DBF")
LOCAL cInsIdx := TempFile(m->GlobalTmpPath,"IDX")
LOCAL aInsStru := {{'Rec','N',8,0}}
LOCAL aHeads,aPict:={,,"9999999999.99"}
LOCAL nSummaP:=0,nSummaP0

PRIVATE aRec:={}

DO CASE
   CASE nPayType==1
   cHead:="[ Банк: Документы прихода ]"
   cTag:="Pay_Name"  //вид оборота+наименование партнера
   cScope:="UPPER(OBOROT)";xScope:="0"
   cFindMacro:='cFind$UPPER(TRIM(Agent_N)).OR.cFind$UPPER(TRIM(Name))'
   aHeads := {;
   {"Дата операции..:","DOPER"},;
   {"Номер документа:","NDOC"},;
   {"Сумма..........:","Summa"}}
   aSortSeek:={;
   {'- партнеру       ','Наименование?:',;
   'LEFT(Agent_N,20)','"0"+TRIM(UPPER(aIn[1]))','@K',,,"Pay_Name"},;
   {'- дате документа ','Дата?:','DOper',;
   '"0"+DTOS(aIn[1])','@D',,,"Pay_Date"};
   }

   CASE nPayType==2
   cHead:="[ Касса: Документы прихода ]"
   cTag:="Pay_Name"  //тип+наименование партнера
   cScope:="UPPER(TYPE)";xScope:="П/О"
   cFindMacro:='cFind$UPPER(TRIM(An_Name)).OR.cFind$UPPER(TRIM(Reason)).OR.cFind$UPPER(TRIM(Priloj)).OR.cFind$UPPER(TRIM(Contragent))'
   aHeads := {;
   {"Дата операции..:","DataOper"},;
   {"Номер документа:","NNDoc"},;
   {"Сумма..........:","Summa"}}
   aSortSeek:={;
   {'- партнеру       ','Наименование?:',;
   'LEFT(An_Name,20)','"П/О"+TRIM(UPPER(aIn[1]))','@K',,,"Pay_Name"},;
   {'- дате документа ','Дата?:','DataOper',;
   '"П/О"+DTOS(aIn[1])','@D',,,"Pay_Date"};
   }
   CASE nPayType==3.OR.nPayType==4
   IF nPayType=3
      cHead:="[ Товары: Приходные накладные ]"
   ELSE
      cHead:="[ Запасы: Приходные накладные ]"
   ENDIF
   cTag:="Pay_Name"  //тип+наименование партнера
   cScope:="UPPER(TYPE)";xScope:="1"
   cFindMacro:='cFind$UPPER(TRIM(AgentName))'
   aHeads := {;
   {"Дата операции..:","Date"},;
   {"Номер документа:","NumDoc"},;
   {"Сумма..........:","Summa"}}
   aSortSeek:={;
   {'- партнеру       ','Наименование?:',;
   'LEFT(An_Name,20)','"1"+TRIM(UPPER(aIn[1]))','@K',,,"Pay_Name"},;
   {'- дате документа ','Дата?:','DataOper',;
   '"1"+DTOS(aIn[1])','@D',,,"Pay_Date"};
   }

ENDCASE



DBCREATE(cInsDBF,aInsStru)
NetUseExc('InsTable',cInsDBF)
INDEX ON Rec TO (cInsIdx)
SELECT ShipPay
GO TOP
WHILE !EOF()
   AADD(aRec,(cAlias)->(RECNO()))
   nSummaP+=PSumma
   SKIP
ENDDO
nSummaP0:=nSummaP

cColHead :=; 
"   Дата   Вид Номер         Партнер             Сумма по док  Не разнесено"
*112345678 123 123456 1234567890123456789012345 1234567890123 1234567890123*
*0123456789012345678901234567890123456789012345678901234567890123456789012345678
aBlock := {}

AADD(aBlock,{{||IF(InsTable->(DBSEEK((cAlias)->(RECNO()))),"√"," ")} ,0})


AADD(aBlock,{{||MySay(7,aPayKey,nPayType)},01})
AADD(aBlock,{{||MySay(5,aPayKey,nPayType)},10})
AADD(aBlock,{{||MySay(6,aPayKey,nPayType)},14})
AADD(aBlock,{{||MySay(9,aPayKey,nPayType)},21})
AADD(aBlock,{{||MySay(8,aPayKey,nPayType)},47})
AADD(aBlock,{{||MySay(10,aPayKey,nPayType)},61})



DbSelectArea(cAlias) 
nPayOrder:=ORDSETFOCUS(cTag)
SetScope(cScope,xScope)

SET FILTER TO !RECNO()$aRec



IF !DBSEEK(xScope+UPPER(cAgentName))
   ORDSETFOCUS("PAY_DATE")
   DBGOTOP()
ENDIF
   
ShadowBox(cHead,5,2,21,77,cColor,FRAMES1,,,"noShadow")

SAYSCREEN(REPLICATE("─",74),16,3)
SAYSCREEN(REPLICATE("─",74),19,3)
ScrTitul(23,"")
ScrTitul(24,"F6,Alt-F6:Фильтр Ins:Выбор Enter/Tab:Перенос в карточку оплаты")

SetKey(K_F8,{||1})
SetKey(K_F9,{||1})
SetKey(K_F4,{||1})
SetKey(K_INS,{||MakeIns(@nSummaP,nPayType)})
SetKey(ASC("-"),{||ClearIns(@nSummaP,nPayType)})
SetKey(ASC("+"),{||AllIns(@nSummaP,nPayType)})
SetKey(K_RETURN,{||ShipMakeTab(nShipType,aShipKey[nShipType],nPayType,aPayKey[nPayType],cShipAlias,nPayOrder)})
SetKey(K_TAB,{||Keyb(K_RETURN)})
InitList(nTop,nBottom,cColHead,aBlock,{||CurPay(nShipType,nPayType,nSummaP,nSummaP0)},aHeads,,aPict,,,,,,aSortSeek,,,,,,,,,cFindMacro)

SET FILTER TO
SetScope()

ORDSETFOCUS(nPayOrder)
InsTable->(DBCloseArea())
FErase(cInsIdx)
FErase(cInsDBF)
RestSetKey(aKey)
SETCOLOR(cLastColor)
SELECT(nArea)



RESTSCREEN(,,,,cScreen)

RETURN NIL



STATIC FUNCTION CurPay(nShipType,nPayType,nSummaP,nSummaP0)
LOCAL cc 
DO CASE
   CASE nPayType=1 //Банк
   @ 17,3 SAY SUBSTR(FIELD->NAME,1,74) COLOR COL_BROWS0
   IF UPPER(FIELD->Valuta) == UPPER(m->GlobalValuta)
      @ 18,3 SAY SUBSTR(FIELD->NAME,75,74) COLOR COL_BROWS0
   ELSE
      cc:="Валюта: "+ FIELD->VALUTA +" Курс:"+ALLTRIM(STR(FIELD->KURS))+;
      " Сумма в валюте:"+ALLTRIM(STR(FIELD->SUMMA_V,15,2))
      @ 18,3 SAY PADR(cc,74) COLOR COL_BROWS0
   ENDIF
   CASE nPayType=2 //Касса
   @ 17,3 SAY SUBSTR(FIELD->Reason,1,74) COLOR COL_BROWS0
   IF UPPER(FIELD->Code_Curr) == UPPER(m->GlobalValuta)
      @ 18,3 SAY SUBSTR(FIELD->Priloj,1,74) COLOR COL_BROWS0
   ELSE
      cc:="Валюта: "+ FIELD->Code_Curr +" Курс:"+ALLTRIM(STR(FIELD->Curs_Curr))+;
      " Сумма в валюте:"+ALLTRIM(STR(FIELD->Summ_curr,15,2))
      @ 18,3 SAY PADR(cc,74) COLOR COL_BROWS0
   ENDIF
   CASE nPayType=3.OR.nPayType=4 //Товар-Запас
   IF nPayType=3
      cc:="Склад товаров: "+Sclad 
   ELSE
      cc:="Склад запасов: "+Sclad 
   ENDIF
   @ 17,3 SAY PADR(cc,74) COLOR COL_BROWS0
   IF UPPER(FIELD->CodeVal) == UPPER(m->GlobalValuta)
      @ 18,3 SAY PADR(FIELD->Prim,74) COLOR COL_BROWS0
   ELSE
      cc:="Валюта: "+ FIELD->CodeVal +" Курс:"+ALLTRIM(STR(FIELD->CenaVal))+;
      " Сумма в валюте:"+ALLTRIM(STR(FIELD->SumOut,15,2))
      @ 18,3 SAY PADR(cc,74) COLOR COL_BROWS0
   ENDIF
   
ENDCASE
IF nShipType==1
   cc:="Отнесено на заказ: "
ELSE
   cc:="Отнесено на накладную: "
ENDIF
cc+=IF(nSummaP0>0,ALLTRIM(STR(nSummaP0,13,2))+" + ","")+ALLTRIM(STR(nSummaP-nSummaP0,13,2))+;
  IF(nSummaP0>0," = "+ALLTRIM(STR(nSummaP,13,2)),"")

@ 20,3 SAY PADC(cc,74) COLOR COL_BROWSE
RETURN 1


STATIC FUNCTION MakeIns(nSummaP,nPayType)
LOCAL nArea:=SELECT()
LOCAL cAlias:=ALIAS()
IF !EOF()
   SELECT InsTable
   IF EOF()
      AddRec()
      REPLACE Rec WITH (cAlias)->(RECNO())
      nSummaP+=(cAlias)->(EVAL(aPayKey[nPayType,10]))
   ELSE
      nSummaP-=(cAlias)->(EVAL(aPayKey[nPayType,10]))
      RecLock()
      DELETE
   ENDIF
   SELECT(nArea)
ENDIF

Keyb(K_DOWN)
RETURN 1


STATIC FUNCTION ClearIns(nSummaP,nPayType)
LOCAL nArea:=SELECT()
LOCAL cAlias:=ALIAS()

SELECT InsTable
GO TOP
WHILE !EOF()
   (cAlias)->(DBGOTO(InsTable->Rec))
   nSummaP-=(cAlias)->(EVAL(aPayKey[nPayType,10]))
   DELETE
   SKIP
ENDDO
SELECT(nArea)
GO TOP
RETURN 2


STATIC FUNCTION AllIns(nSummaP,nPayType)
LOCAL nArea:=SELECT()
LOCAL cAlias:=ALIAS()
LOCAL nRecno:=RECNO()
ClearIns(@nSummaP,nPayType)
GO TOP
WHILE !EOF()
   SELECT InsTable 
   IF !DBSEEK((cAlias)->(RECNO()))
      AddRec()
      REPLACE Rec WITH (cAlias)->(RECNO())
      (cAlias)->(DBGOTO(InsTable->Rec))
      nSummaP+=(cAlias)->(EVAL(aPayKey[nPayType,10]))
   ENDIF
   SELECT(nArea)
   SKIP
ENDDO
SELECT(nArea)
GO TOP
RETURN 2



STATIC FUNCTION ShipMakeTab(nShipType,aShip,nPayType,aPay,cShipAlias,nPayOrder)
LOCAL nArea:=SELECT(),nSummaPSumma
LOCAL nDocSumma:=(cShipAlias)->(EVAL(aShipKey[nShipType,8]))
LOCAL nSummaSpis
(aPay[1])->(SetScope())
(aPay[1])->(ORDSETFOCUS(nPayOrder))
(aPay[1])->(DBCLEARFILTER())
SELECT ShipPay
InsTable->(DbGoTop())
WHILE !InsTable->(EOF())
   DBSELECTAREA(aPay[1])
   DBGOTO(InsTable->Rec)
   nSummaSpis:=EVAL(aPay[10]) //сколько можно списать по максимуму
   RecLock()
   REPLACE PSumma0 WITH EVAL(aPay[8]) //все списываем
   UNLOCK
   SELECT ShipPay
   AddRec()
   (aPay[1])->(DBGOTO(InsTable->Rec)) 
   REPLACE ShipType WITH nShipType,;
   ShipKey WITH  (cShipAlias)->(&(INDEXKEY(aShip[3]))),;
   ShipDate WITH (cShipAlias)->(EVAL(aShip[7])),;
   PayType WITH nPayType,;
   PayKey WITH (aPay[1])->(&(INDEXKEY(aPay[3]))),;
   PayDate WITH (aPay[1])->(EVAL(aPay[7])),;
   PSumma WITH nSummaSpis
   UNLOCK
   InsTable->(dbSkip())
ENDDO

IF (nSummaPSumma:=SumPSum())>nDocSumma.AND.;
   YesOrNo({"Оплата больше суммы "+IF(nShipType=1,"заказа","накладной")+"!","Подравнять?"})
   CutPSumma(nShipType,nDocSumma,"NoSay")
ENDIF
SELECT(nArea)
RETURN 0

STATIC FUNCTION CutPSumma(nShipType,nDocSumma,lNoSay) //подравнять SELECT Shippay
LOCAL nSumma0,nSumma
LOCAL nSummaPSumma:=0
LOCAL nDiff,lDone:=.F.
LOCAL nRec:=RECNO()
IF sSumma0!=nDocSumma.AND.(lNoSay!=NIL.OR.YesOrNo("Привести сумму оплаты к сумме "+IF(nShipType=1,"заказа","накладной")+"?"))
   IF sSumma0<nDocSumma
      DbGoTop()
      WHILE !EOF()
         nSumma0:=PSumma
         nSumma:=(aPayKey[ShipPay->PayType,1])->(EVAL(aPayKey[ShipPay->PayType,11]))
         RecLock()
         REPLACE PSumma WITH nSumma
         UNLOCK
         DBSELECTAREA(aPayKey[ShipPay->PayType,1])
         SKIP(0)
         RecLock()
         REPLACE PSumma0 WITH PSumma0-nSumma0+nSumma
         UNLOCK
         SELECT ShipPay
         SKIP
      ENDDO
   ENDIF
   DbGoTop()

   WHILE !EOF()
      nSummaPSumma+=PSumma
      IF nSummaPSumma>nDocSumma
         nSumma0:=PSumma
         nSumma:=nDocSumma-nSummaPSumma+PSumma
         IF lDone
            nSumma:=0
         ELSE
            lDone:=.T.
         ENDIF
         RecLock()
         REPLACE PSumma WITH nSumma
         UNLOCK
         DBSELECTAREA(aPayKey[ShipPay->PayType,1])
         SKIP(0)
         RecLock()
         REPLACE PSumma0 WITH PSumma0-nSumma0+nSumma
         UNLOCK
         SELECT ShipPay
      ENDIF
      DBSKIP()
   ENDDO
   DBGOTO(nRec)
ENDIF
RETURN 2


STATIC PROCEDURE MakePaySumma0(nPayType,nPayKey,aPayKey)
//выбран ShipPay, Снят Scope, OrdSetFocus("PayKey") 
LOCAL nPSumma0:=0
LOCAL nArea:=SELECT()
IF nPayType>0 
   IF DBSEEK(STR(nPayType,2,0)+STR(nPayKey,17,0))
      WHILE PayType==nPayType.AND.PayKey==nPayKey
         nPSumma0+=PSumma
         SKIP
      ENDDO
   ENDIF
   DBSELECTAREA(aPayKey[nPayType,1])
   IF DBSEEK(nPayKey)
      RecLock()
      REPLACE PSumma0 WITH nPSumma0
      UNLOCK
   ENDIF
ENDIF
SELECT(nArea)
RETURN



STATIC PROCEDURE MakeShipSumma0(nShipType,nShipKey,aShipKey)
//выбран ShipPay, Снят Scope, OrdSetFocus("ShipKey") 
LOCAL nSumma0:=0
LOCAL nArea:=SELECT()
IF nShipType>0
   IF DBSEEK(STR(nShipType,2,0)+STR(nShipKey,17))
      WHILE ShipType==nShipType.AND.ShipKey==nShipKey
         nSumma0+=PSumma
         SKIP
      ENDDO
   ENDIF
   DBSELECTAREA(aShipKey[nShipType,1])
   IF DBSEEK(nShipKey)
      RecLock()
      REPLACE Summa0 WITH nSumma0
      UNLOCK
   ENDIF
ENDIF
SELECT(nArea)
RETURN




PROCEDURE PayShip(nPayType,cPayAlias,nSumma0,dDate0,lDelete,lPreDelete) //nSumma0,dDate0 - пока не испольуются
LOCAL sScreen:=SAVESCREEN()
LOCAL cColor:=COL_HEADR
LOCAL cLastColor:=SETCOLOR(cColor)
LOCAL aSetKey:=SaveSetKey(),i
LOCAL nTop:=5,nBottom:=19
LOCAL cColHead
LOCAL aBlock := {}
LOCAL aHeads := {}
LOCAL aWhen,aValid,aPict,bSave
LOCAL nArea:=SELECT()
LOCAL aHotKey := {{},{},{}}
LOCAL aDoc:={}
LOCAL aPHeads
LOCAL aa:={},lRet:=.T.

IF lDelete == NIL

   SETKEY(K_F9,{||PrintPayShip(nPayType,cPayAlias)})



   cColHead :=; 
"         Дата   Вид Номер         Партнер           Сумма по док    Разнесено "
*123456 12345678 123 123456 12345678901234567890123 1234567890123 1234567890123*
*0123456789012345678901234567890123456789012345678901234567890123456789012345678
aBlock := {}

   AADD(aBlock,{{||IF(ShipType=0,SPACE(6),EVAL(aShipKey[ShipType,4]))},0})
   AADD(aBlock,{{||MySay(7,aShipKey,ShipType)},7})
   AADD(aBlock,{{||MySay(5,aShipKey,ShipType)},16})
   AADD(aBlock,{{||MySay(6,aShipKey,ShipType)},20})
   AADD(aBlock,{{||LEFT(MySay(9,aShipKey,ShipType),23)},27})
   AADD(aBlock,{{||MySay(8,aShipKey,ShipType)},51})
   AADD(aBlock,{{||StrS(PSumma,13,CURR_MAIN)},65})



   ShadowBox("[ Справка по разнесению платежей ] ",2,0,22,MAXCOL(),cColor)
   SAYSCREEN(MySay(4,aPayKey,nPayType,cPayAlias),3,1)
   SAYSCREEN(MySay(7,aPayKey,nPayType,cPayAlias),3,8)
   SAYSCREEN(MySay(5,aPayKey,nPayType,cPayAlias),3,17)
   SAYSCREEN(MySay(6,aPayKey,nPayType,cPayAlias),3,21)
   SAYSCREEN(MySay(9,aPayKey,nPayType,cPayAlias),3,28)
   SAYSCREEN(MySay(8,aPayKey,nPayType,cPayAlias),3,52)

   SAYSCREEN(REPLICATE("─",78),4,1)
   SAYSCREEN(REPLICATE("─",78),20,1)
   @ 21,41 SAY "Всего осталось разнести:"

   ScrTitul(23,"")
   ScrTitul(24,"F9:Печать")


ENDIF


FOR i:=1 TO LEN(aShipKey)
NetUse(aShipKey[i,1],EVAL(aShipKey[i,2]))
ORDSETFOCUS(aShipKey[i,3])
NEXT

NetUse("ShipPay","ShipPay.dbf")
ORDSetFocus("PayKey")
SetScope("PayType+PayKey",STR(nPayType,2,0)+STR((cPayAlias)->(&(IndexKey(aPayKey[nPayType,3]))),17,0))

IF lDelete==NIL

   FOR i:=1 TO LEN(aShipKey)
   dbsetrelation(aShipKey[i,1],{||ShipKey},"ShipKey") 
   NEXT

ENDIF

DBGOTOP()
WHILE !EOF()
   AADD(aDoc,{ShipType,ShipKey}) //для пересчета PSumma0
   SKIP
ENDDO
DBGOTOP()


SETKEY(K_RETURN,{||1})
SETKEY(K_F8,{||1})
SETKEY(K_F4,{||1})


aHeads := {{"Разнесено:","PSumma"}}
aPict := {Replicate('9',11)+'.'+'99'}




IF lDelete == NIL


   InitList(nTop,nBottom,cColHead,aBlock,{||PayDispPSumma(nPayType,cPayAlias)},aHeads,,aPict,,,,,,,aPHeads,,,,,,,,,cColor)


ELSE

   GO TOP
   IF lPreDelete!=NIL
      IF !EOF()
         AADD(aa,"Платеж разнесен по товарным документам:")
         WHILE !EOF()

            AADD(aa,;
            MySay(4,aShipKey,ShipType)+" "+;
            MySay(7,aShipKey,ShipType)+" "+;
            MySay(5,aShipKey,ShipType)+" "+;
            MySay(6,aShipKey,ShipType)+" "+;
            MySay(9,aShipKey,ShipType))
            SKIP
         ENDDO
         AADD(aa,"Продолжить удаление?")
         IF LEN(aa)>2
            lRet:=YesOrNo(aa)
         ENDIF
      ENDIF
   ELSE
      WHILE !EOF()
         RecLock()
         DELETE
         UNLOCK
         SKIP
      ENDDO
      SetScope()
      ORDSETFOCUS("ShipKey")
      FOR i:=1 TO LEN(aDoc)
      MakeShipSumma0(aDoc[i,1],aDoc[i,2],aShipKey)
      NEXT
   ENDIF
ENDIF
SumPSum()

DBCloseArea()


FOR i:=1 TO LEN(aShipKey)
(aShipKey[i,1])->(DbCloseArea())
NEXT

RestSetKey(aSetKey)


SELECT(nArea)
RESTSCREEN(,,,,sScreen)
SETCOLOR(cLastColor)
RETURN lRet










STATIC FUNCTION PrintShipPay(nShipType,cShipAlias)
LOCAL cHead := {},aHeads:={},aHeader:={},aFields:={},cFormat,aGroup:={}
LOCAL lc:= 0,cFile:=TEMPFILE(m->GlobalTmpPath,"rep")
LOCAL nRec:=RECNO()
LOCAL bFooter:={||" "}//чтобы при EXCEL_DRILL не проходил анализ структуры
PRIVATE pDocSumma:=(cShipAlias)->(EVAL(aShipKey[nShipType,8]))
PRIVATE pAlias:=cShipAlias
PRIVATE pShipType:=nShipType


AADD(aHeads,"┌───────────────────────────┬─────────────────────────┬──────────────┬──────────────┬──────────────┐")
AADD(aHeads,"│        Документ           │         Партнер         │    Остаток   │   Разнесено  │    Осталось  │")
AADD(aHeads,"│                           │                         │              │              │    оплатить  │")
AADD(aHeads,"├───────────────────────────┼─────────────────────────┼──────────────┼──────────────┼──────────────┤")
cFormat:=   "│XXXXXX XXXXXXXX XXX XXXXXX │XXXXXXXXXXXXXXXXXXXXXXXXX│99999999999.99│99999999999.99│99999999999.99│"


AADD (aHeader,PADC('Карточка оплаты',LEN(cFormat)))
AADD (aHeader,PADC('',LEN(cFormat)))
AADD (aHeader,PADR('Документ:..................: '+TRIM(MyShipSay(4,pShipType,pAlias))+SPACE(1)+TRIM(MyShipSay(7,pShipType,pAlias))+SPACE(1)+TRIM(MyShipSay(5,pShipType,pAlias))+' номер '+ALLTRIM(MyShipSay(6,pShipType,pAlias)),LEN(cFormat)))
AADD (aHeader,PADR('Сумма к оплате по документу: '+StrS(pDocSumma,14,2)+" "+LOWER(GlobalValuta),LEN(cFormat)))
AADD (aHeader,PADR('Всего разнесено оплаты.....: '+StrS(sSumma0,14,2)+" "+LOWER(GlobalValuta),LEN(cFormat)))
AADD (aHeader,PADR('Всего осталось оплатить....: '+StrS(pDocSumma-sSumma0,14,2)+IF(pDocSumma-sSumma0>0," "+LOWER(GlobalValuta),""),LEN(cFormat)))

AADD(aFields,"MyPaySay(4)+SPACE(1)+MyPaySay(7)+SPACE(1)+MyPaySay(5)+SPACE(1)+MyPaySay(6)")
AADD(aFields,"MyPaySay(9)")
AADD(aFields,"MyPaySay(10)")
AADD(aFields,"PSumma")
AADD(aFields,"pDocSumma-=PSumma")

GO TOP
IF (lc:=TotRep(aHeader,aFields,aHeads,cFormat,,aGroup,bFooter,cFile,.F.,.T.,.T.,;
               LastRec())) > 0
   View(cFile,lc,LEN(cFormat))
ENDIF

DbGoto(nRec)

RETURN 1




STATIC FUNCTION PrintPayShip(nPayType,cPayAlias)
LOCAL cHead := {},aHeads:={},aHeader:={},aFields:={},cFormat,aGroup:={}
LOCAL lc:= 0,cFile:=TEMPFILE(m->GlobalTmpPath,"rep")
LOCAL nRec:=RECNO()
LOCAL bFooter:={||" "}//чтобы при EXCEL_DRILL не проходил анализ структуры
PRIVATE pDocSumma:=(cPayAlias)->(EVAL(aPayKey[nPayType,8]))
PRIVATE pAlias:=cPayAlias
PRIVATE pPayType:=nPayType


AADD(aHeads,"┌───────────────────────────┬─────────────────────────┬──────────────┬──────────────┐")
AADD(aHeads,"│        Документ           │         Партнер         │    Сумма по  │   Разнесено  │")
AADD(aHeads,"│                           │                         │   документу  │              │")
AADD(aHeads,"├───────────────────────────┼─────────────────────────┼──────────────┼──────────────┤")
cFormat:=   "│XXXXXX XXXXXXXX XXX XXXXXX │XXXXXXXXXXXXXXXXXXXXXXXXX│99999999999.99│99999999999.99│"


AADD (aHeader,PADC('Справка по разнесению платежей',LEN(cFormat)))
AADD (aHeader,PADC('',LEN(cFormat)))
AADD (aHeader,PADR('Документ:................: '+TRIM(MyPaySay(4,pPayType,pAlias))+SPACE(1)+TRIM(MyPaySay(7,pPayType,pAlias))+SPACE(1)+TRIM(MyPaySay(5,pPayType,pAlias))+' номер '+ALLTRIM(MyPaySay(6,pPayType,pAlias)),LEN(cFormat)))
AADD (aHeader,PADR('Сумма по документу.......: '+StrS(pDocSumma,14,2)+" "+LOWER(GlobalValuta),LEN(cFormat)))
AADD (aHeader,PADR('Всего разнесено оплаты...: '+StrS(sSumma0,14,2)+" "+LOWER(GlobalValuta),LEN(cFormat)))
AADD (aHeader,PADR('Всего осталось разнести..: '+StrS(pDocSumma-sSumma0,14,2)+IF(pDocSumma-sSumma0>0," "+LOWER(GlobalValuta),""),LEN(cFormat)))

AADD(aFields,"MyShipSay(4)+SPACE(1)+MyShipSay(7)+SPACE(1)+MyShipSay(5)+SPACE(1)+MyShipSay(6)")
AADD(aFields,"MyShipSay(9)")
AADD(aFields,"MyShipSay(8)")
AADD(aFields,"PSumma")
//AADD(aFields,"pDocSumma-=PSumma")
GO TOP

IF (lc:=TotRep(aHeader,aFields,aHeads,cFormat,,aGroup,bFooter,cFile,.F.,.T.,.T.,;
               LastRec())) > 0
   View(cFile,lc,LEN(cFormat))
ENDIF




DbGoto(nRec)

RETURN 1   



STATIC  FUNCTION GetSumOpl(xKey)
//--------------------------------------------------------------------------//
// Возвращает сумму по документу подлежащую оплате
LOCAL nSumma
//dbPush("MDOC","MDOC","",{C_KEY,xKey,,.F.,{"MDOC"}},"")
//dbPush("MDOCM","MDOCM_W","",{C_KEY,xKey,,.F.,{"MDOCM_W"}},"")
//IF SUBSTR(xKey,7) = "23"
//  nSumma := MDOC->SUMMA + IF(MDOC->L_NDS,0,MDOC->SUM_NDS) + IF(MDOC->L_ACZ,0,MDOC->SUM_ACZ) + IF(MDOC->L_CSH,0,MDOC->SUM_CSH)
//  DBEVAL({|| nSumma -= MDOCM->KOL2*Div((MDOCM->SUMFACT + IF(MDOC->L_NDS,0,MDOCM->SUM_NDS) + IF(MDOC->L_ACZ,0,MDOCM->SUM_ACZ) + IF(MDOC->L_CSH,0,MDOCM->SUM_CSH)),MDOCM->KOL) })
//ELSEIF SUBSTR(xKey,7) = "1"
IF SUBSTR(xKey,7) = "1"
  nSumma := FIELD->SUMR
ELSE
  nSumma := FIELD->SUMR + IF(FIELD->L_NDS,0,FIELD->SUM_NDS) + IF(FIELD->L_ACZ,0,FIELD->SUM_ACZ) + IF(FIELD->L_CSH,0,FIELD->SUM_CSH)
ENDIF
//dbPop()
//dbPop()
RETURN ROUND(nSumma,CURR_MAIN)




/************
Процедуры для корректировки ключевых полей в ShipPay.dbf 
в случае изменения ключевых полей в платежных документах


выполнить процедуру два раза:
- запоминаем старый ключ (перед редактированием) - стоим на старой записи 
- стоим на новой записи - редактируем ShipPay.dbf при необходимости
**/

PROCEDURE PayKey(nPayType,nStep) 
STATIC cOldKey,dOldDate
LOCAL cNewKey,cNewDate
altd()
IF nStep=1
   cOldKey:=GetPayKey(nPayType)
   dOldDate:=GetPayDate(nPayType)
ELSE
   cNewKey:=GetPayKey(nPayType)
   dNewDate:=GetPayDate(nPayType)
   ReplacePay(nPayType,cOldKey,cNewKey,dOldDate,dNewDate)
ENDIF
RETURN


STATIC FUNCTION GetPayKey(nPayType) //возвращает значение ключа по записи в базе
RETURN &(IndexKey(aPayKey[nPayType,3]))

STATIC FUNCTION GetPayDate(nPayType) //возвращает значение даты по записи в базе
RETURN EVAL(aPayKey[nPayType,7])





STATIC PROCEDURE ReplacePay(nPayType,cOldKey,cNewKey,dOldDate,dNewDate)
LOCAL nArea:=SELECT()
LOCAL aRec:={},i
IF (cOldKey!=NIL.AND.cNewKey!=NIL .AND.cOldKey!=cNewKey).OR.;
   (dOldDate!=NIL.AND.dNewDate!=NIL .AND.dOldDate!=dNewDate)
   NetUse("ShipPay","ShipPay.dbf")
   ORDSETFOCUS("PayKey")
   IF DBSEEK(STR(nPayType,2,0)+STR(cOldKey,17,0))
      WHILE PayKey==cOldKey.AND.!EOF()
         AADD(aRec,RECNO())
         SKIP
      ENDDO
      FOR i:=1 TO LEN(aRec)
      DBGOTO(aRec[i])
      RecLock()
      REPLACE PayKey WITH cNewKey,PayDate WITH dNewDate

      UNLOCK
      NEXT
   ENDIF
   CLOSE
ENDIF
SELECT(nArea)
RETURN 


PROCEDURE ShipKey(nShipType,nStep) 
STATIC cOldKey,dOldDate
LOCAL cNewKey,dNewDate

IF nStep=1
   cOldKey:=GetShipKey(nShipType)
   dOldDate:=GetShipDate(nShipType)
ELSE
   cNewKey:=GetShipKey(nShipType)
   dNewDate:=GetShipDate(nShipType)
   ReplaceShip(nShipType,cOldKey,cNewKey,dOldDate,dNewDate)
ENDIF
RETURN


STATIC FUNCTION GetShipKey(nShipType) //возвращает значение ключа по записи в базе
RETURN &(IndexKey(aShipKey[nShipType,3]))

STATIC FUNCTION GetShipDate(nShipType) //возвращает значение даты по записи в базе
RETURN EVAL(aShipKey[nShipType,7])



STATIC PROCEDURE ReplaceShip(nShipType,cOldKey,cNewKey,dOldDate,dNewDate)
LOCAL nArea:=SELECT()
LOCAL aRec:={},i
altd()

IF (cOldKey!=NIL.AND.cNewKey!=NIL.AND.cOldKey!=cNewKey).OR.;
   (dOldDate!=NIL.AND.dNewDate!=NIL.AND.dOldDate!=dNewDate)
   NetUse("ShipPay","ShipPay.dbf")
   ORDSETFOCUS("ShipKey")
   IF DBSEEK(STR(nShipType,2,0)+STR(cOldKey,17,0))
      WHILE ShipKey==cOldKey
         AADD(aRec,RECNO())
         SKIP
      ENDDO
      FOR i:=1 TO LEN(aRec)
      DBGOTO(aRec[i])
      RecLock()
      REPLACE ShipKey WITH cNewKey,ShipDate WITH dNewDate
      UNLOCK
      NEXT
   ENDIF
   CLOSE
ENDIF
SELECT(nArea)
RETURN 


FUNCTION GetaShipKey()
RETURN aShipKey
