// Скрипт импорта накладной От Вектор-Групп (Тамбов)

const UseBarcode = true; // определяет, будет ли использоваться штрихкод, поставляемый поставщиком

var
    Header :TStringList; // предопределена приложением, используется для полей заголовка
    Data :TStringList; // предопределена приложением, используется для заполнения данными, рассматривается программой как таблица в TXT-формате с разделителями - табуляциями
    Dataset :TDataset; // датасет для набора. Скрипт использует либо Data, либо Dataset

var // константы с именами, используемыми в Header, имена заголовка. например: Header[ExportAgent]='Воронеж-Фарм';
    ExportAgent :string; // все определены приложением
    Filename :string;

    ExportAgentName :string;
    ExportNakladNom :string;
    ExportNakladID_DOC :string;
    ExportNakladFACTURA :string;
    ExportNakladData :string;
    ExportNakladSklad :string;
    ExportSkladName :string;

var // Поля заголовка. Можно заполнять переменные, а можно заполнять заголовок Header с полями, имена которых отражены в блоке имен заголовка

   VarOrg :string ='';
   VarOrgCODE :string ='';
   VarOrgName :string ='';

   VarOrg2 :string ='';
   VarOrg2CODE :string ='';
   VarOrg2Name :string ='';

   VarNumberDoc :string ='';
   VarPAY_DEADLINE :string ='';
   VarDateDoc :string ='';
   VarDocReason :string ='';
   VarFACTURA :string ='';
   VarStorage :string ='';


// локальные переменные, используемые скриптом для работы
var Table :TClientdataset;
    num_doc :string;
    Item :variant;
    i :integer;
    OpenDialog :TOpenDialog;
    ThF_FIRSTPRICE,thf_SROK,thF_SrokSertif,ThF_NameSertif,thF_Amount,thF_NDS,
    thF_Name,thF_Seria,thF_Sertif,thF_NameProducer,thf_Tamog,
    thF_Country,thF_Regn,thF_Price,thF_BarCode,thF_DateSertif,thF_Em,thF_Analize :TField;
    thF_Price_Reg :TField;
    str,str1 :string;
    Field :TField;

    //InvoicesList :TStringList;


const ListSeparator = ' от ';


    function GetItemValue(Item :Variant; Name :String) :string;
    begin
       try
         result := vartostr(Item.attributes.getNamedItem(Name).value);
       except
         result := ''
       end;
    end;

    procedure AddStr(var Destination :string; const thField :tField);
    begin
      if thField<>nil
      then Destination := Destination + thField.asstring;
      Destination := Destination + #9;
    end;

    function FindField(const Table :tDataset; const FieldNames :string; const FieldDescription :string) :TField;
    var List :TstringList;
        i :integer;
    begin
       result := nil;
       List := tstringlist.create;
       try
          stringtolist(FieldNames,List,';,');
          if list.count=0 then RaiseException('не указаны имена полей в функции FindField');

          for i := 0 to List.count-1 do
          begin
            Result := Table.findfield(List[i]);
            if result<>nil then break;
          end;
          if (Result=nil) and (FieldDescription>'') then RaiseException('не найдено поле "'+FieldDescription+'" ('+FieldNames+')');
       finally
          List.free;
       end;

    end;

    function IFSTR(BoolVal :boolean; const TrueVal :string; const FAlseVal :string = '') :string;
    begin
      if BoolVal then Result := TrueVal
      else Result := FalseVal;
    end;

    function GetValueFromListDialog(List :Tstrings) :string;
    var Form :TForm;
        ListBox :TListBox;
        Panel :TPanel;
        Btn :TButton;
    begin

      result := '';
      if List=nil then  exit;

      Form := TForm.create(nil);

      try
        ListBox := TListBox.create(Form);
        with Listbox do
        begin
          parent :=Form;
          Items.text := List.text;
          if List.count>0 then ItemIndex := 0;
          align :=alclient;
        end;


        Form.caption := 'Выберите накладную:';
        form.position := poScreenCenter;
        form.borderstyle := bsDialog;
        form.width := 300;
        form.height := 250;

        Panel := tPanel.create(Form);
        with Panel do
        begin
          parent := Form;
          align := albottom;
          height := 35;
          BevelInner :=bvNone;
          BevelOuter := bvNone;

          Btn := TButton.create(Form);
          with Btn do
          begin
            Parent := Panel;
            Caption := 'Отмена';
            ModalResult := mrCancel;
            Cancel := true;
            width := 70;
            Top := 6;
            Left := Form.ClientWidth - Width - 20;
          end;


          with TButton.create(Form) do
          begin
            Parent := Panel;
            Caption := 'Ok';
            ModalResult := mrOk;
            Default := true;
            Width := Btn.width;
            Top := Btn.Top;
            Left := Btn.left- Width -10;
          end;

        end;

        if form.showmodal = mrok then
        begin
          if ListBox.Itemindex <0
          then CreateHintW('Вы не выбрали ни одной накладной')
          else Result := ListBox.Items[ListBox.Itemindex];
        end

      finally
        Form.free
      end;
    end;


 begin
     if filename = ''
     then begin
       OpenDialog := TOpenDialog.create(nil);
       try
         OpenDialog.Title := 'Укажите файл';
         OpenDialog.FileName  := AppIniFile.readstring(extractfilenamewithoutext(scriptfilename),'filename','');
         opendialog.initialdir := extractfilepath(opendialog.filename);
         OpenDialog.Filter := 'Файлы-накладные(*.xls)|*.xls*|Все файлы(*.*)|*.*';
         while  OpenDialog.execute do
         begin
           if not fileexists(OpenDialog.FileName) then CreateHint('Укажите правильно файл ')
           else begin
             Filename := OpenDialog.FileName;
             AppIniFile.writestring(extractfilenamewithoutext(scriptfilename),'filename',OpenDialog.filename);
             break;
           end;
         end;
       finally
         OpenDialog.free;
       end;
     end;

     if FileName = '' then exit;

     //InvoicesList:= Tstringlist.create;
     with TMyWait.create('Идет импорт накладной') do
     try

       Table := tclientdataset.Create(selfscript);
       try

        ReadXLS(table,filename,false,false);

        Table.First;

        while not table.eof and (table.fields[0].asstring<>'Накладная №') and  (table.fields[0].asstring<>'Код') do table.next;
        if table.eof then begin
          createhinte('Не найден номер накладной в данном формате документа'#13'Продолжение операции невозможно');
          exit;
        end
        else if (table.fields[0].asstring<>'Код') then VarNumberDoc := table.fields[1].asstring;


        while not table.eof and (table.fields[0].asstring<>'Дата накладной:') and (table.fields[0].asstring<>'Код') do table.next;
        if table.eof then begin
          createhinte('Не найдена дата накладной в данном формате документа'#13'Продолжение операции невозможно');
          exit;
        end
        else if (table.fields[0].asstring<>'Код') then VarDateDoc := table.fields[1].asstring;


        while not table.eof and (table.fields[0].asstring<>'Поставщик:') and (table.fields[0].asstring<>'Код') do table.next;
        if table.eof then begin
          createhinte('Не найден поставщик накладной в данном формате документа'#13'Продолжение операции невозможно');
          exit;
        end
        else if (table.fields[0].asstring<>'Код') then VarDateDoc := table.fields[1].asstring;


        while not table.eof and (table.fields[0].asstring<>'Код') do table.next;
        if table.eof then begin
          createhinte('Не найден заголовок таблицы'#13'Продолжение операции невозможно');
          exit;
        end;

        ReadXLS(table,filename,false,true,table.recno-1);

        dataset.first;
        while not Dataset.isempty do dataset.delete;

        thF_NAME := FindField(Table,'Наименование товара','Наименование товара');
        thF_AMOUNT := FindField(Table,'Количество','Количество единиц');
        thf_em := findfield(table,'Штук в упак_','');
        thF_Price := FindField(Table,'Сумма с НДС','Сумма с НДС');
        thF_NDS := FindField(Table,'Ставка НДС','Ставка НДС');

        {
        thf_country := findfield(table,'COUNTRY','Страна-производитель');
        thF_NameProducer := FindField(Table,'FACTORY','Производитель');
        thF_NDS := FindField(Table,'NDS_PR','Ставка НДС');
        thF_Price := FindField(Table,'PRICE_SNDS','Сумма с НДС');
        thF_Tamog := nil; //findfield(Table,'NUMBERGTD','Номер таможенной декларации');
        thF_Price_reg := findfield(Table,'reestr_GNL','Цена реестра');
        thF_Seria := FindField(Table,'SERIES','Серия');
        thF_SROK :=  FindField(Table,'GODENDO','Срок годности');
        thF_Sertif := nil; //FindField(Table,'REGNUMBER','Сертификат');
        thF_SROKSERTIF := nil; //FindField(Table,'CERTIFDATE','Срок действия сертификата');
        thF_NAMESERTIF := nil; //FindField(Table,'CERTIFLAB','Кем выдан сертификат');
        //thF_RegN := nil; //FindField(Table,'SAR_LAB;REGN','Регистрационный номер');
        thF_FIRSTPRICE := FindField(Table, 'PROIZVBEZN','Цена завода');
      //  thF_analize := nil; //FindField(Table,'analis','№ протокола анализа');
       // thF_DateSertif := findfield(table,'datasert;DOCD','');
       // thF_tamog := FindField(Table,'gtd','');
       }

      		if UseBarcode
      		then
          thF_Barcode := FindField(Table,'Штрих_код;SCANCOD;BARCODE1;barcode;barcod;skod','') // если нет, то не будет ошибки
      		else
      		  thF_Barcode := nil;



        //thF_Em := findfield(table,'package','');
        //thF_SROKSERTIF := FindField(Table,'srok_ser;srok_sert','Срок действия сертификата');


      		table.first;

        while not Table.eof and (table.fields[0].asstring>'') do
        begin
          dataset.append;
          if thf_srok<>nil then dataset.fieldbyname('srok').asstring := thf_srok.asstring;
          if thf_sroksertif<>nil then dataset.fieldbyname('sroksertif').asstring := thf_sroksertif.asstring;
          if thf_namesertif<>nil then dataset.fieldbyname('sertifname').asstring := thf_namesertif.asstring;
          if thf_amount<>nil then dataset.fieldbyname('kol').asstring := thf_amount.asstring;
          if thf_nds<>nil then dataset.fieldbyname('nds').asstring := thf_nds.asstring;
          if thf_name<>nil then dataset.fieldbyname('name').asstring := thf_name.asstring;
          if thf_firstprice<>nil then dataset.fieldbyname('firstcena').asstring := thf_firstprice.asstring;
          if thf_seria<>nil then dataset.fieldbyname('seria').asstring := thf_seria.asstring;
          if thf_sertif<>nil then dataset.fieldbyname('sertif').asstring := thf_sertif.asstring;
          if thf_nameproducer<>nil then dataset.fieldbyname('producername').asstring := thf_nameproducer.asstring;
          if thf_country<>nil then dataset.fieldbyname('countryname').asstring := thf_country.asstring;

          if thf_price<>nil then
          begin

            str := thf_price.asstring;


            //str := stringreplace(str,'р.','');
            //str := stringreplace(str,'р','');

            if (length(str)>0) and not isdigit(str[length(str)]) then delete(str,length(str),1);

            for i := length(str) downto 0 do
            if not isdigit(str[i]) and (str[i]<>',') and (str[i]<>'.') and (str[i]<>DecimalSeparator)
            then delete(str,i,1);

            str := formatfloat('############.00##', strtofloatprotected(str));

            dataset.fieldbyname('summa').asstring := str;
          end;

          if thf_price_reg<>nil then dataset.fieldbyname('price_reg').asstring := thf_price_reg.asstring;
          if thf_barcode<>nil then dataset.fieldbyname('barcode').asstring := thf_barcode.asstring;
          if thf_em<>nil then dataset.fieldbyname('em').asstring := thf_em.asstring;

          dataset.post;

          Table.Next;
        end;
       finally
          Table.free;
       end;

     finally
	   //invoiceslist.free;
       free
     end;

     createhint('Операция завершена');
 end.
