// Ýêñïîðò çàÿâîê â ÑÈÀ Èíòåðíåéøíë.


var // ïðåäîïðåäåëåííûå ïåðåìåííûå

  Dataset :TDataset;
  VarExportEMail :string;
  VarName_Storage :variant;
  VarID_Storage :variant;
  varname_org :variant;
  varid_orgs :variant;
  VarDate_Doc :variant;
  varTime_Doc :tdatetime;
  VarNumber_Doc :variant;
  VarID :variant;
  VarPreq_Sum :variant;
  VarRows_count :variant;
  VarExportReport :string;
  VarINfo :string;
  VarExportOutPreqOriginalPrices :boolean; // ôëàã, íóæíî ëè ýêñïîðòèðîâàòü öåíó îðèãèíàëüíóþ èç ïðàéñ-ëèñòà. èíà÷å - öåíó, óêàçàííóþ â çàÿâêå


const
   MessageSubject = 'Ýëåêòðîííàÿ çàÿâêà SolPrice';


var
    MailMessage :Variant;
    ExportFilename :string;
    Bodystr :string;

    strval :string;

    table :ttable;

    dateprice :tdatetime;

    podr : string;
    nds :variant;
    podrcd :string;



function GetPrice :double;
begin
  if VarExportOutPreqOriginalPrices
  then result := Dataset.fieldbyname('price_pr').asfloat
  else result := Dataset.fieldbyname('price').asfloat;
end;


procedure AddStr(var DestStr: string; SourceStr :string);
begin
  if DestStr >'' then begin
     DestStr := DestStr + #13+#10;
  end;

  DestStr := DestStr + SourceStr;
end;

function ifthen_1(BoolVal :boolean; trueval,falseval :string) :string;
begin
  if boolval
  then result := trueval
  else result := falseval
end;

procedure CheckParams;
begin
   if asint64(varid_storage)=0
   then begin
     varid_storage := id_storage_current;
   end;
   if (asint64(varid_storage)<>0) and (varname_storage='')
   then begin
     varname_storage := dbQueryvalue('select name from orgs where id = :id ',[varid_storage]);
   end;
   if asint64(varid_storage)<>0
   then begin
     id_org_main := coalesce_int64( asint64( DBQueryvalue('select id_parent_org from orgs where id = :id',[VARID_STORAGE]))
                                    ,id_org_main);
   end;
end;


begin
  CheckParams;

   table := ttable.create(selfscript);

   table.tablename := gettempdir+'\outpreqtmp\'+asstring(varid)+'.dbf';

   forcedirectories(extractfilepath(table.tablename));

   table.tabletype := ttFoxpro;

   table.fielddefs.clear;
   table.fielddefs.add('numz',ftstring,12,false);
   table.fielddefs.add('datez',ftdate,0,false);
   table.fielddefs.add('codepst',ftstring,13,false);
   table.fielddefs.add('datep',ftdate,0,false);
   table.fielddefs.add('podr',ftstring,40,false);
   table.fielddefs.add('qnt',ftfloat,0,false);
   table.fielddefs.add('price2',ftfloat,0,false);
   table.fielddefs.add('price2n',ftfloat,0,false);
   table.fielddefs.add('sumnds2',ftfloat,0,false);
   table.fielddefs.add('podrcd',ftstring,12,false);
   table.fielddefs.add('mess',ftstring,40,false);

   table.createtable;

   table.open;




   bodystr := '';

   strval := 'Êëèåíò : '+asstring(dbQueryvalue('select name from orgs where id = :id',[ID_ORG_MAIN]));

   addstr(BodyStr,strval);


   podr :=  asstring(coalesce_int64(varid_storage, ID_ORG_MAIN))+' : '+
            coalesce_string(asstring(varname_storage),
                              asstring(dbQueryvalue('select name from orgs where id = :id',[ID_ORG_MAIN]))
                             );

   strval := 'Ïîëó÷àòåëü : '
            + podr
            + ' : '+coalesce_string(asstring(DBQueryvalue('select address from orgs where id = :id',[VARID_STORAGE])),
                             asstring(DBQueryvalue('select address from orgs where id = :id',[ID_ORG_MAIN])));
   addstr(BodyStr,strval);

   strval := 'Äàòà çàêàçà : '+formatdatetime('dd.mm.yyyy hh:nn:ss',vardate_doc+vartime_doc);
   addstr(BodyStr,strval);

   dataset.last; // âäðóã ýòî fibdataset, è îí íå äîáðàí

   strval := 'Ïîçèöèé : '+asstring(dataset.recordcount);
   addstr(BodyStr,strval);




   strval := 'Êîììåíòàðèé : '+asString(VarInfo);
   addstr(BodyStr,strval);

   dateprice :=  asdatetime(dbQueryValue('select first 1 a.update_org from prices_headers_upd a '
                                     +' join prices_rows b on a.id = b.id_prices_headers '
                                     +' join out_preq_rows c on b.id = c.id_prices_rows '
                                     +' where c.id_out_preq = :id',[varid]));


   podrcd := asstring(  getexternalorgcode(VARID_STORAGE,VARID_ORGS));

   dataset.first;
   while not dataset.eof do
   begin
     table.append;

     table.fieldbyname('numz').asstring := coalesce_string(varnumber_doc,asstring(varid));
     table.fieldbyname('datez').asdatetime := asdatetime(vardate_doc);
     table.fieldbyname('codepst').asstring :=
           coalesce_string( dataset.fieldbyname('price_code').asstring, dataset.fieldbyname('price_code_goods').asstring);

     table.fieldbyname('datep').asdatetime := dateprice;
     table.fieldbyname('podr').asstring := podr;
     table.fieldbyname('qnt').asfloat :=  dataset.fieldbyname('quantity').asfloat;
     table.fieldbyname('price2').asfloat := GetPrice;

     nds := dbqueryvalue('select nds from prices_rows where id = :id',[dataset.fieldbyname('id_prices_rows').asfloat]);
     if varisnull(nds)
     then nds := dbqueryvalue('select first 1 nds from prices_rows_logs where id_old = :id and id_new is null',[dataset.fieldbyname('id_prices_rows').asfloat]);

     nds := asinteger(nds);

     table.fieldbyname('price2n').asfloat := bvroundto(table.fieldbyname('price2').asfloat * ( 1- nds / (100+ nds)),-2);
     table.fieldbyname('sumnds2').asfloat := (table.fieldbyname('price2').asfloat - table.fieldbyname('price2n').asfloat ) * dataset.fieldbyname('quantity').asfloat;
     table.fieldbyname('podrcd').asstring := podrcd;
     table.fieldbyname('mess').asstring := varinfo;


     table.post;
     dataset.next;
   end;

    table.close;


    MailMessage := CreateOleObject('mailprocessor.mpmailmessage');

    if not MailMessage.srv.connected
    then MailMessage.SRV.ConnectWP('Ïîëüçîâàòåëü','1');

    if not MailMessage.srv.connected
    then begin
      CreateHintE('Íå ìîãó ïðèñîåäèíèòüñÿ.');
      exit;
    end;

    MailMessage.ID := 0;
    MailMessage.Recipients :=  varexportemail;


    MailMessage.Subject := MessageSubject;

    MailMessage.Body := BodyStr;

    MailMessage.AddAttachment(table.tablename);

    if (VarExportReport>'')
       and fileexists(VarExportReport)
    then
      MailMessage.AddAttachment(VarExportReport);


    MailMessage.Save;

    //deletefile(exportfilename);


end.
