예제 #1
0
	}//FOLD01

	//  ---------------------------------------------------------------
	//  Получить имя файла с помощью графической панели открытия файла
	static string SelectFileNameGUI( string SettingsPath ) {//fold01
		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 ) )
					Result		=	CCommon.LoadText(  SettingsFileName , CAbc.CHARSET_WINDOWS );
				if	( Result == null )
				        Result	=	CAbc.EMPTY;
			}
		Result	=	Result.Trim();
		Result	=	__.OpenFileBox(
					"Выберите файл для обработки"
				,	Result
				,	"ведомости пенс.фонда|0*.0*"
			);
		if	( Result == null )
			return	CAbc.EMPTY;
		Result		=	Result.Trim();
                if	( __.IsEmpty( Result ) )
			return	Result;
		if	( SettingsFileName != null )
			CCommon.SaveText( SettingsFileName , __.GetDirName( Result ) , CAbc.CHARSET_WINDOWS ) ;
		return	Result;
	}//FOLD01
예제 #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);
    }
    }    //FOLD00

    //  -------------------------------------------------------------
    //  Получить имя файла с помощью графической панели открытия файла
    static string SelectFileNameGUI(string SettingsPath)        //fold00
    {
        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))
                {
                    Result = CCommon.LoadText(SettingsFileName, CAbc.CHARSET_WINDOWS);
                }
                if (Result == null)
                {
                    Result = CAbc.EMPTY;
                }
            }
        }
        Result = Result.Trim();
        Result = __.OpenFileBox(
            "Укажите файл для обработки"
            , Result
            , "з/п ведомости (*.dif,*.dbf)|*.d?f"
            );
        if (Result == null)
        {
            return(CAbc.EMPTY);
        }
        Result = Result.Trim();
        if (__.IsEmpty(Result))
        {
            return(Result);
        }
        if (SettingsFileName != null)
        {
            CCommon.SaveText(SettingsFileName, __.GetDirName(Result), CAbc.CHARSET_WINDOWS);
        }
        return(Result);
    }    //FOLD00
예제 #4
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();
    }
예제 #5
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();
    }
예제 #6
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();
    }