Ejemplo n.º 1
0
    // - - - - - - - - - - - - - - - - - - - - - - - - -
    //	Запуск команды на Sql-сервере
    static bool    StartSqlCmd(string CmdText)
    {
        if (CmdText == null)
        {
            return(false);
        }
        if (CmdText.Trim() == "")
        {
            return(false);
        }
        CConsole.ShowBox("", "Выполнение команды на сервере", "");
        Connection      = new   CConnection(ConnectionString);
        Command         = new   CCommand(Connection);
        Command.Timeout = 599;
        bool Result = Command.Execute(CmdText);

        Command.Close();
        Connection.Close();
        CConsole.Clear();
        CCommon.Print(CAbc.EMPTY, "Для продолжения нажмите Enter.");
        CConsole.ClearKeyboard();
        CConsole.Flash();
        CConsole.ReadChar();
        return(Result);
    }
Ejemplo n.º 2
0
    //  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    //  Получить имя файла с помощью графической панели открытия файла
    static string SelectFileNameGUI(string SettingsPath, string DestPath)
    {
        string TmpS             = CAbc.EMPTY;
        string Result           = CAbc.EMPTY;
        string SettingsFileName = null;

        if (SettingsPath != null)
        {
            if (SettingsPath.Trim().Length > 0)
            {
                SettingsFileName = SettingsPath.Trim() + "\\" + CCommon.GetUserName() + ".ldr";
                if (CCommon.FileExists(SettingsFileName))
                {
                    TmpS = CCommon.LoadText(SettingsFileName, CAbc.CHARSET_WINDOWS);
                }
                if (TmpS == null)
                {
                    TmpS = CAbc.EMPTY;
                }
            }
        }
        TmpS = TmpS.Trim();
        TmpS = CCommon.OpenFileBox(
            "Укажите А-файл для загрузки"
            , TmpS
            , "А-файлы (?A*.*)|?a*.*"
            );
        if (TmpS == null)
        {
            return(Result);
        }
        TmpS = TmpS.Trim();
        if (TmpS.Length == 0)
        {
            return(Result);
        }
        if (SettingsFileName != null)
        {
            CCommon.SaveText(SettingsFileName, CCommon.GetDirName(TmpS), CAbc.CHARSET_WINDOWS);
        }
        Result = DestPath.Trim() + "\\" + CCommon.GetFileName(TmpS);
        if (CCommon.FileExists(Result))
        {
            CCommon.Print("", "Выбранный файл уже существует в целевом каталоге : ", Result, "", "Нажмите  ENTER  для выхода...");
            CCommon.Input();
            Result = CAbc.EMPTY;
        }
        else
        if (!CCommon.CopyFile(TmpS, Result))
        {
            CCommon.Print("Ошибка копирования файла в целевой каталог : ", Result, "", "Нажмите  ENTER  для выхода...");
            CCommon.Input();
            Result = CAbc.EMPTY;
        }
        return(Result);
    }
Ejemplo n.º 3
0
    public void    AskFixedValues()
    {
        //----------------------------------------------------------
        // если из файла читается кредитовый IBAN, то кредитовый счет запрашивать у пользователя уже не будем
        if (Kinds[CSepAFileInfo.L_CREDITIBAN] > 0 && Kinds[CSepAFileInfo.L_CREDITACC] == -1)
        {
            Kinds[CSepAFileInfo.L_CREDITACC] = -4;
        }
        string Answer = "";

        for (int CurrentField = 0; CurrentField < TotalFields; CurrentField++)
        {
            if (Kinds[CurrentField] == -1)                              /*  -1 = постоянное+редактир.  */
            {
                do
                {
                    CCommon.Write(Infos[CurrentField]);
                    if ((Values[CurrentField] != "") && (Values[CurrentField] != null))
                    {
                        CCommon.Write(" ( " + Values[CurrentField] + " )");
                    }
                    CCommon.Write(" : ");
                    Answer = CCommon.Input().Trim();
                    if ((Answer != "") && (Answer != null))
                    {
                        Values[CurrentField] = Answer;
                    }
                }       while   (Values[CurrentField] == "");
            }
        }
        CCommon.Write("Записать шаблон в файл ( пусто = не записывать ) : ");
        Answer = CCommon.Input();
        if (Answer != null)
        {
            if (Answer.Trim() != "")
            {
                if (!SaveToFile(Answer.Trim() + ((CCommon.GetExtension(Answer.Trim()) != "") ? "" : ".mod")))
                {
                    CCommon.Print(" Ошибка записи шаблона в файл " + Answer);
                }
            }
        }
        CCommon.Write("Нумеровать документы начиная с ( " + NumberDoc.ToString() + " ) : ");
        Answer = CCommon.Input();
        if ((Answer != "") && (Answer != null))
        {
            try{
                NumberDoc = CCommon.CLng(Answer.Trim());
            } catch (System.Exception Excpt) {
                NumberDoc = 1;
            }
        }
    }
Ejemplo n.º 4
0
    // - - - - - - - - - - - - - - - - - - - - - - - -
    //	Запуск выборки на Sql-сервере
    static bool    StartSqlRS(string CmdText)
    {
        if (CmdText == null)
        {
            return(false);
        }
        if (CmdText.Trim() == "")
        {
            return(false);
        }
        CConsole.ShowBox("", "Выполнение команды на сервере", "");
        Connection = new   CConnection(ConnectionString);
        RecordSet  = new   CRecordSet(Connection);
        bool Result;

        RecordSet.Timeout = 599;
        if (RecordSet.Open(CmdText))
        {
            CConsole.Clear();
            int FieldCount = RecordSet.FieldCount();
            while (RecordSet.Read())
            {
                for (int Index = 0; Index < FieldCount; Index++)
                {
                    CCommon.Print(RecordSet[Index]);
                }
            }
        }
        else
        {
            CConsole.Clear();
        }
        RecordSet.Close();
        Connection.Close();
        CCommon.Print(CAbc.EMPTY, "Для продолжения нажмите Enter.");
        CConsole.ClearKeyboard();
        CConsole.Flash();
        CConsole.ReadChar();
        return(true);
    }
Ejemplo n.º 5
0
    public void    PrintConstValues()
    {
        string Answer = "";

        CConsole.Clear();
        CCommon.Print("\tСодержимое шаблона : ");
        for (int CurrentField = 0; CurrentField < TotalFields; CurrentField++)
        {
            if ((Kinds[CurrentField] == -1) &&                                  /*  -1 = постоянное+редактир.  */
                (Values[CurrentField] != null) &&
                (Aliases[CurrentField] != null)
                )
            {
                if ((Values[CurrentField].Trim() != "") &&
                    (Aliases[CurrentField].Trim() != "")
                    )
                {
                    CCommon.Print(CCommon.Left(Infos[CurrentField], 20) + " = " + Values[CurrentField]);
                }
            }
        }
    }
Ejemplo n.º 6
0
 void    Print()
 {
     CConsole.Clear();
     for (Current = 0; Current < TOTAL_GROUP; Current++)
     {
         if (Topics[Current] == "")
         {
             TopicMenus[Current] = " ( пусто ) ";
         }
         else
         {
             TopicMenus[Current] = " Для счетов " + Topics[Current].Trim();
         }
     }
     for (Current = 0; Current < TOTAL_GROUP; Current++)
     {
         if (Topics[Current] != "")
         {
             CCommon.Print(TopicMenus[Current] + " : " + Purposes[Current] + CAbc.CRLF);
         }
     }
 }
Ejemplo n.º 7
0
    static void    Main()
    {
        const bool DEBUG       = false;
        CParam     Param       = new   CParam();
        int        Mode        = 0;                             // 1=today, 2=chk_via; 3=chk_misc ; 4=copy for MStat
        int        PrevDate    = 0;
        int        DayDate     = __.Today();
        int        NextDate    = __.Today() - 1;
        string     LogFileName = CAbc.EMPTY;
        //string		REQUEST_GET_BRC_CONNECTIONSTRING	=	" select 'Server='+Ltrim(Rtrim([Server]))+';Database='+Ltrim(Rtrim([Base]))+';Integrated Security=TRUE;' from dbo.sv_Branchs with (NoLock) where kind=3";
        string REQUEST_GET_BRANCH_KIND = " select BranchKind from dbo.vMega_Common_MyBankInfo with ( NoLock ) ";

        if (DEBUG)
        {
            Mode = 4;
        }
        else
        {
            switch (Param["MODE"].Trim().ToUpper())
            {
            case    "TODAY": {
                Mode = 1;
                break;
            }

            case    "CHK_VIA": {
                Mode = 2;
                break;
            }

            case    "CHK_MISC": {
                Mode = 3;
                break;
            }

            case    "COPY4MSTAT": {
                Mode = 4;
                break;
            }

            case    "CHK_ISCARD": {
                Chk_ISCard();
                return;
            }

            default: {
                Mode = 0;
                break;
            }
            }
        }
        if (Param["DAYDATE"].Trim() != CAbc.EMPTY)
        {
            if (__.CInt(Param["DAYDATE"].Trim()) > 0)
            {
                DayDate = __.CInt(Param["DAYDATE"].Trim());
            }
        }
        if (Param["NEXTDATE"].Trim() != CAbc.EMPTY)
        {
            if (__.CInt(Param["NEXTDATE"].Trim()) > 0)
            {
                NextDate = __.CInt(Param["NEXTDATE"].Trim());
            }
        }
        if (Mode == 0)
        {
            __.Print("Не задан режим работы !");
            return;
        }
        // -------------------------------------------------------
        CScrooge2Config Scrooge2Config = new   CScrooge2Config();

        if (!Scrooge2Config.IsValid)
        {
            CCommon.Print(Scrooge2Config.ErrInfo);
            return;
        }
        ScroogeDir = (string)Scrooge2Config["Root"].Trim();
        DayOutDir  = (string)Scrooge2Config["Output"].Trim();
        ScroogeOut = ScroogeDir + "\\" + DayOutDir;
        ServerName = (string)Scrooge2Config["Server"].Trim();
        DataBase   = (string)Scrooge2Config["DataBase"].Trim();
        if (ScroogeDir == null)
        {
            CCommon.Print("  Не найдена переменная `Root` в настройках `Скрудж-2` ");
            return;
        }
        if (ServerName == null)
        {
            CCommon.Print("  Не найдена переменная `Server` в настройках `Скрудж-2` ");
            return;
        }
        if (DataBase == null)
        {
            CCommon.Print("  Не найдена переменная `Database` в настройках `Скрудж-2` ");
            return;
        }
        CCommon.Print("  Беру настройки `Скрудж-2` здесь :  " + ScroogeDir);
        __.Print("  Сервер        :  " + ServerName);
        __.Print("  База данных   :  " + DataBase + CAbc.CRLF);
        ConnectionString = "Server=" + ServerName
                           + ";Database=" + DataBase
                           + ";Integrated Security=TRUE;"
        ;
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        if (DayOutDir != null)
        {
            DayOutDir = ScroogeDir + "\\" + DayOutDir.Trim();
            if (!CCommon.DirExists(DayOutDir))
            {
                CCommon.MkDir(DayOutDir);
            }
            if (CCommon.DirExists(DayOutDir))
            {
                DayOutDir += "\\" + CCommon.StrD(DayDate, 8, 8).Replace("/", "").Replace(".", "");
                if (!CCommon.DirExists(DayOutDir))
                {
                    CCommon.MkDir(DayOutDir);
                }
                if (!CCommon.DirExists(DayOutDir))
                {
                    DayOutDir = ScroogeDir + "\\";
                }
            }
            LogFileName = DayOutDir + "\\" + "dayopen.log";
        }
        else
        {
            LogFileName = ScroogeDir + "\\" + "dayopen.log";
        }
        Err.LogTo(LogFileName);
        // --------------------------------------------------------------
        Connection = new   CConnection(ConnectionString);
        if (!Connection.IsOpen())
        {
            __.Print("  Ошибка подключения к серверу !");
            return;
        }
        Command = new   CCommand(Connection);
        __.Print("Определяю режим банк\\филиал.");
        int BranchKind = ( int )CCommon.IsNull(Command.GetScalar(REQUEST_GET_BRANCH_KIND), -1);

        if (BranchKind == -1)
        {
            __.Print("  Ошибка выполнения команды на сервере !");
        }
        else
        if (BranchKind != 0)
        {
            MainBank = false;
        }

        /*	Выборка адреса БД БРЦ
         * if	( MainBank ) {
         *      __.Print("Вычитываю адрес БД БРЦ.");
         *      BrcConnStr	=	( string ) CCommon.IsNull( Command.GetScalar( REQUEST_GET_BRC_CONNECTIONSTRING ) , CAbc.EMPTY );
         * }
         */
        __.Print("Определяю дату предыдущего рабочего дня.");
        PrevDate = ( int )CCommon.IsNull(Command.GetScalar(" exec dbo.Mega_Day_Close;2  " + DayDate.ToString()), (int)0);
        if (PrevDate == 0)
        {
            __.Print(" Ошибка определения даты предыдущего рабочего дня !");
            return;
        }
        else
        {
            __.Print("Предыдущий рабочий день - " + __.StrD(PrevDate, 8, 8));
        }
        switch (Mode)
        {
        case    4: {
            CopyXML4Mebius(NextDate, "");
            // CopyXML4Mebius( NextDate , "kv" ); // Это перекладывание киевских отчетов очетов отключено 18 июля 2019г.
            return;
        }
        }
        Command.Close();
        Connection.Close();
        // ------------------------------------------------------
        switch (Mode)
        {
        case    1: {
            Today(PrevDate, DayDate);
            break;
        }

        case    2: {
            Chk_VIA(PrevDate
                    , (__.Month(DayDate) != __.Month(PrevDate))
                    );
            break;
        }

        case    3: {
            Chk_Misc(PrevDate, DayDate);
            break;
        }

        default: {
            __.Print("Неверно указан режим работы !");
            break;
        }
        }
    }
Ejemplo n.º 8
0
    //-----------------------------------------------------------------------------------------
    //	основная программа
    public static void Main()
    {
        const bool DEBUG       = false;
        const int  MAX_COLUMNS = 299;                                           // максимальное количество столбцов

        int[]       ColWidth = new   int[MAX_COLUMNS];                          // ширины столбцов
        int         ColNumber = 0;
        int         ALineNumber = 0;
        int         AFieldNumber = 0;
        string      AFileName = "";
        string      ModelFileName = CCommon.GetTempDir() + "\\" + "AMaker.mod";
        string      Now_Date_Str = CCommon.DtoC(CCommon.Today()).Substring(2, 6);
        string      Now_Time_Str = CCommon.Hour(CCommon.Now()).ToString("00") + CCommon.Minute(CCommon.Now()).ToString("00");
        CTsvWriter  TsvWriter = new   CTsvWriter();
        CTextReader TextReader = new   CTextReader();
        string      TsvFileName = "$";
        string      InpFileName = "";
        int         InpColCount = 0;
        int         I, SourceMode = -2;                                         // откуда читать данные : 0=ClipBoard , 1=CSV , 2=DIF
        string      Tmps = "";

        string[] SubTmps;
        //----------------------------------------------------------
        CCommon.Print("  Программа для cоздания А-файлов с платежами на основе форматных данных,");
        CCommon.Print("  полученных из электронной таблицы (CVS/DIF). Версия 2.03 от 17.09.2019г.");
        if (DEBUG)
        {
            InpFileName = "F:\\Trash\\Kazna1.csv";
        }
        else
        if (CCommon.ParamCount() < 2)
        {
            CCommon.Print("");
            CCommon.Print(" Формат запуска : ");
            CCommon.Print("      AMaker3    Имя_файла  ");
            CCommon.Print(" где : ");
            CCommon.Print("      Имя_файла  - имя файла данных в формате CSV или DIF ");
            CCommon.Print("");
            return;
        }
        else
        {
            InpFileName = CAbc.ParamStr[1].Trim();
        }

        if (InpFileName == "*")
        {
            SourceMode = 0;
        }
        else
        {
            switch (CCommon.GetExtension(InpFileName).ToUpper())
            {
            case    ".CSV": {
                SourceMode = 1;
                break;
            }

            case    ".DIF": {
                SourceMode = 2;
                break;
            }

            case    ".MOD": {
                SourceMode = -1;
                break;
            }

            default: {
                CCommon.Print("Неправильный тип файла !");
                SourceMode = -2;
                break;
            }
            }
        }
        //----------------------------------------------------------
        // если выбран файл с шаблоном, то выводим его на экран
        if (SourceMode == -1)
        {
            if (AModel.LoadFromFile(InpFileName))
            {
                AModel.PrintConstValues();
                if (CConsole.GetBoxChoice("Использовать теперь этот шаблон ?", " Да = Enter . Нет = Esc ."))
                {
                    if (CCommon.FileExists(ModelFileName))
                    {
                        CCommon.DeleteFile(ModelFileName);
                    }
                    if (CCommon.FileExists(ModelFileName))
                    {
                        CCommon.Print("Ошибка удаления файла " + ModelFileName);
                    }
                    else if (!CCommon.CopyFile(InpFileName, ModelFileName))
                    {
                        CCommon.Print("Ошибка записи файла  " + ModelFileName);
                    }
                    return;
                }
            }
        }
        else
        if (CCommon.FileExists(ModelFileName))
        {
            AModel.LoadFromFile(ModelFileName);
        }
        if ((SourceMode < 0) || (SourceMode > 2))
        {
            CCommon.Print("Неправильная строка параметров !");
            return;
        }
        //----------------------------------------------------------
        // скидываем информацию в промежуточный Tsv-файл
        TsvFileName = CCommon.GetTempName();
        if (TsvFileName == null)
        {
            TsvFileName = InpFileName + ".$$$";
        }
        else if (TsvFileName.Trim() == "")
        {
            TsvFileName = InpFileName + ".$$$";
        }
        if (SourceMode == 0)
        {
            TsvWriter.LoadFromClipboard();
            if (!TsvWriter.SaveToFile(TsvFileName))
            {
                CCommon.Print("Ошибка записи в файл " + TsvFileName);
                return;
            }
        }
        if (SourceMode > 0)
        {
            if (!CCommon.FileExists(InpFileName))
            {
                CCommon.Print("Не найден файл " + InpFileName);
                return;
            }
        }
        if (SourceMode == 1)
        {
            if (TsvWriter.LoadFromCsvFile(InpFileName))
            {
                if (!TsvWriter.SaveToFile(TsvFileName))
                {
                    CCommon.Print("Ошибка записи в файл " + TsvFileName);
                    return;
                }
            }
            else
            {
                CCommon.Print("Ошибка чтения файла " + InpFileName);
                return;
            }
        }
        if (SourceMode == 2)
        {
            if (TsvWriter.LoadFromDifFile(InpFileName))
            {
                if (!TsvWriter.SaveToFile(TsvFileName))
                {
                    CCommon.Print("Ошибка записи в файл " + TsvFileName);
                    return;
                }
            }
            else
            {
                CCommon.Print("Ошибка чтения файла " + InpFileName);
                return;
            }
        }
        //----------------------------------------------------------
        // подсчитываем количество столбцов во входящем файле , а также ширину этих столбцов
        for (I = 0; I < MAX_COLUMNS; I++)
        {
            ColWidth[I] = 0;
        }
        for (I = 0; I < (MAX_LINES * MAX_FILES); I++)
        {
            Cents[I] = 0;
        }
        if (!TextReader.Open(TsvFileName, CAbc.CHARSET_WINDOWS))
        {
            CCommon.Print("Ошибка чтения файла" + TsvFileName);
            TsvFile.Close();
            CCommon.DeleteFile(TsvFileName);
            return;
        }
        if (!TextReader.Read())
        {
            CCommon.Print("Ошибка чтения файла" + TsvFileName);
            TsvFile.Close();
            CCommon.DeleteFile(TsvFileName);
            return;
        }
        for (I = 0; I < 20; I++)
        {
            Tmps    = TextReader.Value;
            SubTmps = Tmps.Split(CCommon.Chr(9));
            if (SubTmps != null)
            {
                if (SubTmps.Length > InpColCount)
                {
                    InpColCount = SubTmps.Length;
                }
                for (ColNumber = 0; ColNumber < SubTmps.Length; ColNumber++)
                {
                    if (SubTmps[ColNumber].Length > ColWidth[ColNumber])
                    {
                        ColWidth[ColNumber] = SubTmps[ColNumber].Length;
                    }
                }
            }
            else
            {
                InpColCount = 0;
            }
            if (!TextReader.Read())
            {
                break;
            }
        }
        TextReader.Close();
        if (InpColCount == 0)
        {
            CCommon.Print("Не получается распознать входные данные ");
            CCommon.DeleteFile(TsvFileName);
            return;
        }
        //----------------------------------------------------------
        // выводим столбцы на экран и запрос пользователю ( помним , что в Csv - файле нумерация столбцов начинается с 1 )
        CConsole.Clear();
        if (!TsvFile.Open(TsvFileName, CAbc.CHARSET_WINDOWS))
        {
            CCommon.Print("Ошибка чтения файла " + TsvFileName);
            return;
        }
        for (I = 0; I < (System.Console.WindowHeight - 1); I++)
        {
            if (!TsvFile.Read())
            {
                break;
            }
            Tmps = "";
            for (ColNumber = 0; ColNumber < InpColCount; ColNumber++)
            {
                Tmps += CCommon.Left(TsvFile[ColNumber + 1], ColWidth[ColNumber]) + "¦";
            }
            if (Tmps.Length > 0)
            {
                if (Tmps.Length < System.Console.WindowWidth - 1)
                {
                    CCommon.Print(Tmps);
                }
                else
                {
                    CCommon.Print(Tmps.Substring(0, System.Console.WindowWidth - 2));
                }
            }
        }
        TsvFile.Close();
        if (!CConsole.GetBoxChoice("Для продолжения обработки нажмите Enter.", "", "Для выхода нажмите Esc. "))
        {
            CCommon.DeleteFile(TsvFileName);
            return;
        }
        CConsole.Clear();
        //----------------------------------------------------------
        // распознавание столбцов во входящем файле ( помним , что в Csv - файле нумерация столбцов начинается с 1 )
        for (ColNumber = 0; ColNumber < InpColCount; ColNumber++)
        {
            CConsole.Clear();
            CCommon.Print("");
            if (!TsvFile.Open(TsvFileName, CAbc.CHARSET_WINDOWS))
            {
                CCommon.Print("Ошибка чтения файла " + TsvFileName);
                TsvFile.Close();
                CCommon.DeleteFile(TsvFileName);
                return;
            }
            for (I = 0; I < (System.Console.WindowHeight - 1); I++)
            {
                if (!TsvFile.Read())
                {
                    break;
                }
                else
                {
                    CCommon.Print(" " + TsvFile[ColNumber + 1]);
                }
            }
            TsvFile.Close();
            if (!AModel.RecognizeColumn(ColNumber + 1))
            {
                CCommon.DeleteFile(TsvFileName);
                return;
            }
        }
        CConsole.Clear();
        //----------------------------------------------------------
        // запрашиваем у пользователя значения постоянных полей
        AModel.AskFixedValues();
        //----------------------------------------------------------
        // подсчитываем количество строк и общую сумму по входному файлу
        TotalLines = 0;
        TotalCents = 0;
        if (!TsvFile.Open(TsvFileName, CAbc.CHARSET_WINDOWS))
        {
            CCommon.Print("Ошибка чтения файла " + TsvFileName);
            TsvFile.Close();
            CCommon.DeleteFile(TsvFileName);
            return;
        }
        while (TsvFile.Read())
        {
            if (IsLineEmpty())
            {
                continue;
            }
            Cents[TotalLines] = CCommon.CLng(GetColValue(CSepAFileInfo.L_SUMA).Trim());
            TotalCents       += Cents[TotalLines];
            TotalLines++;
        }
        TsvFile.Close();
        //-----------------------------------------------------------
        // запрашиваем у пользователя имя файла , в который будет записан результат
        string ShortName = ConstPartOfName;

        CCommon.Write("Краткое имя результирующего файла ( " + ShortName + " ) : ");
        ShortName = CCommon.Input().Trim();
        if (ShortName.Length > 0)
        {
            ConstPartOfName = CCommon.Left(ShortName, 8);
        }
        //-----------------------------------------------------------
        // сверяем с пользователем общее количество строк и общую сумму
        if (!CConsole.GetBoxChoice(" Всего строк : " + CCommon.Right(TotalLines.ToString(), 11)
                                   , " Общая сумма : " + CCommon.StrN(TotalBucks, 11).Replace(",", ".")
                                   , "_________________________________"
                                   , "Для продолжения нажмите Enter."
                                   , "Для выхода - Esc. "
                                   )
            )
        {
            CCommon.DeleteFile(TsvFileName);
            return;
        }
        CConsole.Clear();
        //-----------------------------------------------------------
        // записываем результатов работы программы в файлы
        if (!TsvFile.Open(TsvFileName, CAbc.CHARSET_WINDOWS))
        {
            CCommon.Print("Ошибка чтения файла " + TsvFileName);
            TsvFile.Close();
            CCommon.DeleteFile(TsvFileName);
            return;
        }
        BatchNum = 0;
        //
        while (TotalLines > 0)
        {
            AFileName = GetAFileName();
            if (!AFile.Create(AFileName, CAbc.CHARSET_DOS))
            {
                CCommon.Print("Ошибка создания файла " + AFileName);
                break;
            }
            else
            {
                CCommon.Print(AFileName);
            }
            //
            AFile.Head[CSepAFileInfo.H_EMPTYSTR]      = "";
            AFile.Head[CSepAFileInfo.H_CRLF1]         = CAbc.CRLF;
            AFile.Head[CSepAFileInfo.H_FILENAME]      = CCommon.Left(AFileName, 12);
            AFile.Head[CSepAFileInfo.H_DATE]          = Now_Date_Str;
            AFile.Head[CSepAFileInfo.H_TIME]          = Now_Time_Str;
            AFile.Head[CSepAFileInfo.H_STRCOUNT]      = TotalLinesInBatch().ToString();
            AFile.Head[CSepAFileInfo.H_TOTALDEBET]    = "0";
            AFile.Head[CSepAFileInfo.H_TOTALCREDIT]   = TotalCentsInBatch().ToString();
            AFile.Head[CSepAFileInfo.H_DES]           = "0";
            AFile.Head[CSepAFileInfo.H_DES_ID]        = "UIAB00";
            AFile.Head[CSepAFileInfo.H_DES_OF_HEADER] = "";
            AFile.Head[CSepAFileInfo.H_CRLF2]         = CAbc.CRLF;
            //
            if (!AFile.WriteHeader())
            {
                CCommon.Print("Ошибка записи файла " + AFileName);
                AFile.Close();
                break;
            }
            //
            for (ALineNumber = 0; ALineNumber < TotalLinesInBatch(); ALineNumber++)
            {
                do
                {
                    if (!TsvFile.Read())
                    {
                        break;
                    }
                }while   (IsLineEmpty());
                for (AFieldNumber = 0; AFieldNumber < AModel.TotalFields; AFieldNumber++)
                {
                    AFile.Line[AFieldNumber] = GetColValue(AFieldNumber);
                }
                if (!AFile.WriteLine())
                {
                    CCommon.Print("Ошибка записи файла " + AFileName);
                    break;
                }
                AModel.IncNumber();
            }
            AFile.Close();
            BatchNum++;
            TotalLines -= TotalLinesInBatch();
        }
        TsvFile.Close();
        CCommon.DeleteFile(TsvFileName);
    }
Ejemplo n.º 9
0
	public	static void Main() {//FOLD01
		const	bool	DEBUG		=	false		;
		bool			UseErcRobot	=	false		;	// подключаться ли к серверу под логином ErcRobot
		const	string	ROBOT_LOGIN=	"******"	;
		const	string	ROBOT_PWD	=	"35162987"	;
		const	string	TASK_CODE	=	"OpenGate"	;
		byte	SavedColor							;
		COpengateConfig	OgConfig					;
		string		ConnectionString=	CAbc.EMPTY
		,		CleanFileName	=	CAbc.EMPTY
		,		TmpFileName	=	CAbc.EMPTY
		,		LogFileName	=	CAbc.EMPTY
		,		ScroogeDir	=	CAbc.EMPTY
		,		SettingsDir	=	CAbc.EMPTY
		,		ServerName	=	CAbc.EMPTY
		,		DataBase	=	CAbc.EMPTY
		,		FileName	=	CAbc.EMPTY
		,		AboutError	=	CAbc.EMPTY
		,		InputDir	=	CAbc.EMPTY
		,		TodayDir	=	CAbc.EMPTY
		,		StatDir		=	CAbc.EMPTY
		,		TmpDir		=	CAbc.EMPTY
		;
		int		WorkDate	=	-1
		,		SeanceNum	=	-1
		,		UniqNum		=	0
		,		i			=	0
		;
		CConnection	Connection = null					;
		System.Console.BackgroundColor	=	0			;
		System.Console.Clear()						;
		Err.LogToConsole() ;
		CCommon.Print( "","  Загрузка в `Скрудж` выплат от пенс.фонда. Версия 1.04 от 06.03.2018г." );
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - -
		// считываем конфигурацию Скрудж-2
		CScrooge2Config	Scrooge2Config	= new	CScrooge2Config();
		if	(!Scrooge2Config.IsValid) {
			CCommon.Print( Scrooge2Config.ErrInfo ) ;
			return	;
		}
		ScroogeDir	=	(string)Scrooge2Config["Root"]		;
		SettingsDir	=	(string)Scrooge2Config["Common"]	;
		ServerName	=	(string)Scrooge2Config["Server"]	;
		DataBase	=	(string)Scrooge2Config["DataBase"]	;
		if	( ServerName == null ) {
			CCommon.Print("  Не найдена переменная `Server` в настройках `Скрудж-2` ");
			return;
		}
		if	( DataBase == null ) {
			CCommon.Print("  Не найдена переменная `Database` в настройках `Скрудж-2` ");
			return;
		}
		System.Console.Title="Загрузка в `Скрудж` выплат от пенс.фонда";
		__.DeleteOldTempDirs("??????" , __.Today() - 1 );
		if	( DEBUG )
			FileName ="D:\\WorkShop\\0000105.015";
		else
			if	( __.ParamCount() > 1 )
				for	( i= 1 ; i< __.ParamCount() ; i++ )
					if	( CAbc.ParamStr[ i ].Trim().ToUpper() == "/R" ) {
						UseErcRobot	= true;
						System.Console.Title = System.Console.Title + " * ";
					}
					else
						FileName	=	CAbc.ParamStr[ i ].Trim();
		if	( __.IsEmpty( FileName ) ) {
			__.Print( "  Формат запуска :   PfuImporter.exe [/R] <FileName> " );
			__.Print( "  Пример         :   PfuImporter.exe      * " );
			return;
		}
		if	(	( ! __.IsEmpty( ScroogeDir ) )
			&&	( ! __.IsEmpty( SettingsDir ) )
			)
			SettingsDir	=	ScroogeDir.Trim() + CAbc.SLASH + SettingsDir.Trim();
		else
			SettingsDir	=	CAbc.EMPTY;
		if	( FileName == "*" )
			FileName	=	SelectFileNameGUI( SettingsDir );
		if	( ! __.FileExists( FileName ) ) {
			__.Print( " Не найден указанный файл ! " );
			return;
		}
		CleanFileName	=	__.GetFileName( FileName );
		UniqNum		=	GetUniqNum( FileName );
		if	( __.GetExtension( CleanFileName ).Trim().ToUpper() == ".MOD" ) {
			if	( __.FileExists( ModelFileName ) )
				__.DeleteFile( ModelFileName ) ;
			__.CopyFile( FileName , ModelFileName );
			return;
		}
		if	( ! __.IsDigit( CleanFileName.Replace(".","") ) ) {
			__.Print( " Указан неправильный файл ! " );
			return;
		}
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - -
		// подключаемся к SQL-серверу
		ConnectionString	=	"Server="	+	ServerName
					+	";Database="	+	DataBase	;
		if	( UseErcRobot )
				ConnectionString	+=	";UID=" + ROBOT_LOGIN + ";PWD=" + ROBOT_PWD + ";" ;
		else
				ConnectionString	+=	";Integrated Security=TRUE;" ;
		try {
			Connection		= new	CConnection( ConnectionString );
		} catch ( System.Exception Excpt ) {
			CCommon.Print( Excpt.ToString() );
			CCommon.Print( "","  Ошибка подключения к серверу !" );
		}
		if	( ! Connection.IsOpen() ) {
			CCommon.Print( "","  Ошибка подключения к серверу !" );
			return;
		}
		else
			if	( DEBUG )
				CCommon.Print("  Сервер        :  " + ServerName );
		Command			= new	CCommand(Connection) ;
		if	( ! Command.IsOpen() )  {
			CCommon.Print( "  Ошибка подключения к базе данных !" );
			return;
		}
		else
			if	( DEBUG )
				CCommon.Print("  База данных   :  " + DataBase );
		System.Console.Title=System.Console.Title+"   | "+ServerName+"."+DataBase	;
		CConsole.Clear();
		LoadModel( ModelFileName ) ;
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - -
		// считываем настройки универсального шлюза
		WorkDate		=	( int ) __.IsNull( Command.GetScalar( " exec  dbo.pMega_OpenGate_Days;7 " ) , (int) 0 );
		if	( WorkDate < 1 ) {
			__.Print( " Ошибка определения даты текущего рабочего дня. " );
			Command.Close();
			Connection.Close();
			return	;
		}
		OgConfig	= new	COpengateConfig();
		OgConfig.Open( WorkDate );
		if	( ! OgConfig.IsValid() ) {
			__.Print( "  Ошибка чтения настроек программы из " + OgConfig.Config_FileName() );
			__.Print( OgConfig.ErrInfo())		;
			Command.Close();
			Connection.Close();
			return;
		}
		SeanceNum	=	( int ) __.IsNull( Command.GetScalar(" exec dbo.pMega_OpenGate_Days;4  @TaskCode='" + TASK_CODE + "',@ParamCode='NumSeance' ") , (int) 0 );
		if	( SeanceNum < 1 ) {
			__.Print( " Ошибка определения номера сеанса " );
			Command.Close();
			Connection.Close();
			return	;
		}
		TodayDir	=	(string)OgConfig.TodayDir()		;
		TmpDir		=	(string)OgConfig.TmpDir()		;
		StatDir		=	(string)OgConfig.StatDir()		;
		if ( (TodayDir == null) || (InputDir == null) ) {
			__.Print( "  Ошибка чтения настроек программы из " + OgConfig.Config_FileName() );
			Command.Close();
			Connection.Close();
			return;
		}
		TodayDir	=	TodayDir.Trim() ;
		StatDir		=	StatDir.Trim();
		TmpDir		=	TmpDir.Trim();
		if	( ! __.DirExists( TodayDir ) )
			__.MkDir( TodayDir );
		if	( ! __.DirExists( StatDir ) )
			__.MkDir( StatDir );
		if	( ! __.DirExists( TmpDir ) )
			__.MkDir( TmpDir );
		if	( ! __.SaveText( StatDir + "\\" + "test.dat" , "test.dat" , CAbc.CHARSET_DOS ) ) {
			__.Print( " Ошибка записи в каталог " + StatDir );
			Command.Close();
			Connection.Close();
			return	;
		}
		__.DeleteFile(StatDir + "\\" + "test.dat");
		LogFileName	=	OgConfig.LogDir() + "\\SEANS" + SeanceNum.ToString("000")  + ".TXT";
		Err.LogTo( LogFileName );
		__.AppendText( LogFileName , __.Now() + "   " + USER_NAME + "  загружает файл " + CleanFileName + CAbc.CRLF , CAbc.CHARSET_WINDOWS );
		TmpFileName		=	TodayDir + CAbc.SLASH + CleanFileName	;
		if	( ! __.FileExists( TmpFileName ) )
			__.CopyFile( FileName , TmpFileName ) ;
		if	( ! __.FileExists( TmpFileName ) ) {
			__.Print( " Ошибка записи файла " + TmpFileName );
			Command.Close();
			Connection.Close();
			return ;
		}
		TmpFileName		=	TmpDir + CAbc.SLASH
					+	__.Right( "0" + __.Hour(__.Clock()).ToString() , 2 )
					+	__.Right( "0" + __.Minute( __.Clock()).ToString() , 2 )
					+	__.Right( "0" + __.Second( __.Clock()).ToString() , 2 )	;
		if( ! __.DirExists( TmpFileName ) )
			__.MkDir( TmpFileName )	;
		TmpFileName		=	TmpFileName + CAbc.SLASH + CleanFileName	;
		if	( __.FileExists( TmpFileName ) )
			__.DeleteFile( TmpFileName )	;
		if	( __.FileExists( TmpFileName ) ) {
			__.Print("Ошибка удаления файла ",TmpFileName)	;
			Command.Close();
			Connection.Close();
			return	;
		}
		__.CopyFile( FileName , TmpFileName )	;
		if	( DEBUG )
			__.Print("  Беру настройки шлюза здесь :  " + OgConfig.Config_FileName() );
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - -
		// проверяем пачку
		AboutError	=	CheckPfuFile( FileName , UniqNum ) ;
		if	( __.IsEmpty( AboutError ) )  {
			if	( ! CConsole.GetBoxChoice(
								" Всего строк : " + TotalLines.ToString()
							,	" Общая сумма : " + ( __.CCur( TotalCents ) / 100 ).ToString().Replace(",",".")
							,	" Дебет.счет  : " + __.Left(DebitMoniker , 26 )
							,	__.Left( DebitName  , 42 )
							,	"__________________________________________"
							,	" Для загрузки нажмите ENTER . "
							,	" Для выхода - ESC."
							)
				) {
				__.AppendText( LogFileName ,  CAbc.CRLF + __.Now() + "  загрузка отменена. " + CAbc.CRLF , CAbc.CHARSET_WINDOWS );
				Command.Close();
				Connection.Close();
				return;
			}
		}
		else	{
			__.Print( AboutError );
			__.AppendText( LogFileName ,  CAbc.CRLF + AboutError + CAbc.CRLF , CAbc.CHARSET_WINDOWS );
			SavedColor		=	CConsole.BoxColor ;
			CConsole.BoxColor	=	CConsole.RED*16 + CConsole.WHITE	;
			if	( ! CConsole.GetBoxChoice(	" При проверке файла обнаружены ошибки !"
							,	"__________________________________________"
							,	" Всего строк : " + TotalLines.ToString()
							,	" Общая сумма : " + ( __.CCur( TotalCents ) / 100 ).ToString().Replace(",",".")
							,	" Дебет.счет  : " + __.Left(DebitMoniker , 26 )
							,	__.Left( DebitName  , 42 )
							,	"__________________________________________"
							,	" Для отмены загрузки нажмите ESC . "
							,	" Для выполнения загрузки - ENTER ."
							)
				) {
				__.AppendText( LogFileName ,  CAbc.CRLF + __.Now() + "  загрузка отменена. " + CAbc.CRLF , CAbc.CHARSET_WINDOWS );
				CConsole.BoxColor	=	SavedColor ;
				Command.Close();
				Connection.Close();
				return;
			}
			CConsole.BoxColor	=	SavedColor ;
		}
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - -
		// загружаем пачку
		LoadPfuFile( FileName , UniqNum );
		__.AppendText( LogFileName ,  CAbc.CRLF + __.Now() + "  загрузка завершена. " + CAbc.CRLF , CAbc.CHARSET_WINDOWS );
		CConsole.ShowBox(CAbc.EMPTY," Подождите..." ,CAbc.EMPTY) ;
		Command.Execute("  exec pMega_OpenGate_PayRoll;2 "
			+	"  @FileName='"  + CleanFileName + "-" + UniqNum.ToString().Trim() + "'"
			+	", @DayDate=" + WorkDate.ToString()
			) ;
		CConsole.Clear();
		Connection.Close();
	}//FOLD01
Ejemplo n.º 10
0
    static void Main()
    {
        string ScroogeDir       = CAbc.EMPTY;
        string ServerName       = CAbc.EMPTY;
        string DataBase         = CAbc.EMPTY;
        string ConnectionString = CAbc.EMPTY;

        if (!DEBUG)
        {
            if (__.ParamCount() < 2)
            {
                PrintAboutMe();
                return;
            }
        }
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        CCommon.Print("", " Построитель сальдовок для Фонда Гарантирования. Версия 1.03 от 12.03.2018г.", "");
        CScrooge2Config Scrooge2Config = new   CScrooge2Config();

        if (!Scrooge2Config.IsValid)
        {
            CCommon.Print(Scrooge2Config.ErrInfo);
            return;
        }
        ScroogeDir = (string)Scrooge2Config["Root"];
        ServerName = (string)Scrooge2Config["Server"];
        DataBase   = (string)Scrooge2Config["DataBase"];
        if (ScroogeDir == null)
        {
            CCommon.Print("  Не найдена переменная `Root` в настройках `Скрудж-2` ");
            return;
        }
        if (ServerName == null)
        {
            CCommon.Print("  Не найдена переменная `Server` в настройках `Скрудж-2` ");
            return;
        }
        if (DataBase == null)
        {
            CCommon.Print("  Не найдена переменная `Database` в настройках `Скрудж-2` ");
            return;
        }
        CCommon.Print("  Беру настройки `Скрудж-2` здесь :  " + ScroogeDir);
        __.Print("  Сервер        :  " + ServerName);
        __.Print("  База данных   :  " + DataBase + CAbc.CRLF);
        ConnectionString = "Server=" + ServerName
                           + ";Database=" + DataBase
                           + ";Integrated Security=TRUE;"
        ;
        Connection = new CConnection(ConnectionString);
        if (!Connection.IsOpen())
        {
            CCommon.Print("  Ошибка подключения к источнику данных !");
            return;
        }
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        string TODAY_STR = CCommon.StrD(CCommon.Today(), 10, 10).Substring(6)
                           + CCommon.StrD(CCommon.Today(), 10, 10).Substring(2, 4)
                           + CCommon.StrD(CCommon.Today(), 10, 10).Substring(0, 2);
        CParam Param = new   CParam();

        if (!__.IsEmpty(Param["DEBUG"]))
        {
            DEBUG = true;
        }
        bool   NeedCorrection = ((Param["COR"]).ToUpper() == "Y");
        string Date;

        if (__.IsEmpty(Param["DATE"]))
        {
            Date = TODAY_STR;
        }
        else
        {
            Date = (Param["DATE"]);
        }
        string DateStr = Date.Trim().Replace(",", "").Replace(".", "").Replace("/", "");

        if (!__.IsEmpty(Param["SEP"]))
        {
            switch (Param["SEP"].ToUpper()[0])
            {
            case    'C': {
                MetaData[0] = 44;
                break;
            }

            case    'S': {
                MetaData[0] = 59;
                break;
            }

            case    'T': {
                MetaData[0] = 9;
                break;
            }

            default: {
                __.Print("Указан неизвестный разделитель полей.");
                break;
            }
            }
        }
        if (__.IsEmpty(Param["MODE"]))
        {
            __.Print("Не указано `mode` - какой отчет строить .");
        }
        else
        {
            switch (Param["MODE"].ToUpper().Trim())
            {
            case    "N63": {
                WriteDataToCsv(
                    "exec dbo.Mega_Report_SaldoFGV;2 '" + Date
                    + "','2903'"
                    + (NeedCorrection ? ",1" : "")
                    , DateStr + "-63.csv"
                    );
                break;
            }

            case    "N64": {
                WriteDataToCsv(
                    "exec dbo.Mega_Report_SaldoFGV;2 '" + Date
                    + "','2620,2622,2625,2628,2630,2635,2638,2903,3320,3328,3330,3338,3340,3348'"
                    + (NeedCorrection ? ",1" : "")
                    , DateStr + ".csv"
                    );
                break;
            }

            case    "N65": {
                WriteDataToCsv(
                    "exec dbo.Mega_Report_SaldoFGV;2 '" + Date
                    + "','2600,2602,2603,2604,2605,2608,2610,2615,2618'"
                    + (NeedCorrection ? ",1" : "")
                    , DateStr + "-65.csv"
                    );
                break;
            }

            default: {
                __.Print("Указан неправильный код отчета.");
                break;
            }
            }
        }
        if (DEBUG)
        {
            WriteDataToCsv(
                "exec dbo.Mega_Report_SaldoFGV;2 '2015.12.01','2903',1"
                , "20160801-63.csv"
                );
        }
        Connection.Close();
        __.Print("Готово.");
        return;
    }
Ejemplo n.º 11
0
    static void    Main()
    {
        const bool DEBUG = false
        ;
        string ScroogeDir  = CAbc.EMPTY
        , ServerName       = CAbc.EMPTY
        , DataBase         = CAbc.EMPTY
        , ConnectionString = CAbc.EMPTY
        ;
        int UserId = 0
        , GroupId  = 0
        , BranchId = 0
        , DateFrom = 0
        , DateInto = 0
        ;
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        CParam Param = new   CParam();

        if (!DEBUG)
        {
            if (__.ParamCount() < 2)
            {
                PrintAboutMe();
                return;
            }
        }
        if (!CCommon.IsEmpty(Param["UserId"]))
        {
            UserId = __.CInt(Param["UserId"]);
        }
        if (!CCommon.IsEmpty(Param["GroupId"]))
        {
            UserId = __.CInt(Param["GroupId"]);
        }
        if (!CCommon.IsEmpty(Param["BranchId"]))
        {
            BranchId = __.CInt(Param["BranchId"]);
        }
        if (!CCommon.IsEmpty(Param["DateInto"]))
        {
            DateInto = __.GetDate(Param["DateInto"]);
        }
        if (!CCommon.IsEmpty(Param["DateFrom"]))
        {
            DateFrom = CCommon.GetDate(Param["DateFrom"]);
        }
        if ((DateFrom == 0) && (DateInto != 0))
        {
            DateFrom = DateInto;
        }
        if (DateInto == 0)
        {
            __.Print("Ошибка : не задана отчетная дата !");
            return;
        }
        if ((BranchId == 0) && (UserId == 0) && (GroupId == 0))
        {
            __.Print("Ошибка : не заданы условия построения отчета !");
            return;
        }
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        CConsole.Color = CConsole.GRAY;
        CConsole.Clear();
        CCommon.Print("", " Построение выписок в формате Скрудж-2. Версия 1.01 от 13.10.2017г.", "");
        CScrooge2Config Scrooge2Config = new   CScrooge2Config();

        if (!Scrooge2Config.IsValid)
        {
            CCommon.Print(Scrooge2Config.ErrInfo);
            return;
        }
        ScroogeDir = (string)Scrooge2Config["Root"].Trim();
        ServerName = (string)Scrooge2Config["Server"];
        DataBase   = (string)Scrooge2Config["DataBase"];
        if (ScroogeDir == null)
        {
            CCommon.Print("  Не найдена переменная `Root` в настройках `Скрудж-2` ");
            return;
        }
        if (ServerName == null)
        {
            CCommon.Print("  Не найдена переменная `Server` в настройках `Скрудж-2` ");
            return;
        }
        if (DataBase == null)
        {
            CCommon.Print("  Не найдена переменная `Database` в настройках `Скрудж-2` ");
            return;
        }
        CCommon.Print("  Беру настройки `Скрудж-2` здесь :  " + ScroogeDir);
        __.Print("  Сервер        :  " + ServerName);
        __.Print("  База данных   :  " + DataBase + CAbc.CRLF);
        ConnectionString = "Server=" + ServerName
                           + ";Database=" + DataBase
                           + ";Integrated Security=TRUE;";
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        System.Console.Title = "  Выписка в формате Скрудж-2              |   " + ServerName + "." + DataBase;
        CSc2Extract Sc2Extract = new   CSc2Extract();

        if (Sc2Extract.Open(ConnectionString))
        {
            Sc2Extract.Path         = __.GetCurDir();
            Sc2Extract.DateFrom     = DateFrom;
            Sc2Extract.DateInto     = DateInto;
            Sc2Extract.CbMode       = false;
            Sc2Extract.CoolSum      = false;
            Sc2Extract.ApartFile    = true;
            Sc2Extract.NeedPrintMsg = true;
            Sc2Extract.OverMode     = 2;
            Sc2Extract.BranchId     = BranchId;
            Sc2Extract.GroupId      = GroupId;
            Sc2Extract.UserId       = UserId;
            Sc2Extract.Build();
            Sc2Extract.Close();
            __.Print("Выписки построены.", "Для продолжения нажмите Enter...");
            CConsole.ClearKeyboard();
            CConsole.Flash();
            CConsole.ReadChar();
        }
    }
Ejemplo n.º 12
0
    public static void Main()
    {
        Err.LogToConsole();
        int          ErcDate          = 0;
        bool         UseErcRobot      = false;                                  // подключаться ли к серверу под логином ErcRobot
        string       FileName         = CAbc.EMPTY;
        const string ROBOT_LOGIN      = "******";
        const string ROBOT_PWD        = "35162987";
        const string TASK_CODE        = "OpenGate";
        string       StatDir          = null;
        string       DataBase         = null;
        string       ServerName       = null;
        string       ScroogeDir       = null;
        string       SettingsDir      = null;
        string       ConnectionString = null;

        if (System.Console.BufferHeight > 50)
        {
            System.Console.WindowHeight = 25;
            System.Console.BufferHeight = 25;
        }
        System.Console.Title           = "Загрузка в `Скрудж` платежей из А-файлов ";
        System.Console.BackgroundColor = 0;
        System.Console.Clear();
        CCommon.Print("", "  Загрузка в `Скрудж` платежей из А-файлов. Версия 3.03 от 29.08.2019г.");
        if (CCommon.ParamCount() < 2)
        {
            CCommon.Print("  В строке запуска нужно указатьть один из режимов :");
            CCommon.Print("  /A   диалоговый режим, для загрузки файлов для универсального шлюза ;");
            CCommon.Print("  /С   проверка одного файла, имя которого задано далее в строке ;");
            CCommon.Print("  /D   `браковка` заготовок из файла, имя которого задано далее в строке ;");
            CCommon.Print("  /S   пакетный режим  , для загрузки файлов от САКР ( маска !A??_*.* ) ;");
            CCommon.Print("  /U   диалоговый режим, для загрузки файлов от ЕРЦ  ( кроме !A??_*.* ) ;");
            CCommon.Print("  /Z   диалоговый режим, для загрузки файлов зарплаты( маска !A*.Z??  ) .");
            CCommon.Print("", "  /R   дополнительная опция - подключаться под пользователем ErcRobot .");
            return;
        }
        if (CCommon.ParamCount() == 0)
        {
            return;
        }
        for (int i = 1; i < CCommon.ParamCount(); i++)
        {
            if (CAbc.ParamStr[i].Trim().ToUpper() == "/R")
            {
                UseErcRobot          = true;
                System.Console.Title = System.Console.Title + " * ";
            }
            else
            if (CAbc.ParamStr[i].Trim().Substring(0, 1) == "/")
            {
                WorkMode = CCommon.Upper(CAbc.ParamStr[i]).Trim();
            }
            else
            {
                FileName = CAbc.ParamStr[i].Trim();
            }
        }
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // Вычитываем настройки "Скрудж-2"
        ErcAFile       = new   CErcAFile();
        ErcEFile       = new   CErcEFile();
        Scrooge2Config = new   CScrooge2Config();
        if (!Scrooge2Config.IsValid)
        {
            CCommon.Print(Scrooge2Config.ErrInfo);
            return;
        }
        ScroogeDir  = (string)Scrooge2Config["Root"];
        SettingsDir = (string)Scrooge2Config["Common"];
        ServerName  = (string)Scrooge2Config["Server"];
        DataBase    = (string)Scrooge2Config["DataBase"];
        if (ScroogeDir == null)
        {
            CCommon.Print("  Не найдена переменная `Root` в настройках `Скрудж-2` ");
            return;
        }
        if (ServerName == null)
        {
            CCommon.Print("  Не найдена переменная `Server` в настройках `Скрудж-2` ");
            return;
        }
        if (DataBase == null)
        {
            CCommon.Print("  Не найдена переменная `Database` в настройках `Скрудж-2` ");
            return;
        }
        ScroogeDir = ScroogeDir.Trim();
        if (SettingsDir != null)
        {
            SettingsDir = ScroogeDir + "\\" + SettingsDir;
        }
        ServerName = ServerName.Trim();
        DataBase   = DataBase.Trim();
        CCommon.Print("  Беру настройки `Скрудж-2` здесь :  " + ScroogeDir);
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // Подключаемся к базе данных
        ConnectionString = "Server=" + ServerName
                           + ";Database=" + DataBase;
        if (UseErcRobot)
        {
            ConnectionString += ";UID=" + ROBOT_LOGIN + ";PWD=" + ROBOT_PWD + ";";
        }
        else
        {
            ConnectionString += ";Integrated Security=TRUE;";
        }
        Connection = new   CConnection(ConnectionString);
        if (Connection.IsOpen())
        {
            /* CCommon.Print("  Сервер        :  " + ServerName ) */;
        }
        else
        {
            CCommon.Print("  Ошибка подключения к серверу !");
            return;
        }
        Command = new   CCommand(Connection);
        if (Command.IsOpen())
        {
            /* CCommon.Print("  База данных   :  " + DataBase ) */;
        }
        else
        {
            CCommon.Print("  Ошибка подключения к базе данных !");
            return;
        }
        System.Console.Title = System.Console.Title + " | " + ServerName + "." + DataBase;
        // - - - - - - - - - - - - - - - - -
        // считываем настройки шлюза в ЕРЦ
        AppSettings = new   CAppSettings(Connection);
        ErcDate     = ( int )CCommon.IsNull(Command.GetScalar(" exec  dbo.pMega_OpenGate_Days;7 "), (int)0);
        if (ErcDate < 1)
        {
            CCommon.Print(" Ошибка определения даты текущего рабочего дня. ");
            return;
        }
        switch (WorkMode)
        {
        case    WorkModes.CHECK:
        {
            SeanceNum = 1;
            ErcConfig = new   COpenwayConfig();
            ErcConfig.Open(ErcDate);
            InputDir = (string)ErcConfig["InputDir"];
            break;
        }

        case    WorkModes.DISABLE:
        {
            SeanceNum = 1;
            ErcConfig = new   COpenwayConfig();
            ErcConfig.Open(ErcDate);
            InputDir = (string)ErcConfig["InputDir"];
            break;
        }

        case    WorkModes.SALARY:
        {
            SeanceNum = ( int )CCommon.IsNull(Command.GetScalar(" exec dbo.pMega_OpenGate_Days;4  @TaskCode='ErcGate',@ParamCode='NumSeance' "), (int)0);
            ErcConfig = new   CSalaryConfig();
            ErcConfig.Open(ErcDate);
            InputDir = (string)ErcConfig["SalaryDir"] + "\\IN\\";
            break;
        }

        case    WorkModes.OPENGATE:
        {
            SeanceNum = ( int )CCommon.IsNull(Command.GetScalar(" exec dbo.pMega_OpenGate_Days;4  @TaskCode='OpenGate',@ParamCode='NumSeance' "), (int)0);
            ErcConfig = new   COpenwayConfig();
            ErcConfig.Open(ErcDate);
            InputDir = (string)ErcConfig["InputDir"];
            break;
        }

        case    WorkModes.SAKR:
        case    WorkModes.ERC:
        {
            SeanceNum = ( int )CCommon.IsNull(Command.GetScalar(" exec dbo.pMega_OpenGate_Days;4  @TaskCode='ErcGate',@ParamCode='NumSeance' "), (int)0);
            ErcConfig = new   CErcConfig();
            ErcConfig.Open(ErcDate);
            InputDir = (string)ErcConfig["InputDir"];
            break;
        }

        default:
        {
            CCommon.Print("", "Ошибка в строке параметров программы ! ");
            return;

            break;
        }
        }
        if (!ErcConfig.IsValid())
        {
            CCommon.Print("  Ошибка чтения настроек программы из " + ErcConfig.Config_FileName());
            System.Console.WriteLine(ErcConfig.ErrInfo());
            return;
        }
        if (SeanceNum < 1)
        {
            CCommon.Print(" Ошибка определения номера сеанса ");
            return;
        }
        TodayDir = (string)ErcConfig.TodayDir();
        TmpDir   = (string)ErcConfig.TmpDir();
        StatDir  = (string)ErcConfig.StatDir();
        if ((TodayDir == null) || (InputDir == null))
        {
            CCommon.Print("  Ошибка чтения настроек программы из " + ErcConfig.Config_FileName());
            return;
        }
        TodayDir = TodayDir.Trim();
        InputDir = InputDir.Trim();
        if ((TodayDir == "") || (InputDir == ""))
        {
            CCommon.Print("  Ошибка чтения настроек программы из " + ErcConfig.Config_FileName());
            return;
        }
        if (!CCommon.DirExists(StatDir))
        {
            CCommon.MkDir(StatDir);
        }
        if (!CCommon.SaveText(StatDir + "\\" + "test.dat", "test.dat", CAbc.CHARSET_DOS))
        {
            CCommon.Print(" Ошибка записи в каталог " + StatDir);
            return;
        }
        CCommon.DeleteFile(StatDir + "\\" + "test.dat");
        LogFileName = ErcConfig.LogDir() + "\\"
                      + ((WorkMode == WorkModes.CHECK)
                                        ?       "W" + CCommon.Hour(CCommon.Now()).ToString("00") + CCommon.Minute(CCommon.Now()).ToString("00") + CCommon.Second(CCommon.Now()).ToString("00")
                                        :       "SEANS" + SeanceNum.ToString("000")
                         )
                      + ".TXT";
        CCommon.Print("  Беру настройки шлюза здесь :  " + ErcConfig.Config_FileName());
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // основной блог работы программы
        switch (WorkMode)
        {
        // - - - - - - - - - - - - - - - - - - - - - - -
        // Загружаем сторонние платежи
        case    WorkModes.SAKR:
        {
            foreach (string FName in CCommon.GetFileList(InputDir + "!A??_*.*"))
            {
                if (FName != null)
                {
                    if (FileName.Trim() != "")
                    {
                        ProcessAFile(Command, FileName, false);
                    }
                }
            }
            // Загружаем допреквизиты
            foreach (string FName in CCommon.GetFileList(InputDir + "!E*.*"))
            {
                if (FName != null)
                {
                    if (FName.Trim() != "")
                    {
                        if (ErcEFile.Load(Command, FileName))
                        {
                            CCommon.MoveFile(FileName, TodayDir + CAbc.SLASH + CCommon.GetFileName(FileName));
                        }
                    }
                }
            }
            // Завершающие действия
            CCommon.Print("  Пересчет промежуточных данных ...");
            Command.Execute("exec dbo.pMega_OpenGate_PalvisBind ");
            break;
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // Загружаем коммунальные платежи из файла, который выбирает пользователь
        case    WorkModes.ERC:
        {
            FileName = SelectFileName(InputDir + "!A*.*");
            while (FileName != "")
            {
                if (ErcAFile.UserAccepted(FileName))
                {
                    ProcessAFile(Command, FileName, true);
                }
                FileName = SelectFileName(InputDir + "!A*.*");
            }
            break;
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // Загружаем зарплатные платежи из файла, который выбирает пользователь
        case    WorkModes.SALARY:
        {
            FileName = SelectFileName(InputDir + "!A*.Z*");
            while (FileName != "")
            {
                if (ErcAFile.UserAccepted(FileName))
                {
                    ProcessAFile(Command, FileName, true);
                }
                FileName = SelectFileName(InputDir + "!A*.*");
            }
            break;
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // Загружаем платежи по универсальному шлюзу из файла, который выбирает пользователь
        case    WorkModes.OPENGATE:
        {
            if (FileName != "")
            {
                if (CCommon.FileExists(FileName))
                {
                    if (ErcAFile.UserAccepted(FileName))
                    {
                        ProcessAFile(Command, FileName, true);
                    }
                }
            }
            else
            {
                FileName = SelectFileNameGUI(SettingsDir, InputDir);
                if (FileName != "")
                {
                    if (ErcAFile.UserAccepted(FileName))
                    {
                        ProcessAFile(Command, FileName, true);
                        if (CCommon.FileExists(FileName))
                        {
                            CCommon.DeleteFile(FileName);
                        }
                    }
                }
            }
            break;
        }

        // - - - - - - - - - - - -
        // Только проверка файла
        case    WorkModes.CHECK:
        {
            string AboutError = "";
            if (FileName.Length > 0)
            {
                if (!CCommon.FileExists(FileName))
                {
                    CCommon.Print("", "Не найден файл " + FileName);
                    FileName = "";
                }
            }
            if (FileName != "")
            {
                Err.LogToConsole();
                AboutError = ErcAFile.Check(Command, FileName);
                CConsole.Clear();
                if (AboutError == "")
                {
                    CCommon.Print("", " " + ErcAFile.String_Count.ToString() + " строк на общую суммму "
                                  + CCommon.StrN(ErcAFile.Total_Credit, 11).Replace(",", "."), ""
                                  , " Ошибок не найдено.");
                }
                else
                {
                    CCommon.AppendText(LogFileName, CCommon.Now() + "   " + CCommon.Upper(CCommon.GetUserName()) + "  проверяет файл "
                                       + CCommon.GetFileName(FileName) + CAbc.CRLF + CAbc.CRLF + AboutError + CAbc.CRLF, CAbc.CHARSET_WINDOWS);
                    CCommon.Print(AboutError);
                }
            }
            else
            {
                FileName = SelectFileNameGUI(SettingsDir, InputDir);
                if (FileName != "")
                {
                    if (ErcAFile.UserAccepted(FileName))
                    {
                        AboutError = ErcAFile.Check(Command, FileName);
                        CConsole.Clear();
                        if (AboutError == "")
                        {
                            CCommon.Print("", " " + ErcAFile.String_Count.ToString() + " строк на общую суммму "
                                          + CCommon.StrN(ErcAFile.Total_Credit, 11).Replace(",", "."), ""
                                          , " Ошибок не найдено.");
                        }
                        else
                        {
                            CCommon.AppendText(LogFileName, CCommon.Now() + "   " + CCommon.Upper(CCommon.GetUserName()) + "  проверяет файл "
                                               + CCommon.GetFileName(FileName) + CAbc.CRLF + CAbc.CRLF + AboutError + CAbc.CRLF, CAbc.CHARSET_WINDOWS);
                            CCommon.Print(AboutError);
                        }
                    }
                    if (CCommon.FileExists(FileName))
                    {
                        CCommon.DeleteFile(FileName);
                    }
                }
            }
            break;
        }

        // - - - - - - - - - - - - - - - - - -
        // `запретить` заготовки из А-файла
        case    WorkModes.DISABLE:
        {
            CConsole.Clear();
            Err.LogToConsole();
            if (CCommon.ParamCount() > 2)
            {
                FileName = CAbc.ParamStr[2].Trim();
            }
            if (FileName == "")
            {
                CCommon.Print("", "Не задано имя файла !");
            }
            else
            {
                FileName = CCommon.GetFileName(FileName);
                if (Command.Execute("exec dbo.pMega_OpenGate_Disable @TaskCode='OpenGate',@FileName='" + FileName + "'"))
                {
                    CCommon.Print("", "заготовки из файла  " + FileName + "  запрещены .");
                }
                else
                {
                    CCommon.Print("", "Ошибка выполнения команды на сервере !");
                }
            }
            break;
        }
        }
        Command.Close();
        Connection.Close();
    }
Ejemplo n.º 13
0
    //  - - - - - - - - - - - - - - - - - - - - - - - - - -
    static void    ProcessAFile(CCommand Command, string FileName, bool IsCheckNeeded)
    {
        string ShortFileName = null;
        string BranchCode    = null;
        string TmpFileName   = null;
        string AboutError    = null;
        bool   Result        = false;
        byte   SavedColor    = CConsole.BoxColor;

        if (FileName == null)
        {
            return;
        }
        if (FileName.Trim() == "")
        {
            return;
        }
        ShortFileName = CCommon.GetFileName(FileName);
        CCommon.AppendText(LogFileName, CCommon.Now() + "   " + CCommon.Upper(CCommon.GetUserName()) + "  загружает файл " + ShortFileName + CAbc.CRLF, CAbc.CHARSET_WINDOWS);

        if (ShortFileName.IndexOf("_") < 0)
        {
            BranchCode = "";
        }
        else
        {
            BranchCode = ShortFileName.Substring(2, 2);
        }

        TmpFileName = TodayDir + CAbc.SLASH + ShortFileName;
        if (!CCommon.FileExists(TmpFileName))
        {
            CCommon.CopyFile(FileName, TmpFileName);
        }
        if (!CCommon.FileExists(TmpFileName))
        {
            return;
        }
        TmpFileName = TmpDir + CAbc.SLASH
                      + CCommon.Right("0" + CCommon.Hour(CCommon.Clock()).ToString(), 2)
                      + CCommon.Right("0" + CCommon.Minute(CCommon.Clock()).ToString(), 2)
                      + CCommon.Right("0" + CCommon.Second(CCommon.Clock()).ToString(), 2);
        if (!CCommon.DirExists(TmpFileName))
        {
            CCommon.MkDir(TmpFileName);
        }
        TmpFileName = TmpFileName + CAbc.SLASH + ShortFileName;
        if (CCommon.FileExists(TmpFileName))
        {
            CCommon.DeleteFile(TmpFileName);
        }
        if (CCommon.FileExists(TmpFileName))
        {
            CConsole.GetBoxChoice("", "Ошибка при удалении файла ", TmpFileName, "", " Для выхода нажмите Esc.");
            return;
        }
        CCommon.CopyFile(FileName, TmpFileName);
        if (!CCommon.FileExists(TmpFileName))
        {
            CConsole.GetBoxChoice("", "Ошибка при создании файла ", TmpFileName, "", " Для выхода нажмите Esc.");
            return;
        }
        Err.LogTo(LogFileName);
        CCommon.DeleteFile(FileName);
        CConsole.BoxColor = SavedColor;
        if (IsCheckNeeded)
        {
            AboutError = ErcAFile.Check(Command, TmpFileName);
            CConsole.Clear();
            if (AboutError != null)
            {
                if (AboutError.Trim() != "")
                {
                    CCommon.AppendText(LogFileName, AboutError + CAbc.CRLF, CAbc.CHARSET_WINDOWS);
                    CCommon.Print(AboutError);
                    CConsole.BoxColor = CConsole.RED * 16 + CConsole.WHITE;
                    if (!CConsole.GetBoxChoice("Внимание ! При проверке " + ShortFileName + " обнаружены ошибки !"
                                               , "", "Для отмены загрузки нажмите Esc , для продолжения - Enter"
                                               )
                        )
                    {
                        CCommon.CopyFile(TmpFileName, FileName);
                        CCommon.Print(AboutError);
                        CConsole.BoxColor = SavedColor;
                        return;
                    }
                }
            }
        }
        CConsole.BoxColor = SavedColor;
        if (WorkMode == WorkModes.OPENGATE)
        {
            Result = ErcAFile.Load(Command, TmpFileName, BranchCode, "OpenGate");
            if (Result)
            {
                // добавление в PayRoll информации о файле
                CConsole.BoxColor = SavedColor;
                CConsole.Clear();
                CConsole.ShowBox("", " Подождите...", "");
                Command.Execute(" exec pMega_OpenGate_PayRoll;2 @FileName='" + CCommon.GetFileName(TmpFileName) + "'");
            }
        }
        else
        {
            Result = ErcAFile.Load(Command, TmpFileName, BranchCode, "ErcGate");
        }
        if (Result)
        {
            CCommon.AppendText(LogFileName, CCommon.Now() + "   загрузка закончена." + CAbc.CRLF, CAbc.CHARSET_WINDOWS);
        }
        else
        {
            CCommon.CopyFile(TmpFileName, FileName);
            CConsole.BoxColor = CConsole.RED * 16 + CConsole.WHITE;
            CConsole.GetBoxChoice("", "  При загрузке " + ShortFileName + " возникли ошибки !", "");
        }
        CConsole.BoxColor = SavedColor;
        CConsole.Clear();
        Err.LogToConsole();
    }
Ejemplo n.º 14
0
    public static void Main()
    {
        const bool DEBUG            = false;
        int        WorkMode         = 0;                                 // 1 = выгружать B ; 2 = выгружать V
        const int  WORK_MODE_B      = 1;                                 // для WorkMode : 1 = выгружать B
        const int  WORK_MODE_V      = 2;                                 // для WorkMode : 2 = выгружать V
        int        DayStatus        = 0;                                 // &1 = стоп по B ; &2 = стоп по V
        int        ErcDate          = CCommon.Today();
        string     TmpDir           = null;
        string     StatDir          = null;
        string     TodayDir         = null;
        string     OutputDir        = null;
        string     DataBase         = null;
        string     ServerName       = null;
        string     ScroogeDir       = null;
        string     LogFileName      = null;
        string     SimpleFileName   = null;
        string     ConfigFileName   = null;
        string     ConnectionString = null;

        Err.LogToConsole();
        CCommon.Print("", " Создание файлов для ЕРЦ. Версия 3.02 от 23.05.2019г.");

        if (!DEBUG)
        {
            if (CCommon.ParamCount() < 2)
            {
                CCommon.Print(" Режим работы программы (задаются в строке запуска программы):");
                CCommon.Print("        /E      -  выполнить выгрузку файлов для ЕРЦ .");
                CCommon.Print(" Примеры запуска программы  : ");
                CCommon.Print("        ErcExport  /E");
                CCommon.Print("        ErcExport  /E  2019/05/20");
                return;
            }
            if (CCommon.Upper(CAbc.ParamStr[1]).Trim() != "/E")
            {
                CCommon.Print(" Ошибка ! Неправильный режим работы  - " + CAbc.ParamStr[1]);
                return;
            }
            if (CCommon.ParamCount() > 2)
            {
                ErcDate = CCommon.GetDate(CAbc.ParamStr[2].Trim());
                if (ErcDate < 10000)
                {
                    CCommon.Print(" Ошибка ! Неправильная дата - " + CAbc.ParamStr[2]);
                    return;
                }
            }
        }
        else
        {
            CCommon.Print("--- DEBUG ---");
        }
        CCommon.Print(" Рабочая дата " + CCommon.StrD(ErcDate, 10, 10));

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        Scrooge2Config = new   CScrooge2Config();
        if (!Scrooge2Config.IsValid)
        {
            CCommon.Print(Scrooge2Config.ErrInfo);
            return;
        }

        ScroogeDir = (string)Scrooge2Config["Root"];
        ServerName = (string)Scrooge2Config["Server"];
        DataBase   = (string)Scrooge2Config["DataBase"];
        if (ScroogeDir == null)
        {
            CCommon.Print("  Не найдена переменная `Root` в настройках `Скрудж-2` ");
            return;
        }
        if (ServerName == null)
        {
            CCommon.Print("  Не найдена переменная `Server` в настройках `Скрудж-2` ");
            return;
        }
        if (DataBase == null)
        {
            CCommon.Print("  Не найдена переменная `Database` в настройках `Скрудж-2` ");
            return;
        }
        CCommon.Print("  Беру настройки `Скрудж-2` здесь :  " + ScroogeDir);

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        ConnectionString = "Server=" + ServerName
                           + ";Database=" + DataBase
                           + ";Integrated Security=TRUE;"
        ;
        Connection1 = new CConnection(ConnectionString);
        Connection2 = new CConnection(ConnectionString);

        if (Connection1.IsOpen())
        {
            CCommon.Print("  Сервер        :  " + ServerName);
            CCommon.Print("  База данных   :  " + DataBase + CAbc.CRLF);
        }
        else
        {
            CCommon.Print(CAbc.CRLF + "  Ошибка подключения к серверу !");
            return;
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        CCommand Command = new   CCommand(Connection1);

        DayStatus = ( int )CCommon.IsNull(Command.GetScalar(" exec dbo.pMega_OpenGate_Days;8 @TaskCode = 'ErcGate' , @DayDate = " + ErcDate.ToString()), (int)0);

        switch ((DayStatus & 3))
        {
        case  0: {                                      // разрешена отправка и B и V
            WorkMode = WORK_MODE_B;                     // отправлять B
            break;
        }

        case  1: {                                      // запрещена отправка B ; разрешена отправка V
            WorkMode = WORK_MODE_V;                     // отправлять V
            break;
        }

        case  2: {                                      // разрешена отправка B ; запрещена отправка V
            WorkMode = WORK_MODE_B;                     // отправлять B
            break;
        }

        case  3: {
            CCommon.Print(" На " + CCommon.StrD(ErcDate, 10, 10) + " отправка пачек B и V завершена (см. признак текущего дня).");
            Connection1.Close();
            Connection2.Close();
            return;

            break;
        }
        }

        SeanceNum = ( int )CCommon.IsNull(Command.GetScalar(" exec dbo.pMega_OpenGate_Days;4  @TaskCode = 'ErcGate' , @ParamCode = 'NumSeance'  , @DayDate = " + ErcDate.ToString()), (int)0);
        if (WorkMode == WORK_MODE_B)
        {
            BFileNum = ( int )CCommon.IsNull(Command.GetScalar(" exec dbo.pMega_OpenGate_Days;4  @TaskCode = 'ErcGate' , @ParamCode = 'NumOutFile' , @DayDate = " + ErcDate.ToString()), (int)0);
            CCommon.Print(" Выполняется формирование B-файлов ");
        }
        else
        {
            CCommon.Print(" Выполняется формирование V и W -файлов ");
        }

        Command.Close();
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        ConfigFileName = ScroogeDir + CAbc.SLASH + "EXE" + CAbc.SLASH + "GLOBAL.ERC";
        ErcConfig      = new CErcConfig();
        ErcConfig.Open(ErcDate);
        if (!ErcConfig.IsValid())
        {
            CCommon.Print("  Ошибка чтения настроек из файла " + ConfigFileName);
            System.Console.WriteLine(ErcConfig.ErrInfo());
            Connection1.Close();
            Connection2.Close();
            return;
        }
        TodayDir  = (string)ErcConfig.TodayDir();
        StatDir   = (string)ErcConfig.StatDir();
        TmpDir    = (string)ErcConfig.TmpDir();
        OutputDir = (string)ErcConfig["OutputDir"];
        if ((TodayDir == null) || (OutputDir == null))
        {
            CCommon.Print("  Ошибка чтения настроек из файла " + ConfigFileName);
            Connection1.Close();
            Connection2.Close();
            return;
        }
        TodayDir  = TodayDir.Trim();
        OutputDir = OutputDir.Trim();
        StatDir   = StatDir.Trim();
        if ((TodayDir == "") || (OutputDir == "") || (StatDir == ""))
        {
            CCommon.Print("  Ошибка чтения настроек из файла " + ConfigFileName);
            Connection1.Close();
            Connection2.Close();
            return;
        }
        if (!CCommon.DirExists(StatDir))
        {
            CCommon.MkDir(StatDir);
        }
        if (!CCommon.SaveText(StatDir + "\\" + "test.dat", "test.dat", CAbc.CHARSET_DOS))
        {
            CCommon.Print(" Ошибка записи в каталог " + StatDir);
            Connection1.Close();
            Connection2.Close();
            return;
        }
        CCommon.DeleteFile(StatDir + "\\" + "test.dat");
        CCommon.Print("  Беру настройки шлюза здесь :  " + ConfigFileName);

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        TmpDir = TmpDir + "\\" + SeanceNum.ToString("000000");
        CCommon.MkDir(TmpDir);
        if (!CCommon.SaveText(TmpDir + "\\" + "test.dat", "test.dat", CAbc.CHARSET_DOS))
        {
            CCommon.Print("  Ошибка записи в каталог " + TmpDir);
            Connection1.Close();
            Connection2.Close();
        }
        LogFileName = ErcConfig.LogDir() + "\\SE" + SeanceNum.ToString("000000") + ".TXT";
        if (!CCommon.AppendText(LogFileName, CCommon.Now() + " , " + CCommon.Upper(CCommon.GetUserName()) + CAbc.CRLF, CAbc.CHARSET_DOS))
        {
            CCommon.Print("  Ошибка записи в файл " + LogFileName);
            Connection1.Close();
            Connection2.Close();
        }

        Err.LogTo(LogFileName);

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        //	Отправка B
        if (WorkMode == WORK_MODE_B)
        {
            if (!WriteBFiles(ErcDate, TmpDir))
            {
                CCommon.Print("  Ошибка записи B-файлов!");
            }
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        //	Отправка V
        if (WorkMode == WORK_MODE_V)
        {
            WriteVFiles(ErcDate, TmpDir, 0);
            WriteVFiles(ErcDate, TmpDir, 1);
            Command = new   CCommand(Connection1);
            if (!Command.Execute(" exec dbo.pMega_OpenGate_Days;9  @TaskCode = 'ErcGate' , @DayDate = " + ErcDate.ToString()))
            {
                CCommon.Print("  Ошибка установки запрета на отправку V-файла!");
                CCommon.AppendText(LogFileName, "  Ошибка установки запрета на отправку V-файла!", CAbc.CHARSET_DOS);
                CCommon.AppendText(LogFileName, CAbc.CRLF, CAbc.CHARSET_DOS);
                Connection1.Close();
                Connection2.Close();
                return;
            }
            Command.Close();
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        foreach (string ResultFile in CCommon.GetFileList(TmpDir + "\\" + "!*.*"))
        {
            if (ResultFile != null)
            {
                SimpleFileName = CCommon.GetFileName(ResultFile);
                CCommon.CopyFile(ResultFile, TodayDir + "\\" + SimpleFileName);
                CCommon.CopyFile(ResultFile, OutputDir + "\\" + SimpleFileName);
                CCommon.AppendText(LogFileName, "Записываю файл " + SimpleFileName, CAbc.CHARSET_DOS);
                CCommon.Print("  Записываю файл " + SimpleFileName);
            }
        }
        CCommon.AppendText(LogFileName, CAbc.CRLF, CAbc.CHARSET_DOS);
        Connection1.Close();
        Connection2.Close();
    }
Ejemplo n.º 15
0
    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    //	Запуск  списка регламентных процедур на Sql-сервере
    static bool    StartSqlRoutine(string CmdText)
    {
        CConnection Connection2;
        bool        Result = true;

        if (CmdText == null)
        {
            return(false);
        }
        if (CmdText.Trim() == "")
        {
            return(false);
        }
        CArray CommandList = new   CArray();
        CArray NamesList   = new   CArray();

        CConsole.ShowBox("", "Выполнение команды на сервере", "");
        Connection = new   CConnection(ConnectionString);
        RecordSet  = new   CRecordSet(Connection);
        if (RecordSet.Open(CmdText))
        {
            while (RecordSet.Read())
            {
                NamesList.Add(RecordSet["Name"]);
                CommandList.Add(RecordSet["Command"]);
            }
        }
        else
        {
            Result = false;
        }
        CConsole.Clear();
        RecordSet.Close();
        string Cmd       = CAbc.EMPTY
        , Msg            = CAbc.EMPTY
        , Results        = CAbc.EMPTY;
        CCommand Command = new   CCommand(Connection);

        for (int I = 0; I < NamesList.Count; I++)
        {
            CCommon.Print(NamesList[I] + " - выполняется.");
            CConsole.ShowBox("", "Выполнение команды на сервере", "");
            Cmd     = DateSubstitution((string)CommandList[I]);
            CmdText = " exec  dbo.Mega_Common_WriteToLoginfo "
                      + " @TaskCode='Mega_Day_Routine-" + Mode.ToString().Trim() + "'"
                      + ",@Info='start : " + Cmd + "'";
            Command.Execute(CmdText);
            Connection2       = new   CConnection(ConnectionString);
            RecordSet         = new   CRecordSet(Connection2);
            RecordSet.Timeout = 599;
            if (RecordSet.Open(Cmd))
            {
                Msg = (string)NamesList[I];
                int Count = 0;
                if (RecordSet.Read())
                {
                    do
                    {
                        Count++;
                    }while   (RecordSet.Read());
                }
                Msg = NamesList[I] + " - OK."
                      + ((Count > 0) ? " ( " + Count.ToString() + " row(s) affected )" : "");
            }
            else
            {
                Result = false;
                Msg    = NamesList[I] + " - Ошибка !";
            }
            RecordSet.Close();
            Connection2.Close();
            CmdText = " exec  dbo.Mega_Common_WriteToLoginfo "
                      + " @TaskCode='Mega_Day_Routine-" + Mode.ToString().Trim() + "'"
                      + ",@Info='stop  : " + Cmd + "'";
            Command.Execute(CmdText);
            CmdText = " exec  dbo.Mega_Common_WriteToLoginfo "
                      + " @TaskCode='Mega_Day_Routine-" + Mode.ToString().Trim() + "'"
                      + ",@Info='" + Msg.Replace("'", "`") + "'";
            Command.Execute(CmdText);
            Err.Print(CAbc.TAB + CAbc.TAB + Msg + CAbc.CRLF);
            CConsole.Clear();
            Results += Msg + CAbc.CRLF;
            CCommon.Write(Results);
        }
        Connection.Close();
        CCommon.Print(CAbc.EMPTY, CAbc.EMPTY, "Готово. Для продолжения нажмите Enter.");
        CConsole.ClearKeyboard();
        CConsole.Flash();
        CConsole.ReadChar();
        return(Result);
    }
Ejemplo n.º 16
0
    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    public static void    Main()
    {
        const bool DEBUG                = false;
        CParam     Param                = new   CParam();
        int        Choice               = 0;
        bool       Result               = false;
        byte       SavedColor           = 7;
        string     OutputDir            = CAbc.EMPTY;
        string     ScroogeDir           = CAbc.EMPTY;
        string     ServerName           = CAbc.EMPTY;
        string     DataBase             = CAbc.EMPTY;
        string     LogFileName          = CAbc.EMPTY;
        string     UnsolverBillsCmdText = CAbc.EMPTY;
        int        UnsolvedBillsExists  = 0;

        string[] Titles       = { "ОТКРЫТИЕ ДНЯ", "ЗАКРЫТИЕ ДНЯ" };
        string[] LogFileNames = { "dayopen.log", "dayclose.log" };
        string   NOW_STR      = CCommon.StrD(CCommon.Today(), 10, 10).Substring(6)
                                + CCommon.StrD(CCommon.Today(), 10, 10).Substring(2, 4)
                                + CCommon.StrD(CCommon.Today(), 10, 10).Substring(0, 2);

        Err.LogToConsole();
        CConsole.Clear();
        CCommon.Print(" Оболочка открытия и закрытия дня в `Скрудже`. Версия 3.13 от 02.10.2018г.", "");
        if (DEBUG)
        {
            Mode = 1;
        }
        else
        if (CCommon.IsEmpty(Param["Mode"]))
        {
            CCommon.Print("Не указан режим работы программы !");
        }
        else
        {
            switch (Param["Mode"].ToUpper())
            {
            case    "OPEN": {
                Mode = 1;
                break;
            }

            case    "CLOSE": {
                Mode = 2;
                break;
            }

            default: {
                CCommon.Print("Неверно указан режим работы программы !");
                break;
            }
            }
        }
        if ((Mode != 1) && (Mode != 2))
        {
            return;
        }
        if ((Mode == 2) && (!CCommon.DirExists("Z:\\")))
        {
            SavedColor        = CConsole.BoxColor;
            CConsole.BoxColor = CConsole.RED * 16 + CConsole.WHITE;
            CConsole.ShowBox("", "Не подключен Z:\\", "");
            CConsole.ClearKeyboard();
            CConsole.ReadChar();
            CConsole.BoxColor = SavedColor;
            CConsole.Clear();
            CConsole.ShowCursor();
        }
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        //	Запрос пользователю на ввод даты дня, который открывается или закрывается
        while (DayDate == 0)
        {
            switch (Mode)
            {
            case 1: {
                CCommon.Write("Какую дату открываем ? ( " + NOW_STR.Replace("/", ".") + " ) ");
                break;
            }

            default: {
                CCommon.Write("Какую дату закрываем ? ( " + NOW_STR.Replace("/", ".") + " ) ");
                break;
            }
            }
            Answer = CCommon.Input().Trim();
            if (Answer == "")
            {
                DayDate = CCommon.Today();
            }
            else
            {
                DayDate = CCommon.GetDate(Answer);
            }
        }
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        Scrooge2Config = new   CScrooge2Config();
        if (!Scrooge2Config.IsValid)
        {
            CCommon.Print(Scrooge2Config.ErrInfo);
            return;
        }
        ScroogeDir = (string)Scrooge2Config["Root"];
        OutputDir  = (string)Scrooge2Config["Output"];
        ServerName = (string)Scrooge2Config["Server"];
        DataBase   = (string)Scrooge2Config["DataBase"];
        if (ScroogeDir == null)
        {
            CCommon.Print("  Не найдена переменная `Root` в настройках `Скрудж-2` ");
            return;
        }
        if (ServerName == null)
        {
            CCommon.Print("  Не найдена переменная `Server` в настройках `Скрудж-2` ");
            return;
        }
        if (DataBase == null)
        {
            CCommon.Print("  Не найдена переменная `Database` в настройках `Скрудж-2` ");
            return;
        }
        CCommon.Print(" Беру настройки `Скрудж-2` здесь :  " + ScroogeDir);
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        ConnectionString = "Server=" + ServerName
                           + ";Database=" + DataBase
                           + ";Integrated Security=TRUE;";
        Connection = new CConnection(ConnectionString);
        if (Connection.IsOpen())
        {
            CCommon.Print(" Сервер " + ServerName);
            CCommon.Print(" База   " + DataBase + CAbc.CRLF);
        }
        else
        {
            CCommon.Print(CAbc.CRLF + "  Ошибка подключения к серверу !");
            return;
        }
        System.Console.Title = "  " + Titles[Mode - 1] + "             |   " + ServerName + "." + DataBase;
        Command = new   CCommand(Connection);
        int    IsFullAccess   = ( int )CCommon.IsNull(Command.GetScalar(" select  dbo.Fn_IsFullAccess( DEFAULT ) "), (int)0);
        string InfNBU_OutPath = ( string )CCommon.IsNull(Command.GetScalar(" exec dbo.Mega_Day_Open;5  @Mode=2 ; "), (string)CAbc.EMPTY);

        if (Mode == 2)
        {
            // Записываю в историю логин пользователя, который закрывает день
            Command.Execute(" exec  dbo.Mega_Day_Close;12  @DayDate = " + DayDate.ToString() + " , @UserCode = '" + UserCode + "' ");
            // Проверка : имеются ли непроведенные документы ?
            UnsolverBillsCmdText = " If Exists ( select 1 from dbo.Mega_SV_WaitingBills with (NoLock) where  (DayDate=" + DayDate.ToString() + " )  and ((PermitFlag & 255 )!=255) and ((ProcessFlag & 3)!=3) ) select Convert(Integer,1) else select Convert(Integer,0) ";
            UnsolvedBillsExists  = ( int )CCommon.IsNull(Command.GetScalar(UnsolverBillsCmdText), (int)0);
        }
        Command.Close();
        Connection.Close();
        if (IsFullAccess < 1)
        {
            CCommon.Print(CAbc.CRLF + "  Для работы программы пользователю необходим полный доступ в Скрудже !");
            return;
        }
        InfNBU_OutPath = InfNBU_OutPath.Trim();
        if (InfNBU_OutPath.Length == 0)
        {
            Err.Print(CCommon.Now().ToString() + "Ошибка определения выходного каталога для ОДБ." + CAbc.CRLF + CAbc.CRLF);
        }
        if (UnsolvedBillsExists == 1)
        {
            SavedColor        = CConsole.BoxColor;
            CConsole.BoxColor = CConsole.RED * 16 + CConsole.WHITE;
            CConsole.ShowBox("", "Имеются непpоведенные документы", "", "  Пpоведите их или удалите !", "");
            CConsole.ClearKeyboard();
            CConsole.ReadChar();
            CConsole.BoxColor = SavedColor;
            CConsole.Clear();
            CConsole.ShowCursor();
        }
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        if (OutputDir != null)
        {
            OutputDir = ScroogeDir + "\\" + OutputDir.Trim();
            if (!CCommon.DirExists(OutputDir))
            {
                CCommon.MkDir(OutputDir);
            }
            if (CCommon.DirExists(OutputDir))
            {
                OutputDir += "\\" + CCommon.StrD(DayDate, 8, 8).Replace("/", "").Replace(".", "");
                if (!CCommon.DirExists(OutputDir))
                {
                    CCommon.MkDir(OutputDir);
                }
                if (!CCommon.DirExists(OutputDir))
                {
                    OutputDir = ScroogeDir + "\\";
                }
            }
            LogFileName = OutputDir + "\\" + LogFileNames[Mode - 1];
        }
        else
        {
            LogFileName = ScroogeDir + "\\" + LogFileNames[Mode - 1];
        }
        Err.LogTo(LogFileName);
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        //	Основной цикл программы
        do
        {
            System.Console.Title = "  " + Titles[Mode - 1] + "  " + CCommon.StrD(DayDate, 8, 8) + "        |   " + ServerName + "." + DataBase;
            string[] FilesForMEDOC = CCommon.GetFileList(InfNBU_OutPath + "\\@*.*");
            if (FilesForMEDOC != null)
            {
                if (FilesForMEDOC.Length > 0)
                {
                    CConsole.GetBoxChoice(
                        ""
                        , "В каталоге " + InfNBU_OutPath
                        , "Найдены файлы для налоговой  @*.*"
                        , "Не забудьте их отправить!"
                        , ""
                        );
                }
            }
            if (!LoadHistory(Mode))
            {
                Err.Print(CCommon.Now().ToString() + "Ошибка получения с сервера истории работы программы !");
            }
            Choice = CConsole.GetMenuChoice(MenuNames);
            if (Choice > 0)
            {
                Err.Print(CCommon.Now().ToString() + "\t< " + MenuNames[Choice - 1] + "   ( " + UserCode + " ) " + CAbc.CRLF);
                if (!SaveHistory(Mode, Choice))
                {
                    Err.Print("Ошибка сохранения на сервере истории работы программы !");
                }
                switch (MenuKinds[Choice - 1].Trim().ToUpper())
                {
                case    "EXE.COPY": {
                    Result = StartExeCopy(
                        MacroSubstitution(MenuCommands[Choice - 1])
                        , MacroSubstitution(
                            DateSubstitution(
                                MenuParams[Choice - 1]
                                )
                            )
                        );
                    break;
                }

                case    "SQL.CMD": {
                    Result = StartSqlCmd(
                        DateSubstitution(
                            MenuCommands[Choice - 1]
                            )
                        );
                    break;
                }

                case    "SQL.RS": {
                    Result = StartSqlRS(
                        DateSubstitution(
                            MenuCommands[Choice - 1]
                            )
                        );
                    break;
                }

                case    "SQL.ROUTINE": {
                    Result = StartSqlRoutine(
                        DateSubstitution(
                            MenuCommands[Choice - 1]
                            )
                        );
                    break;
                }

                case    "EXC": {
                    Result = StartExc(ScroogeDir
                                      , MacroSubstitution(
                                          DateSubstitution(
                                              MenuCommands[Choice - 1]
                                              )
                                          )
                                      );
                    break;
                }

                case    "URL.IE": {
                    Result = StartUrl(
                        DateSubstitution(
                            MenuCommands[Choice - 1]
                            )
                        );
                    break;
                }

                default: {
                    break;
                }
                }
                Err.Print(CCommon.Now().ToString() + "\t " + MenuNames[Choice - 1] + "   ( " + Result.ToString() + " ) > " + CAbc.CRLF);
            }
        } while (Choice != 0);
    }