Esempio n. 1
0
 private void reloadContractorsListWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     using (TenderContext tc = new TenderContext())
     {
         e.Result = tc.Contractors.OrderBy(p => p.ShortName).ToList();
     }
 }
Esempio n. 2
0
        private void deleteContractorButton_Click(object sender, EventArgs e)
        {
            Contractor selectedContractor = contractorsTable.SelectedRows[0].DataBoundItem as Contractor;

            if (NotificationHelper.ShowYesNoQuestion(string.Format("Ви впевнені, що хочете видалити інформацію про \"{0}\"?", selectedContractor.ShortName)))
            {
                using (TenderContext tc = new TenderContext())
                {
                    bool entityHasReferences = tc.Contracts.Where(p => p.ContractorId == selectedContractor.Id).Any();
                    if (entityHasReferences)
                    {
                        NotificationHelper.ShowError(string.Format("Видалення інформації про контрагента \"{0}\" неможливе, оскільки під нього є зареєстровані договори!", selectedContractor.ShortName));
                        return;
                    }
                    else
                    {
                        tc.Contractors.Attach(selectedContractor);
                        tc.Contractors.Remove(selectedContractor);
                        tc.SaveChanges();

                        NotificationHelper.ShowInfo("Контрагент успішно видалений!");
                        if (!reloadContractorsListWorker.IsBusy)
                        {
                            ToggleLoadAnimation();
                            reloadContractorsListWorker.RunWorkerAsync();
                            wasDbUpdated = true;
                        }
                    }
                }
            }
        }
Esempio n. 3
0
        // Обновление списка связаных с сущностью файлов
        public static void UpdateRelatedFilesOfEntity(TenderContext tc,
                                                      ICollection <UploadedFile> entityFilesCollection,
                                                      ICollection <UploadedFile> filesList,
                                                      ICollection <UploadedFile> deletingFilesList)
        {
            entityFilesCollection.Clear();
            tc.SaveChanges();
            foreach (var file in filesList)
            {
                if (file.Id > 0)
                {
                    tc.UploadedFiles.Attach(file);
                    tc.Entry <UploadedFile>(file).State = System.Data.Entity.EntityState.Modified;
                }
                entityFilesCollection.Add(file);
                FileManager.UploadFile(file);
            }

            foreach (var file in deletingFilesList)
            {
                if (file.Id > 0)
                {
                    tc.UploadedFiles.Attach(file);
                    tc.UploadedFiles.Remove(file);
                }
                try
                {
                    File.Delete(Path.Combine(UploadFilesDir, file.PhisicalName));
                }
                catch (Exception ex) { }
            }

            tc.SaveChanges();
        }
Esempio n. 4
0
        public SetYearPlanReportFilter()
        {
            filteDataWasSelected = false;
            InitializeComponent();

            using (TenderContext tc = new TenderContext())
            {
                string          allString = "- ВСІ -";
                List <Estimate> estList   = tc.Estimates.ToList();
                estList.Insert(0, new Estimate {
                    Id = -1, Name = allString
                });
                comboBox1.DataSource    = estList;
                comboBox1.DisplayMember = "Name";
                comboBox1.ValueMember   = "Id";

                List <KekvCode> kekvList = tc.KekvCodes.OrderBy(p => p.Code).ToList();
                kekvList.Insert(0, new KekvCode {
                    Id = -1, Code = allString
                });
                comboBox2.DataSource    = kekvList;
                comboBox2.DisplayMember = "Code";
                comboBox2.ValueMember   = "Id";
            }
        }
        private void recordsLoader_DoWork(object sender, DoWorkEventArgs e)
        {
            using (TenderContext tc = new TenderContext())
            {
                FilterArgument selectedEstimate = e.Argument as FilterArgument;

                var result = (from rec in tc.TenderPlanRecords.ToList()
                              where ((rec.EstimateId == selectedEstimate.Estimate.Id) && !rec.IsTenderComplete)
                              orderby rec.Dk.Code ascending
                              select new TPEntry
                {
                    Kekv = (selectedEstimate.IsNewSystem) ? rec.PrimaryKekv : rec.SecondaryKekv,
                    Dk = rec.Dk,
                    PlannedMoney = rec.PlannedSum,
                    MoneyRemain = rec.AvailableForContractsMoney,
                    Commentary = rec.CodeRepeatReason,
                    Record = rec
                } into s1
                              where s1.MoneyRemain > 0
                              select s1);

                if (selectedEstimate.Kekv.Id < 0)
                {
                    recordsList = new BindingList <TPEntry>(result.ToList());
                }
                else
                {
                    recordsList = new BindingList <TPEntry>(result.Where(p => p.Kekv.Id == selectedEstimate.Kekv.Id).ToList());
                }
            }
        }
Esempio n. 6
0
        private void updateContractsListWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Contractor selectedContractor = e.Argument as Contractor;

            using (TenderContext tc = new TenderContext())
            {
                List <Contract> contractsList = tc.Contracts.Include(p => p.RecordInPlan.Estimate).ToList()
                                                .Where(p => (p.ContractorId == selectedContractor.Id) &&
                                                       (p.RecordInPlan.Estimate.TenderYearId == year.Id))
                                                .Select(p => p).ToList();;

                if (invoiceRecord.Id == 0)
                {
                    contractsList = contractsList.Where(p => (p.Status == ContractStatus.Active)).ToList();
                }

                contractsRemains.Clear();
                foreach (var contract in contractsList)
                {
                    contractsRemains.Add(contract.MoneyRemain);
                }

                e.Result = contractsList;
            }
        }
        public TenderPlanRecordSelectForm()
        {
            InitializeComponent();
            using (TenderContext tc = new TenderContext())
            {
                tpEstimateCBList.DataSource    = tc.Estimates.ToList();
                tpEstimateCBList.DisplayMember = "Name";
                tpEstimateCBList.ValueMember   = "Id";

                List <KekvCode> kekvs = tc.KekvCodes.OrderBy(p => p.Code).ToList();
                kekvs.Insert(0, new KekvCode {
                    Code = "- ВСІ -", Id = -1
                });
                tpKekvsCBList.DataSource    = kekvs;
                tpKekvsCBList.DisplayMember = "Code";
                tpKekvsCBList.ValueMember   = "Id";

                tenderPlanTable.AutoGenerateColumns = false;

                LoadRecords();

                tpEstimateCBList.SelectedIndexChanged += (sender, e) => LoadRecords();
                tpKekvsCBList.SelectedIndexChanged    += (sender, e) => LoadRecords();
                tpNewSystemRButton.CheckedChanged     += (sender, e) => LoadRecords();
                tpAltSystemRButton.CheckedChanged     += (sender, e) => LoadRecords();

                button1.Click += (sender, e) => SelectRecord();
                tenderPlanTable.CellDoubleClick += (sender, e) => SelectRecord();
            }
        }
Esempio n. 8
0
        private void updateMoneysRemainsWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            UpdateMoneysWorkerArgument arg = e.Argument as UpdateMoneysWorkerArgument;

            using (TenderContext tc = new TenderContext())
            {
                moneysOnSources.Clear();
                DateTime lastDayOfMonth = new DateTime(arg.DocumentDate.Year,
                                                       arg.DocumentDate.Month,
                                                       DateTime.DaysInMonth(arg.DocumentDate.Year, arg.DocumentDate.Month));
                foreach (var source in sourcesList)
                {
                    decimal remain = tc.BalanceChanges
                                     .Where(p => (p.EstimateId == arg.Estimate.Id) &&
                                            (p.PrimaryKekvId == arg.Kekv.Id) &&
                                            (p.DateOfReceiving <= lastDayOfMonth) &&
                                            (p.MoneySourceId == source.Id)).Select(p => p.PrimaryKekvSum).DefaultIfEmpty(0).Sum();

                    if (spendingRecord.Id > 0)
                    {
                        var rec = tc.BalanceChanges
                                  .Where(p => (p.PlannedSpendingId == spendingRecord.Id) &&
                                         (p.EstimateId == arg.Estimate.Id) &&
                                         (p.MoneySourceId == source.Id)).FirstOrDefault();

                        if (rec != null)
                        {
                            remain -= rec.PrimaryKekvSum;
                        }
                    }

                    moneysOnSources.Add(remain);
                }
            }
        }
Esempio n. 9
0
        public static bool AuthorizeUser(string username, string password)
        {
            using (TenderContext tc = new TenderContext())
            {
                User target = tc.Users.Where(p => p.Name.Equals(username)).FirstOrDefault();

                if (target == null)
                {
                    return(false);
                }

                byte[] hashOfEnteredPass = GetPasswordHash(password);
                byte[] hashOfUserInDb    = Convert.FromBase64String(target.PasswordHash);

                if (hashOfEnteredPass.Length != hashOfUserInDb.Length)
                {
                    return(false);
                }

                for (int i = 0; i < hashOfEnteredPass.Length; i++)
                {
                    if (hashOfEnteredPass[i] != hashOfUserInDb[i])
                    {
                        return(false);
                    }
                }

                authenticatedUsername = target.Name;

                return(true);
            }
        }
Esempio n. 10
0
        public AddEditContractor(Contractor record)
        {
            InitializeFormControls();

            if (!UserSession.IsAuthorized)
            {
                button1.Visible = linkLabel1.Visible = linkLabel2.Visible = false;
            }

            using (TenderContext tc = new TenderContext())
            {
                tc.Contractors.Attach(record);
                contractorRecord = record;

                fullNameTextBox.Text     = contractorRecord.LongName;
                shortNameTextBox.Text    = contractorRecord.ShortName;
                edrTextBox.Text          = contractorRecord.EdrCode;
                legalAdressTextBox.Text  = contractorRecord.LegalAddress;
                actualAdressTextBox.Text = contractorRecord.ActualAddress;
                descriptionTextBox.Text  = contractorRecord.Description;

                relatedFiles.Clear();
                foreach (var item in record.RelatedFiles)
                {
                    relatedFiles.Add(item);
                }

                contactsList.Clear();
                foreach (var item in record.Persons)
                {
                    contactsList.Add(item);
                }
            }
        }
Esempio n. 11
0
        private void InitializeFormControls(TenderYear year)
        {
            InitializeComponent();

            button1.Visible = UserSession.IsAuthorized;

            using (TenderContext tc = new TenderContext())
            {
                contractorCBList.DataSource    = tc.Contractors.OrderBy(p => p.ShortName).ToList();
                contractorCBList.DisplayMember = "ShortName";
                contractorCBList.ValueMember   = "Id";
            }

            isPossibleToChangeContractMainData = true;
            locker      = new object();
            label8.Text = string.Empty;
            contractUsedSumLabel.Text      = contractRemainLabel.Text = string.Empty;
            filesTable.AutoGenerateColumns = contractChangesTable.AutoGenerateColumns = contractInvoicesTable.AutoGenerateColumns = false;

            deletingFiles         = new List <UploadedFile>();
            relatedFiles          = new BindingList <UploadedFile>();
            filesTable.DataSource = relatedFiles;
            DataGridViewHelper.ConfigureFileTable(filesTable, relatedFiles, deletingFiles, linkLabel1, linkLabel2, linkLabel3);

            dateOfSigning.Value = dateOfStart.Value = dateOfEnd.Value =
                new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddYears(Convert.ToInt32(year.Year) - DateTime.Now.Year);
            dateOfSigning.MinDate = dateOfStart.MinDate = dateOfEnd.MinDate = new DateTime(Convert.ToInt32(year.Year), 1, 1, 0, 0, 0);
            dateOfSigning.MaxDate = dateOfStart.MaxDate = dateOfEnd.MaxDate = new DateTime(Convert.ToInt32(year.Year), 12, 31, 0, 0, 0);
            dateOfEnd.Value       = new DateTime(Convert.ToInt32(year.Year), 12, 31, 0, 0, 0);

            hiddenPagesList = new List <TabPage>();

            contractChangesTable.RowsAdded  += (sender, e) => DataGridViewHelper.CalculateNewRowNumber(contractChangesTable, 0, e.RowIndex, e.RowCount);
            contractInvoicesTable.RowsAdded += (sender, e) => DataGridViewHelper.CalculateNewRowNumber(contractInvoicesTable, 0, e.RowIndex, e.RowCount);
        }
Esempio n. 12
0
 private void ReloadListOfYears()
 {
     using (TenderContext tc = new TenderContext())
     {
         List <TenderYear> years = tc.TenderYears.ToList();
         listBox1.DataSource    = years;
         listBox1.DisplayMember = "FullName";
         listBox1.ValueMember   = "Id";
     }
 }
Esempio n. 13
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(codeTextBox.Text))
            {
                NotificationHelper.ShowError("Ви не зазначили код");
                return;
            }
            if (!Regex.IsMatch(codeTextBox.Text.Trim(), "[0-9]{8}-[0-9]"))
            {
                NotificationHelper.ShowError("Неправильний формат коду. Код повинен відповідати формату ХХХХХХХХ-Х. Де Х - число від 0 до 9");
                return;
            }
            if (string.IsNullOrWhiteSpace(nameTextBox.Text))
            {
                NotificationHelper.ShowError("Ви не зазначили назву для кода");
                return;
            }

            using (TenderContext tc = new TenderContext())
            {
                if (codeRecord == null)
                {
                    codeRecord = new DkCode();
                }
                else
                {
                    tc.DkCodes.Attach(codeRecord);
                }

                bool codeExist = tc.DkCodes.Where(p => p.Code.Equals(codeTextBox.Text.Trim())).Any();
                if (codeExist && (codeRecord.Id == 0))
                {
                    NotificationHelper.ShowError("Такий код вже існує");
                    return;
                }

                codeRecord.Code = codeTextBox.Text.Trim();
                codeRecord.Name = nameTextBox.Text.Trim();

                if (codeRecord.Id == 0)
                {
                    tc.DkCodes.Add(codeRecord);
                }
                else
                {
                    tc.Entry <DkCode>(codeRecord).State = System.Data.Entity.EntityState.Modified;
                }

                tc.SaveChanges();
                wasDbUpdated = true;
                this.Close();
            }
        }
Esempio n. 14
0
        private void InitializeFormControls()
        {
            InitializeComponent();

            // Отключаем переключатель просмотра остатков по разным системам (оставляем доработку этого функционала в будущих версиях)
            newSystemRButton.Visible = oldSystemRButton.Visible = false;

            saveEstimateDataButton.Visible = UserSession.IsAuthorized;

            wasDbChanged = false;

            estimateMoneyList = new List <EstimateMoneyOnSourceTable>();
            deletingFiles     = new List <UploadedFile>();

            monthes = new string[]
            {
                "Січень", "Лютий", "Березень",
                "Квітень", "Травень", "Червень",
                "Липень", "Серпень", "Вересень",
                "Жовтень", "Листопад", "Грудень"
            };

            using (TenderContext tc = new TenderContext())
            {
                kekvsList   = tc.KekvCodes.OrderBy(p => p.Code).ToList();
                sourcesList = new BindingList <MoneySource>(tc.MoneySources.OrderBy(p => p.ViewPriority).ToList());
            }

            moneySourceCBList.DataSource    = sourcesList;
            moneySourceCBList.DisplayMember = "Name";
            moneySourceCBList.ValueMember   = "Id";

            filesTable.AutoGenerateColumns = false;

            DataGridViewHelper.DrawMoneyTotalsTableSchema <KekvCode, string>(estimateTotalsTable,
                                                                             kekvsList, monthes.ToList(), t => t.Code, t => t);
            estimateTotalsTable.SortCompare += (sender, e) => DataGridViewHelper.SortCompareForMoneyTable(estimateTotalsTable, e);

            tableDataWasChangedByUser = false;
            for (int i = 0; i < estimateTotalsTable.RowCount; i++)
            {
                for (int k = 0; k < estimateTotalsTable.ColumnCount; k++)
                {
                    estimateTotalsTable.Rows[i].Cells[k].Value = 0.00;
                }
            }
            tableDataWasChangedByUser = true;

            relatedFiles          = new BindingList <UploadedFile>();
            filesTable.DataSource = relatedFiles;
            DataGridViewHelper.ConfigureFileTable(filesTable, relatedFiles, deletingFiles, linkLabel1, linkLabel2, linkLabel3);
        }
Esempio n. 15
0
        public EstimateForm(Estimate est)
        {
            InitializeFormControls();

            if (!UserSession.IsAuthorized)
            {
                this.Text = "Перегляд даних кошторису";
            }
            else
            {
                this.Text = "Редагування даних кошторису";
            }

            currentEstimate          = est;
            estimateNameTextBox.Text = currentEstimate.Name;

            using (TenderContext tc = new TenderContext())
            {
                tc.Estimates.Attach(currentEstimate);
                tc.Entry <Estimate>(currentEstimate).Collection(p => p.RelatedFiles).Load();

                relatedFiles.Clear();
                foreach (var elem in currentEstimate.RelatedFiles)
                {
                    relatedFiles.Add(elem);
                }

                // Получаем все поступления по смете
                EstimateMoneyOnSourceTable.GetEstimateMoneyTable(currentEstimate,
                                                                 kekvsList,
                                                                 monthes,
                                                                 p => (p.PlannedSpending == null && p.Invoice == null),
                                                                 CreateMoneySourceTab);

                // Получаем список затрат сметы
                estimateSpendingList = EstimateMoneyOnSourceTable.GetEstimateMoneyTable(currentEstimate,
                                                                                        kekvsList,
                                                                                        monthes,
                                                                                        p => (p.PlannedSpending != null || p.Invoice != null));

                // Получаем список запланированных трат по годовому плану по КЕКВ
                plannedMoneyOnKekvs = (from plItem in tc.TenderPlanRecords.ToList()
                                       where plItem.EstimateId == currentEstimate.Id
                                       group plItem by plItem.PrimaryKekv into g1
                                       select new KekvMoneyRecord
                {
                    Kekv = g1.Key,
                    Sum = g1.Sum(p => p.UsedByRecordSum)
                }).ToList();
            }
        }
Esempio n. 16
0
        // Загрузка списка кодов ДК по выбраному КЕКВ
        private void LoadDkCodeList()
        {
            using (TenderContext tc = new TenderContext())
            {
                KekvRemain selectedMainKekv = mainKekv.SelectedItem as KekvRemain;
                Estimate   selectedEstimate = estimatesCBList.SelectedItem as Estimate;

                if (selectedEstimate == null || selectedMainKekv == null)
                {
                    return;
                }

                // Получаем список всех кодов ДК
                List <DkCode> allDkCodesList = tc.DkCodes.ToList();

                // Список кодов по которым уже существуют записи в текущем году
                List <DkCode> existingDkCodesOnKekv = tc.TenderPlanRecords
                                                      .Where(p => p.Estimate.TenderYearId == year.Id)
                                                      .Select(p => p.Dk)
                                                      .Distinct()
                                                      .ToList();

                bool codeRepeat = isCodeRepeatCheckBox.Checked;

                // Не отображаем текущий код в списке существующих, чтобы исключить возможность продублировать самого себя
                if (planRecord != null)
                {
                    if (planRecord.CodeRepeatReason == null)
                    {
                        existingDkCodesOnKekv = existingDkCodesOnKekv.Where(p => p.Id != planRecord.DkCodeId).ToList();
                    }

                    codeRepeat = codeRepeat || (planRecord.CodeRepeatReason != null);
                }

                if (!codeRepeat)
                {
                    dkCodesCBList.DataSource = allDkCodesList.Except(existingDkCodesOnKekv).OrderBy(p => p.Code).ToList();
                }
                // ... либо выбираем только существующие
                else
                {
                    dkCodesCBList.DataSource = existingDkCodesOnKekv.OrderBy(p => p.Code).ToList();
                }

                dkCodesCBList.DisplayMember = "FullName";
                dkCodesCBList.ValueMember   = "Id";
                dkCodesCBList.Refresh();
            }
        }
Esempio n. 17
0
        public SelectEstimateForReportForm()
        {
            InitializeComponent();

            using (TenderContext tc = new TenderContext())
            {
                List <Estimate> estimates = tc.Estimates.Include(p => p.Year).ToList();
                estimates.Insert(0, new Estimate {
                    Id = -1, Name = "- ВСІ КОШТОРИСИ ЗА РІК -"
                });
                comboBox1.DisplayMember = "Name";
                comboBox1.DataSource    = estimates;
            }
        }
Esempio n. 18
0
        public static void CreateUser(string username, string password, string description)
        {
            User newUser = new User
            {
                Name         = username,
                PasswordHash = Convert.ToBase64String(GetPasswordHash(password)),
                Description  = description
            };

            using (TenderContext tc = new TenderContext())
            {
                tc.Users.Add(newUser);
                tc.SaveChanges();
            }
        }
        private void SelectRecord()
        {
            SelectedRecord = (tenderPlanTable.SelectedRows[0].DataBoundItem as TPEntry).Record;

            using (TenderContext tc = new TenderContext())
            {
                tc.TenderPlanRecords.Attach(SelectedRecord);
                tc.Entry <TenderPlanRecord>(SelectedRecord).Collection(p => p.RegisteredContracts).Load();
                tc.Entry <TenderPlanRecord>(SelectedRecord).Collection(p => p.RegisteredContracts).Query().Include(p => p.Invoices).Load();

                tc.Entry <TenderPlanRecord>(SelectedRecord).Reference(p => p.Estimate).Load();
                tc.Entry <TenderPlanRecord>(SelectedRecord).Reference(p => p.Estimate).Query().Include(p => p.Changes).Load();
            }
            Close();
        }
        public DkCodeChangesHistoryForm(TenderPlanRecord record, bool isNewSystemSelected)
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;

            using (TenderContext tc = new TenderContext())
            {
                tc.TenderPlanRecords.Attach(record);

                estimateNameLabel.Text = record.Estimate.Name;
                dkCodeLabel.Text       = record.Dk.FullName;

                List <TenderPlanItemChangeEntry> changesList = new List <TenderPlanItemChangeEntry>();

                if (isNewSystemSelected)
                {
                    kekvLabel.Text = record.PrimaryKekv.Code;
                    changesList    = (from rec in tc.TenderPlanRecordChanges.ToList()
                                      where (rec.TenderPlanRecordId == record.Id)
                                      orderby rec.DateOfChange descending
                                      select new TenderPlanItemChangeEntry
                    {
                        DateOfChange = rec.DateOfChange,
                        Description = rec.Description,
                        DkCode = rec.Record.Dk.FullName,
                        Kekv = rec.Record.PrimaryKekv.Code,
                        SumChange = rec.ChangeOfSum
                    }).ToList();
                }
                else
                {
                    kekvLabel.Text = record.SecondaryKekv.Code + "(за старою системою)";
                    changesList    = (from rec in tc.TenderPlanRecordChanges.ToList()
                                      where (rec.TenderPlanRecordId == record.Id)
                                      orderby rec.DateOfChange descending
                                      select new TenderPlanItemChangeEntry
                    {
                        DateOfChange = rec.DateOfChange,
                        Description = rec.Description,
                        DkCode = rec.Record.Dk.FullName,
                        Kekv = rec.Record.SecondaryKekv.Code,
                        SumChange = rec.ChangeOfSum
                    }).ToList();
                }

                dataGridView1.DataSource = changesList;
            }
        }
Esempio n. 21
0
        private void SaveDataToDb()
        {
            using (TenderContext tc = new TenderContext())
            {
                currentEstimate.Name = estimateNameTextBox.Text.Trim();
                if (currentEstimate.Id > 0)
                {
                    tc.Estimates.Attach(currentEstimate);
                    tc.Entry <Estimate>(currentEstimate).State = System.Data.Entity.EntityState.Modified;

                    // Удаляем старые записи сметы
                    var oldBalanceChanges = tc.BalanceChanges.Where(p => (p.EstimateId == currentEstimate.Id && p.PrimaryKekvSum >= 0 && p.SecondaryKekvSum >= 0));
                    tc.BalanceChanges.RemoveRange(oldBalanceChanges);

                    tc.SaveChanges();
                }
                else
                {
                    tc.TenderYears.Attach(currentEstimate.Year);
                    tc.Estimates.Add(currentEstimate);
                    tc.SaveChanges();
                }

                for (int i = 0; i < estimateMoneyList.Count; i++)
                {
                    for (int j = 0; j < kekvsList.Count; j++)
                    {
                        for (int k = 0; k < monthes.Length; k++)
                        {
                            BalanceChanges incommingMoney = new BalanceChanges();
                            incommingMoney.DateOfReceiving  = new DateTime((int)currentEstimate.Year.Year, (k + 1), 1, 0, 0, 0);
                            incommingMoney.EstimateId       = currentEstimate.Id;
                            incommingMoney.MoneySourceId    = estimateMoneyList[i].Source.Id;
                            incommingMoney.PrimaryKekvId    = incommingMoney.SecondaryKekvId = kekvsList[j].Id;
                            incommingMoney.PrimaryKekvSum   = estimateMoneyList[i].PrimarySumValues[j, k];
                            incommingMoney.SecondaryKekvSum = estimateMoneyList[i].SecondarySumValues[j, k];
                            tc.BalanceChanges.Add(incommingMoney);
                        }
                    }
                }

                tc.SaveChanges();

                FileManager.UpdateRelatedFilesOfEntity(tc, currentEstimate.RelatedFiles, relatedFiles, deletingFiles);

                wasDbChanged = true;
            }
        }
Esempio n. 22
0
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            AddEditDkCodeForm af = new AddEditDkCodeForm();

            af.ShowDialog();

            if (af.WasDbUpdated)
            {
                using (TenderContext tc = new TenderContext())
                {
                    codesList = new BindingList <DkCode>(tc.DkCodes.OrderBy(p => p.Code).ToList());
                    dkCodesTable.DataSource = codesList;
                }
                wasDbUpdated = true;
            }
        }
Esempio n. 23
0
        private void updateKekvListWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Estimate arg = e.Argument as Estimate;

            using (TenderContext tc = new TenderContext())
            {
                tc.Estimates.Attach(arg);
                List <KekvCode>   mainKekvList            = new List <KekvCode>();
                List <KekvRemain> notPlannedEstimateMoney = (from item in arg.Changes.ToList()
                                                             where ((item.PrimaryKekvSum > 0) || (item.PlannedSpendingId != null))
                                                             group item by item.PrimaryKekv into g1
                                                             select new KekvRemain
                {
                    Kekv = g1.Key,
                    Remain = g1.Sum(p => p.PrimaryKekvSum)
                }).ToList();
                List <KekvRemain> plannedEstimateMoney = (from item in tc.TenderPlanRecords.ToList()
                                                          where (item.EstimateId == arg.Id)
                                                          group item by item.PrimaryKekv into g1
                                                          select new KekvRemain
                {
                    Kekv = g1.Key,
                    Remain = g1.Sum(p => p.UsedByRecordSum)
                }).ToList();

                List <KekvRemain> availableMoneyForPlannedSpending = (from rec1 in notPlannedEstimateMoney
                                                                      join rec2 in plannedEstimateMoney on rec1.Kekv equals rec2.Kekv into j1
                                                                      from jr in j1.DefaultIfEmpty(new KekvRemain())
                                                                      select new KekvRemain
                {
                    Kekv = rec1.Kekv,
                    Remain = rec1.Remain - jr.Remain
                } into s1
                                                                      orderby s1.Kekv.Code ascending
                                                                      select s1).ToList();

                kekvRemains.Clear();
                foreach (var item in availableMoneyForPlannedSpending)
                {
                    mainKekvList.Add(item.Kekv);
                    kekvRemains.Add(item.Remain);
                }

                e.Result = mainKekvList;
            }
        }
Esempio n. 24
0
        private void dkCodesTable_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DkCode            selectedCode = dkCodesTable.SelectedRows[0].DataBoundItem as DkCode;
            AddEditDkCodeForm af           = new AddEditDkCodeForm(selectedCode);

            af.ShowDialog();

            if (af.WasDbUpdated)
            {
                using (TenderContext tc = new TenderContext())
                {
                    codesList = new BindingList <DkCode>(tc.DkCodes.OrderBy(p => p.Code).ToList());
                    dkCodesTable.DataSource = codesList;
                }
                wasDbUpdated = true;
            }
        }
Esempio n. 25
0
        public static bool ChangeUserPassword(string username, string oldPassword, string newPassword)
        {
            // Проверяем старый пароль
            if (AuthorizeUser(username, oldPassword))
            {
                using (TenderContext tc = new TenderContext())
                {
                    User target = tc.Users.Where(p => p.Name.Equals(username)).FirstOrDefault();
                    target.PasswordHash           = Convert.ToBase64String(GetPasswordHash(newPassword));
                    tc.Entry <User>(target).State = System.Data.Entity.EntityState.Modified;

                    tc.SaveChanges();
                    return(true);
                }
            }
            else
            {
                return(false);
            }
        }
Esempio n. 26
0
        private void InitializeControls()
        {
            InitializeComponent();
            filesTable.AutoGenerateColumns = false;
            dbWasChanged          = false;
            moneyRemainLabel.Text = string.Empty;
            LoadProcedureTypesCBList();

            button1.Visible = UserSession.IsAuthorized;

            tenderBeginDate.Value = protocolDate.Value =
                new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddYears(Convert.ToInt32(year.Year) - DateTime.Now.Year);
            tenderBeginDate.MinDate = new DateTime(Convert.ToInt32(year.Year), 1, 1, 0, 0, 0);
            protocolDate.MinDate    = new DateTime(Convert.ToInt32(year.Year - 1), 1, 1, 0, 0, 0);
            tenderBeginDate.MaxDate = protocolDate.MaxDate = new DateTime(Convert.ToInt32(year.Year), 12, 31, 0, 0, 0);

            deletingFiles         = new List <UploadedFile>();
            relatedFiles          = new BindingList <UploadedFile>();
            filesTable.DataSource = relatedFiles;
            DataGridViewHelper.ConfigureFileTable(filesTable, relatedFiles, deletingFiles, linkLabel1, linkLabel2, linkLabel3);

            using (TenderContext tc = new TenderContext())
            {
                estimateList                  = tc.Estimates.Where(p => p.TenderYearId == this.year.Id).ToList();
                controlWasChangedByUser       = false;
                estimatesCBList.DataSource    = estimateList;
                controlWasChangedByUser       = true;
                estimatesCBList.DisplayMember = "Name";
                estimatesCBList.ValueMember   = "Id";

                altKekvList = tc.KekvCodes.OrderBy(p => p.Code).Select(p => new KekvRemain {
                    Kekv = p
                }).ToList();
                altKekv.DataSource = altKekvList;

                mainKekv.DisplayMember = altKekv.DisplayMember = "Kekv";
                mainKekv.ValueMember   = altKekv.ValueMember = "Id";
            }

            LoadKekvsOnEstimate();
        }
Esempio n. 27
0
        public ContractorsListForm()
        {
            wasDbUpdated = false;
            InitializeComponent();

            if (!UserSession.IsAuthorized)
            {
                editContractorButton.Text     = "Переглянути";
                editContractorButton.Location = addContractorButton.Location;
                addContractorButton.Visible   = deleteContractorButton.Visible = false;
            }

            contractorsTable.AutoGenerateColumns = false;
            using (TenderContext tc = new TenderContext())
            {
                contractorsList = new BindingList <Contractor>(tc.Contractors.ToList());
            }
            contractorsTable.DataSource = contractorsList;

            textBox1.TextChanged += (sender, e) => FilterList();
        }
Esempio n. 28
0
        public ContractsOnDkCodeForm(TenderPlanRecord record, bool isNewSystemSelected)
        {
            InitializeComponent();
            contractsTable.AutoGenerateColumns = false;
            contractsTable.RowsAdded          += (sender, e) => DataGridViewHelper.CalculateNewRowNumber(contractsTable, 0, e.RowIndex, e.RowCount);

            using (TenderContext tc = new TenderContext())
            {
                tc.TenderPlanRecords.Attach(record);
                estimateNameLabel.Text = record.Estimate.Name;
                dkCodeLabel.Text       = record.Dk.FullName;

                List <ContractsTableEntry> tableEntries = new List <ContractsTableEntry>();

                if (isNewSystemSelected)
                {
                    kekvLabel.Text = record.PrimaryKekv.Code;
                }
                else
                {
                    kekvLabel.Text = record.SecondaryKekv.Code + "(по старой системе)";
                }

                tableEntries = (from rec in tc.Contracts.ToList()
                                where (rec.TenderPlanRecordId == record.Id)
                                orderby rec.SignDate descending
                                select new ContractsTableEntry
                {
                    ContractDate = rec.SignDate,
                    ContractNum = rec.Number,
                    Contractor = rec.Contractor,
                    Description = rec.Description,
                    FullSum = rec.Sum,
                    RelatedContract = rec,
                    UsedSum = rec.UsedMoney
                }).ToList();

                contractsTable.DataSource = tableEntries;
            }
        }
        public EstimateFreeMoneyForm(int estimateId)
        {
            InitializeComponent();
            kekvRemainsTable.AutoGenerateColumns = false;

            using (TenderContext tc = new TenderContext())
            {
                Estimate est = tc.Estimates.Where(p => p.Id == estimateId).FirstOrDefault();

                estimateNameLabel.Text = est.Name;
                this.Text += " на " + est.Year.Year + " рік";

                var groupedTenderRecordsByKekv = (from rec in tc.TenderPlanRecords.ToList()
                                                  where rec.EstimateId == est.Id
                                                  group rec by rec.PrimaryKekv into g1
                                                  select new KekvMoneyRecord
                {
                    Kekv = g1.Key, Sum = g1.Sum(p => p.UsedByRecordSum)
                });
                var groupedEstimatedMoneysByKekv = (from rec in tc.BalanceChanges
                                                    where (((rec.PrimaryKekvSum > 0) || (rec.PlannedSpendingId != null)) &&
                                                           (rec.EstimateId == est.Id))
                                                    group rec by rec.PrimaryKekv into g1
                                                    select new KekvMoneyRecord
                {
                    Kekv = g1.Key, Sum = g1.Sum(p => p.PrimaryKekvSum)
                });

                kekvRemainsTable.DataSource = (from rec1 in groupedEstimatedMoneysByKekv.ToList()
                                               join rec2 in groupedTenderRecordsByKekv.ToList() on rec1.Kekv equals rec2.Kekv into j1
                                               from def in j1.DefaultIfEmpty(new KekvMoneyRecord {
                    Sum = 0
                })
                                               //where rec1.Sum > def.Sum
                                               select new KekvMoneyRecord
                {
                    Kekv = rec1.Kekv, Sum = rec1.Sum - def.Sum
                }).ToList();
            }
        }
Esempio n. 30
0
        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            DkCode selectedCode = dkCodesTable.SelectedRows[0].DataBoundItem as DkCode;

            using (TenderContext tc = new TenderContext())
            {
                bool codeHasReferences = tc.TenderPlanRecords.Where(p => (p.DkCodeId == selectedCode.Id)).Any();
                if (codeHasReferences)
                {
                    NotificationHelper.ShowError("Неможливо видалити код, оскільки під нього існують записи у річних планах закупівель");
                    return;
                }
                else
                {
                    tc.DkCodes.Attach(selectedCode);
                    tc.DkCodes.Remove(selectedCode);
                    tc.SaveChanges();

                    codesList.Remove(selectedCode);
                    NotificationHelper.ShowInfo("Код успішно видалений!");
                    wasDbUpdated = true;
                }
            }
        }