/* $Id: salork.c,v 5.54 2013/09/26 09:43:55 sasa Exp $ */
/*27.08.2021    22.01.1996      Белых А.И.      salork.c
Получение сальдо по оpганизации и счету
*/
#include        <errno.h>
#include        "buhl.h"

void  salork_iceb_t_akt_sv(class iceb_t_akt_sverki *iceb_t_akt_svr,short dn,short mn,short gn,short dk,short mk,short gk,const char *kor,const char *nai,const char *imaf,const char *imaf_bi);


void salork(const char *sh, //Счет
const char *kor,  //Код контрагента
double *db,  //Дебет
double *kr,  //Дебет
short rp,    //*0-без распечатки 1-с распечаткой*/
char *imaf, //Имя файла
char *imafact, //Имя файла с актом сверки
const char *nai,  //Наименование контрагента
short dn,short mn,short gn, //Дата начала
short dk,short mk,short gk, //Дата конца
const char *shv,
short mks, //*0-все проводки 1-без взаимно кореспондирующих*/
char *imaf_act, /*с месячными итогами*/
char *imaf_act_bi) /*без месячных итогов*/
{
time_t          tmm;
struct  tm      *bf;
short           d,m,g;
class iceb_fopen ff1;
class iceb_fopen ffact;
double          brr;
class iceb_tu_str shh("");
double          ddn,kkn;
double		dd,kk;
short           msv; /*0-без сверки 1-со сверкой*/
short           mvp; /*Метка второго прохода*/
short           mvs; /*Метка выдачи сальдо*/
char		strsql[512];
SQL_str         row;
long		kolstr;
short		godn;
short		shett=0;
short		mes=0,god=0;
double		deb=0.,kre=0.;
double		debm=0.,krem=0.;
class iceb_tu_str koment("");
short	startgodb=0; /*Стартовый год*/


if(iceb_t_poldan("Стартовый год",strsql,"nastrb.alx") == 0)
 startgodb=atoi(strsql);

godn=startgodb;
if(startgodb == 0 || startgodb > gn)
 godn=gn;

*db=0.;
*kr=0.;
mvp=msv=0;
if(shv[0] != '\0')
  msv=1;

shh.new_plus(sh);
if(rp == 1)
 {
  sprintf(imaf,"slo%d.lst",getpid());
  if(ff1.start(imaf,"w") != 0)
   return;

  sprintf(imafact,"act%d.lst",getpid());
  if(ffact.start(imafact,"w") != 0)
   return;

 }

naz:;

ddn=kkn=0.;
dd=kk=0.;
sprintf(strsql,"select deb,kre from Saldo where kkk='1' and gs=%d and \
ns='%s' and kodkon='%s'",godn,shh.ravno(),kor);
SQLCURSOR cur;
if(sql_readkey(&bd,strsql,&row,&cur) == 1)
 {
  ddn=atof(row[0]);
  kkn=atof(row[1]);
 }

if(rp == 1)
 {
  time(&tmm);
  bf=localtime(&tmm);
//  fprintf(ff1.ff,"\x0F");
  fprintf(ff1.ff,"%s\n\
%s %s %s %s %s\n\
     %s %d.%d.%d%s %s %d.%d.%d%s\n\
%s %d.%d.%d  %s - %d:%d\n",
iceb_t_get_pnk("00",0),
gettext("Распечатка проводок по счёту"),
shh.ravno(),
gettext("для контрагента"),
kor,nai,
gettext("Период с"),
dn,mn,gn,
gettext("г."),
gettext("до"),
dk,mk,gk,
gettext("г."),
gettext("По состоянию на"),
bf->tm_mday,bf->tm_mon+1,bf->tm_year+1900,
gettext("Время"),
bf->tm_hour,bf->tm_min);

  fprintf(ff1.ff,"\
--------------------------------------------------------------------------------------------------\n");

fprintf(ff1.ff,gettext("  Дата    |Сче.к.|Записал|Номер доку.|    Дебет   |   Кредит   |      К о м е н т а р и й       |\n"));
/*******
                                                                                               12345678901234567890123456789012
********/
  fprintf(ff1.ff,"\
--------------------------------------------------------------------------------------------------\n");


  //Заголовок акта сверки
  iceb_t_zagacts(dn,mn,gn,dk,mk,gk,kor,nai,ffact.ff);
  iceb_t_zagsh(sh,ffact.ff);
  


 }
/*
printw("%d.%d.%d %d.%d.%d\n",dn,mn,gn,dk,mk,gk);
refresh();
*/
mvs=0;
g=godn;
m=1;
d=1;
class iceb_t_akt_sverki iceb_t_akt_sv;
iceb_t_akt_sv.shet.new_plus(sh);

int nomer=0;

while(iceb_tu_sravmydat(d,m,g,dk,mk,gk) <= 0)
  {
/*
   printw("%d.%d.%d\n",d,m,g);
   refresh();
  */
   if(iceb_tu_sravmydat(d,m,g,dn,mn,gn) >= 0 && mvs == 0)
    {
     iceb_t_akt_sv.dn=d;
     iceb_t_akt_sv.mn=m;
     iceb_t_akt_sv.gn=g;
     if(ddn > kkn)    
      {
       iceb_t_akt_sv.start_saldo_deb=ddn-kkn;
       ddn=ddn-kkn;
       kkn=0.;
       if(rp == 1)
        {
         fprintf(ff1.ff,"%*s:%12s\n",
         iceb_tu_kolbait(37,gettext("Сальдо начальное")),gettext("Сальдо начальное"),
         iceb_tu_prnbr(ddn));
         
         printw("%*s:%12s\n",
         iceb_tu_kolbait(20,gettext("Сальдо начальное")),gettext("Сальдо начальное"),iceb_tu_prnbr(ddn));

         fprintf(ffact.ff,"%02d.%02d.%4d %-20.20s %10.2f %10s| |\n",
         d,m,g,gettext("Сальдо начальное"),ddn," ");

         fprintf(ffact.ff,"\
------------------------------------------------------ ---------------------------------------------------\n");

        }
      }
     else
      {
       iceb_t_akt_sv.start_saldo_kre=kkn-ddn;
       kkn=kkn-ddn;
       ddn=0.;
       if(rp == 1)
        {
         fprintf(ff1.ff,"\
%*s:%12s %12s\n",
         iceb_tu_kolbait(37,gettext("Сальдо начальное")),gettext("Сальдо начальное")," ",iceb_tu_prnbr(kkn));
         printw("\
%*s:%12s %12s\n",
         iceb_tu_kolbait(20,gettext("Сальдо начальное")),gettext("Сальдо начальное")," ",iceb_tu_prnbr(kkn));

         fprintf(ffact.ff,"%02d.%02d.%4d %-*.*s %10s %10.2f| |\n",
         d,m,g,
         iceb_tu_kolbait(20,gettext("Сальдо начальное")),iceb_tu_kolbait(20,gettext("Сальдо начальное")),gettext("Сальдо начальное"),
         " ",kkn);

         fprintf(ffact.ff,"\
------------------------------------------------------ ---------------------------------------------------\n");
        }
      }     

     mvs=1;
    }

   sprintf(strsql,"select * from Prov \
where val=0 and datp='%d-%02d-%02d' and sh='%s' and kodkon='%s'",
   g,m,d,shh.ravno(),kor);

   if((kolstr=cur.make_cursor(&bd,strsql)) < 0)
    {
     iceb_t_msql_error(&bd,"",strsql);
     iceb_tu_dpm(&d,&m,&g,1);
     continue;
    }
   //printw("rozden-kolstr=%d\nsrtsql=%s\n",kolstr,strsql);
   //getch();
   if(kolstr == 0)
    {
     iceb_tu_dpm(&d,&m,&g,1);
     continue;
    }
   shett=0;
   while(cur.read_cursor(&row) != 0)
    {

     if(mks == 1)
       if(iceb_tu_SRAV(row[2],sh,1) == 0 && iceb_tu_SRAV(row[3],shv,1) == 0)
         continue;
     deb=atof(row[9]);
     kre=atof(row[10]);

     /*printw("%d.%d.%d %.2f %.2f\n",bh2n.god,bh2n.mes,bh2n.den,ddn,kkn);*/
     if(iceb_tu_sravmydat(d,m,g,dn,mn,gn) >= 0)
     if(iceb_tu_sravmydat(dk,mk,gk,d,m,g) >= 0)
      {
       if(rp == 1)
        {
         if(shett == 0)
          {
     //      if(mes != m)
           if(iceb_tu_sravmydat(1,m,g,1,mes,god) != 0)
            {
             if(mes != 0)
              {
               iceb_t_salorksl(dd,kk,ddn,kkn,debm,krem,ff1.ff,ffact.ff);
               debm=krem=0.;
              }
             mes=m;
             god=g;
            }
           shett=1;
          }

         debm+=deb;
         krem+=kre;

         fprintf(ff1.ff,"%02d.%02d.%4d %-*s %-3s%4s %-*s %12s",
         d,m,g,
         iceb_tu_kolbait(6,row[3]),row[3],
         row[5],row[11],
         iceb_tu_kolbait(11,row[6]),row[6],
         iceb_tu_prnbr(deb));

         fprintf(ff1.ff," %12s %-*.*s\n",iceb_tu_prnbr(kre),iceb_tu_kolbait(32,row[13]),iceb_tu_kolbait(32,row[13]),row[13]);

         koment.new_plus(row[6]);
         koment.plus(" ",row[13]);
         
         fprintf(ffact.ff,"%02d.%02d.%4d %-*.*s %10.2f %10.2f| |\n",
         d,m,g,
         iceb_tu_kolbait(20,koment.ravno()),iceb_tu_kolbait(20,koment.ravno()),koment.ravno(),
         deb,kre);

         //заряжаем массивы
         sprintf(strsql,"%d.%d.%d|%s",d,m,g,row[6]);
         if(row[6][0] == '\0')
           nomer=-1;
         else
           nomer=iceb_t_akt_sv.data_nomd.find(strsql);

         if(nomer < 0)
          {
           iceb_t_akt_sv.data_nomd.plus(strsql);
           iceb_t_akt_sv.koment.plus(koment.ravno());
          }
         iceb_t_akt_sv.suma_deb.plus(deb,nomer);
         iceb_t_akt_sv.suma_kre.plus(kre,nomer);
         
         fprintf(ffact.ff,"\
------------------------------------------------------ ---------------------------------------------------\n");

        }
       dd+=deb;
       kk+=kre;

      }

     if(iceb_tu_sravmydat(d,m,g,dn,mn,gn) < 0)
      {
       ddn+=deb;
       kkn+=kre;
      }

    }
   iceb_tu_dpm(&d,&m,&g,1);
  }

/*
printw("Конец\n");
refresh();
*/

if(rp == 1)
 {
  brr=dd+ddn;

  printw("%*s:%12s",
  iceb_tu_kolbait(20,gettext("Оборот за период")),gettext("Оборот за период"),iceb_tu_prnbr(dd));

  printw(" %12s\n",iceb_tu_prnbr(kk));

  if(dd+ ddn >= kk+kkn)
   {
    brr=(dd+ddn)-(kk+kkn);
    printw("%*s:%12s\n",iceb_tu_kolbait(20,gettext("Сальдо конечное")),gettext("Сальдо конечное"),iceb_tu_prnbr(brr));
   }
  else
   {
    brr=(kk+kkn)-(dd+ddn);
    printw("%*s:%12s %12s\n",
    iceb_tu_kolbait(20,gettext("Сальдо конечное")),gettext("Сальдо конечное")," ",iceb_tu_prnbr(brr));
   }
  iceb_t_salorksl(dd,kk,ddn,kkn,debm,krem,ff1.ff,ffact.ff);

  if(shv[0] == '\0')
   {
    iceb_t_podpis(ff1.ff);
//    fprintf(ff1.ff,"\x12");
//    fclose(ff1.ff);
    ff1.end();
    iceb_t_konact(ffact.ff);
    ffact.end(); 
//    fclose(ffact);
   }

  sprintf(imaf_act,"asv%d.lst",getpid());
  sprintf(imaf_act_bi,"asvbi%d.lst",getpid());

  salork_iceb_t_akt_sv(&iceb_t_akt_sv,dn,mn,gn,dk,mk,gk,kor,nai,imaf_act,imaf_act_bi);
 }

*db+=dd+ddn;
*kr+=kk+kkn;
if(shv[0] != '\0' && mvp == 0)
 {
  shh.new_plus(shv);
  mvp=1;
  goto naz;
 }

if(rp == 1 && msv == 1)
 {
  fprintf(ff1.ff,"\
---------------------------------------------------------------------------------------\n\
%*s:%12s",
  iceb_tu_kolbait(37,gettext("Общий итог")),gettext("Общий итог"),iceb_tu_prnbr(*db));
  fprintf(ff1.ff,"\
 %12s\n",iceb_tu_prnbr(*kr));

  if(*db >= *kr)
   {
    brr=*db-*kr;
    fprintf(ff1.ff,"\
%37s %12s\n"," ",iceb_tu_prnbr(brr));
   }
  else
   {
    brr=*kr-*db;
    fprintf(ff1.ff,"\
%37s %12s %12s\n"," "," ",iceb_tu_prnbr(brr));
   }
  iceb_t_podpis(ff1.ff);
  ff1.end();
  iceb_t_konact(ffact.ff);
  ffact.end();

   
 }
}
/**********************************/
/*Распечатка акта сверки с общей суммой по документу*/
/*****************************************************/
void  salork_iceb_t_akt_sv(class iceb_t_akt_sverki *iceb_t_akt_svr,short dn,short mn,short gn,
short dk,short mk,short gk,
const char *kor,const char *nai,
const char *imaf,
const char *imaf_bi)
{
class iceb_fopen ff;
class iceb_fopen ff_bi;

if(ff.start(imaf,"w") != 0)
 return;
if(ff_bi.start(imaf_bi,"w") != 0)
 return;

short dt,mt,gt;
iceb_tu_poltekdat(&dt,&mt,&gt);

iceb_t_zagacts(dn,mn,gn,dk,mk,gk,kor,nai,ff.ff);
iceb_t_zagacts(dn,mn,gn,dk,mk,gk,kor,nai,ff_bi.ff);

iceb_t_akt_sv(iceb_t_akt_svr,ff.ff,ff_bi.ff);

iceb_t_konact(ff.ff);

iceb_t_podpis(ff.ff);
ff.end();

iceb_t_konact(ff_bi.ff);

iceb_t_podpis(ff_bi.ff);
ff_bi.end();

}
