Esempio n. 1
0
        public async Task <IEnumerable <GridSetting> > GetAsync(GridSettingSearch option, CancellationToken token = default(CancellationToken))
        {
            var settings = await gridSettingQueryProcessor.GetAsync(option, token);

            var control = await applicationControlByCompanyIdQueryProcessor.GetAsync(option.CompanyId, token);

            return(SetApplicationControlValues(settings, control));
        }
        public async Task <byte[]> GetAsync(MatchingJournalizingReportSource source, CancellationToken token = default(CancellationToken))
        {
            if (!(source.Items?.Any() ?? false))
            {
                return(null);
            }

            var companyTask = companyQueryProcessor.GetAsync(new CompanySearch {
                Id = source.CompanyId,
            }, token);
            var appConTask = applicationControlGetByCompanyQueryProcessor.GetAsync(source.CompanyId, token);
            await Task.WhenAll(companyTask, appConTask);

            var company = companyTask.Result.First();
            var appCon  = appConTask.Result;

            var report = new MatchingJournalizingReport();

            var fileName = $"{(source.ReOutput ? "再出力" : "")}消込仕訳_{DateTime.Now:yyyyMMdd_HHmmss}";

            report.SetBasicPageSetting(company.Code, company.Name);
            report.Name = fileName;
            report.SetData(source.Items, source.Precision, appCon.UseForeignCurrency == 1);
            report.Run();

            return(report.Convert());
        }
        public async Task <byte[]> GetAsync(CustomerSearch option, CancellationToken token = default(CancellationToken))
        {
            var companyTask = companyQueryProcessor.GetAsync(new CompanySearch {
                Id = option.CompanyId
            }, token);
            var appConTask     = applicationControlGetByCompanyQueryProcessor.GetAsync(option.CompanyId.Value, token);
            var masterLoadTask = customerQueryProcessor.GetAsync(option, token);

            await Task.WhenAll(companyTask, appConTask, masterLoadTask);

            var company = companyTask.Result.First();
            var appCon  = appConTask.Result;
            var items   = masterLoadTask.Result.ToList();

            if (!items.Any())
            {
                return(null);
            }

            var report = new CustomerAccountSectionReport();

            report.Name = "得意先台帳" + DateTime.Now.ToString("yyyyMMdd");
            report.SetBasicPageSetting(company.Code, company.Name);
            report.SetData(items,
                           appCon.UsePublishInvoice == 1,
                           appCon.UseReminder == 1);

            report.Run();

            return(report.Convert());
        }
Esempio n. 4
0
        public async Task <int> DeleteAsync(BillingDeleteSource source, CancellationToken token = default(CancellationToken))
        {
            var result = 0;
            var app    = await getApplicationControlByCompanyQueryProcessor.GetAsync(source.CompanyId, token);

            using (var scope = transactionScopeBuilder.Create())
            {
                foreach (var id in source.Ids)
                {
                    if (app.RegisterContractInAdvance == 1)
                    {
                        await updateBillingDivisionContractQueryProcessor.UpdateWithBillingIdAsync(id, source.LoginUserId, token);
                    }
                    else
                    {
                        await deleteBillingDivisionContractQueryProcessor.DeleteWithBillingIdAsync(id, token);
                    }

                    if (app.UseDiscount == 1)
                    {
                        await deleteBillingDiscountQueryProcessor.DeleteAsync(id, token);
                    }

                    result += await DeleteInnerAsync(id, token);
                }
                scope.Complete();
            }
            return(result);
        }
Esempio n. 5
0
        private async Task <BillingDivisionContract> PrepareDataForBillingDivisionContract(BillingImport billingImport, long billingSaveId, int CompanyId, CancellationToken token)
        {
            var setting = await billingDivisionSettingQueryProcessor.GetAsync(CompanyId, token);

            if (setting == null)
            {
                return(null);
            }

            var newNumber = await billingDivisionContractQueryProcessor.GetNewContractNumberAsync(CompanyId, token);

            var contract = new BillingDivisionContract {
                ContractNumber       = newNumber.ToString(),
                CustomerId           = billingImport.CustomerId,
                FirstDateType        = setting.FirstDateType,
                Monthly              = setting.Monthly,
                BasisDay             = setting.BasisDay,
                DivisionCount        = setting.DivisionCount,
                RoundingMode         = setting.RoundingMode,
                RemainsApportionment = setting.RemainsApportionment,
                BillingId            = billingSaveId,
                BillingAmount        = billingImport.BillingAmount,
                Comfirm              = 0,
            };

            return(contract);
        }
Esempio n. 6
0
        //public async Task<int> DeleteAsync(CustomerFeeSearch option, CancellationToken token = default(CancellationToken))
        //    => await deleteCustomerFeeQueryProcessor.DeleteAsync(option, token);

        public async Task <ImportResult> ImportAsync(IEnumerable <CustomerFee> insert, IEnumerable <CustomerFee> update, IEnumerable <CustomerFee> delete, CancellationToken token = default(CancellationToken))
        {
            using (var scope = transactionScopeBuilder.Create())
            {
                var deleteCount = 0;
                var updateCount = 0;
                var insertCount = 0;

                var defaultCurrencyId       = 0;
                var isNotUseForeignCurrency = true;
                if (insert.Any())
                {
                    var companyId  = insert.First().CompanyId;
                    var appControl = await applicationControlByCompanyIdQueryProcessor.GetAsync(companyId, token);

                    isNotUseForeignCurrency = appControl.UseForeignCurrency == 0;

                    if (isNotUseForeignCurrency)
                    {
                        defaultCurrencyId = (await currencyGetByCodesQueryProcessor.GetByCodesAsync(companyId, new[] { DefaultCurrencyCode })).First().Id;
                    }
                }

                foreach (var x in delete)
                {
                    await deleteCustomerFeeQueryProcessor.DeleteAsync(new CustomerFeeSearch { CustomerId = x.CustomerId }, token);

                    deleteCount++;
                }

                foreach (var x in update)
                {
                    await addCustomerFeeQueryProcessor.SaveAsync(x);

                    ++updateCount;
                }

                foreach (var x in insert)
                {
                    if (isNotUseForeignCurrency)
                    {
                        x.CurrencyId = defaultCurrencyId;
                    }
                    await addCustomerFeeQueryProcessor.SaveAsync(x);

                    ++insertCount;
                }

                scope.Complete();

                return(new ImportResult {
                    ProcessResult = new ProcessResult {
                        Result = true,
                    },
                    InsertCount = insertCount,
                    UpdateCount = updateCount,
                    DeleteCount = deleteCount,
                });
            }
        }
Esempio n. 7
0
        public async Task <byte[]> GetAsync(CustomerFeeSearch option, CancellationToken token = default(CancellationToken))
        {
            var companyTask = companyQueryProcessor.GetAsync(new CompanySearch {
                Id = option.CompanyId,
            }, token);
            var appControlTask = applicationControlGetByCompanyQueryProcessor.GetAsync(option.CompanyId.Value, token);
            var masterLoadTask = customerFeeQueryProcessor.GetAsync(option, token);

            await Task.WhenAll(companyTask, appControlTask, masterLoadTask);

            var company   = companyTask.Result.First();
            var appCon    = appControlTask.Result;
            var items     = masterLoadTask.Result.ToList();
            var precision = appCon.UseForeignCurrency == 0 ? 0 : items.Max(x => x.CurrencyPrecision);

            if (!items.Any())
            {
                return(null);
            }

            var report = new CustomerFeeSectionReport();

            report.Name = "登録手数料一覧" + DateTime.Now.ToString("yyyyMMdd");
            report.SetBasicPageSetting(company.Code, company.Name);
            report.SetData(items, appCon.UseForeignCurrency);
            report.Precision = precision;
            report.Run();

            return(report.Convert());
        }
        public async Task <byte[]> GetAsync(int companyId, CancellationToken token = default(CancellationToken))
        {
            var companyTask = companyQueryProcessor.GetAsync(new CompanySearch {
                Id = companyId,
            }, token);
            var appConTask = applicationControlGetByCompanyQueryProcessor.GetAsync(companyId, token);
            var loadTask   = receiptSectionTransferQueryProcessor.GetReceiptSectionTransferForPrintAsync(companyId, token);

            await Task.WhenAll(companyTask, appConTask, loadTask);

            var company = companyTask.Result.First();
            var appCon  = appConTask.Result;
            var items   = loadTask.Result.ToList();

            if (!items.Any())
            {
                return(null);
            }

            var useForeignCurrency = appCon.UseForeignCurrency == 1;
            var precition          = !useForeignCurrency ? 0 : items.Max(x => x.Precision);

            var report = new ReceiptSectionTransferSectionReport();

            report.SetBasicPageSetting(company.Code, company.Name);
            report.Name = "入金部門振替済チェックリスト" + DateTime.Today.ToString("yyyyMMdd");
            report.SetData(items, useForeignCurrency, precition);

            report.Run();

            return(report.Convert());
        }
        public async Task <byte[]> GetAsync(ReceiptApportionForReportSource source, CancellationToken token = default(CancellationToken))
        {
            if (!(source.Apportions?.Any() ?? false))
            {
                return(null);
            }

            var companyId = source.CompanyId;

            var companyTask = companyQueryProcessor.GetAsync(new CompanySearch {
                Id = companyId
            }, token);
            var appConTask = applicationControlGetByCompanyQueryProcessor.GetAsync(companyId, token);
            var nameTask   = columnNameSettingQueryProcessor.GetAsync(new ColumnNameSetting {
                CompanyId = companyId, TableName = nameof(Receipt),
            }, token);

            await Task.WhenAll(companyTask, appConTask, nameTask);

            var company   = companyTask.Result.First();
            var appCon    = appConTask.Result;
            var naming    = nameTask.Result.ToList();
            var precision = 0;

            var report = new ReceiptApportionSectionReport();

            report.Name = "入金データ振分リスト" + DateTime.Now.ToString("yyyyMMdd");
            report.SetBasicPageSetting(company.Code, company.Name);
            report.SetHeaderSetting(source.Header, source.CategoryName);
            report.SetPageDataSetting(source.Apportions, appCon.UseReceiptSection, precision);

            report.Run();

            return(report.Convert());
        }
Esempio n. 10
0
        public async Task <CollationSetting> GetAsync(int CompanyId, CancellationToken token = default(CancellationToken))
        {
            var setting = await collationSettingGetByCompanyQueryProcessor.GetAsync(CompanyId, token);

            setting.CollationOrders       = (await GetCollationOrderAsync(CompanyId, token)).ToArray();
            setting.BillingMatchingOrders = (await GetMatchingBillingOrderAsync(CompanyId, token)).ToArray();
            setting.ReceiptMatchingOrders = (await GetMatchingReceiptOrderAsync(CompanyId, token)).ToArray();
            return(setting);
        }
        public async Task <byte[]> GetAsync(MatchingIndividualReportSource source, CancellationToken token = default(CancellationToken))
        {
            if (!(source.Items?.Any() ?? false))
            {
                return(null);
            }

            var companyTask = companyQueryProcessor.GetAsync(new CompanySearch {
                Id = source.CompanyId,
            }, token);
            var appConTask = applicationControlGetByCompanyQueryProcessor.GetAsync(source.CompanyId, token);

            await Task.WhenAll(companyTask, appConTask);

            var company = companyTask.Result.First();
            var appCon  = appConTask.Result;

            var moneyFormat = "#,0";

            GrapeCity.ActiveReports.SectionReport report;

            if (source.PriorReceipt)
            {
                var reportTemp = new MatchingIndividualReceiptBillingSectionReport();
                reportTemp.SetBasicPageSetting(company.Code, company.Name);
                reportTemp.SetAmountSetting(source.Precision,
                                            source.BillingTaxDiff.ToString(moneyFormat),
                                            source.ReceiptTaxDiff.ToString(moneyFormat),
                                            source.BankFee.ToString(moneyFormat),
                                            source.DiscountAmount.ToString(moneyFormat),
                                            appCon.UseDiscount);
                reportTemp.SetPageDataSetting(source.Items, source.BillingGridSettings, source.ReceiptGridSettings);
                reportTemp.shpBilling.BackColor = System.Drawing.Color.LightCyan;

                report = reportTemp;
            }
            else
            {
                var reportTemp = new MatchingIndividualSectionReport();
                reportTemp.SetBasicPageSetting(company.Code, company.Name);
                reportTemp.SetAmountSetting(source.Precision,
                                            source.BillingTaxDiff.ToString(moneyFormat),
                                            source.ReceiptTaxDiff.ToString(moneyFormat),
                                            source.BankFee.ToString(moneyFormat),
                                            source.DiscountAmount.ToString(moneyFormat),
                                            appCon.UseDiscount);
                reportTemp.SetPageDataSetting(source.Items, source.BillingGridSettings, source.ReceiptGridSettings);
                reportTemp.shpBilling.BackColor = System.Drawing.Color.LightCyan;

                report = reportTemp;
            }

            report.Name = "個別消込画面" + DateTime.Today.ToString("yyyyMMdd");
            report.Run();

            return(report.Convert());
        }
Esempio n. 12
0
        public async Task <byte[]> GetAsync(TransactionImportSource source, CancellationToken token = default(CancellationToken))
        {
            var companyId    = source.CompanyId;
            var importDataId = source.ImportDataId.Value;
            var objectType   = source.IsValidData ? 0 : 1;

            var companyTask = companyQueryProcessor.GetAsync(new CompanySearch {
                Id = companyId,
            }, token);
            var appConTask     = applicationControlGetByCompanyQueryProcessor.GetAsync(companyId, token);
            var columnNameTask = columnNameSettingQueryProcessor.GetAsync(new ColumnNameSetting
            {
                CompanyId  = companyId,
                TableName  = nameof(Billing),
                ColumnName = nameof(Billing.Note1),
            }, token);
            var itemsTask = importDataDetailQueryProcessor.GetAsync(importDataId, objectType, token);

            await Task.WhenAll(companyTask, appConTask, columnNameTask, itemsTask);

            var company = companyTask.Result.First();
            var appCon  = appConTask.Result;
            var note1   = columnNameTask.Result.FirstOrDefault()?.DisplayColumnName ?? "備考";
            var details = itemsTask.Result.ToArray();
            var items   = details.Select(x => serializer.UnpackSingleObject(x.RecordItem)).ToList();

            if (!items.Any())
            {
                return(null);
            }

            var useForeignCurrency = appCon.UseForeignCurrency == 1;

            var report = new BillingImporterSectionReport();

            var title = $"請求フリーインポーター 取込{(source.IsValidData ? "可能" : "不可能")}データ一覧{DateTime.Now:yyyyMMdd}";

            report.SetBasicPageSetting(company.Code, company.Name);
            report.Name = title;
            report.SetData(items, title, useForeignCurrency, note1);
            report.Run();

            return(report.Convert());
        }
Esempio n. 13
0
        public async Task <IEnumerable <MatchingHeader> > SearchMatchedDataAsync(CollationSearch CollationSearch, CancellationToken token = default(CancellationToken))
        {
            var collationSetting = (await getCollationSettingQueryProcessor.GetAsync(CollationSearch.CompanyId, token));

            CollationSearch.SortOrderDirection = collationSetting.SortOrderDirection;

            var items = await matchingQueryProcessor.SearchMatchedDataAsync(CollationSearch, token);

            return(items);
        }
Esempio n. 14
0
        public async Task <ClosingInformation> GetClosingInformationAsync(int companyId, CancellationToken token = default(CancellationToken))
        {
            var closing            = new ClosingInformation();
            var applicationControl = await applicationControlProcessor.GetAsync(companyId, token);

            if (applicationControl?.UseClosing == 1)
            {
                closing.UseClosing = true;
                closing.Closing    = await byCompanyGetClosingQueryProcessor.GetAsync(companyId, token);
            }
            return(closing);
        }
Esempio n. 15
0
        public async Task <IEnumerable <ReceiptApportion> > GetAsync(IEnumerable <long> ids, CancellationToken token = default(CancellationToken))
        {
            var entities = (await receiptApportionQueryProcessor.GetApportionItemsAsync(ids, token)).ToArray();

            if (entities.Any(x => x.Apportioned == 0))
            {
                var companyId = entities.First().CompanyId;
                var app       = await applicationControlGetByCompanyQueryProcessor.GetAsync(companyId, token);

                var collation = await collationSettingGetByCompanyQueryProcessor.GetAsync(companyId, token);

                foreach (var receipt in entities.Where(x => x.Apportioned == 0))
                {
                    var customerId = receipt.CustomerId ?? receipt.RefCustomerId;
                    if (app?.UseReceiptSection == 1 && !receipt.SectionId.HasValue && customerId.HasValue)
                    {
                        var section = (await sectionQueryProcessor.GetAsync(new SectionSearch {
                            CustomerId = customerId.Value,
                        })).FirstOrDefault();
                        if (section != null)
                        {
                            receipt.SectionId   = section.Id;
                            receipt.SectionCode = section.Code;
                            receipt.SectionName = section.Name;
                        }
                    }
                    if (collation?.AutoAssignCustomer == 1 && !receipt.CustomerId.HasValue && customerId.HasValue)
                    {
                        receipt.CustomerId   = receipt.RefCustomerId;
                        receipt.CustomerCode = receipt.RefCustomerCode;
                        receipt.CustomerName = receipt.RefCustomerName;
                    }

                    if (collation?.UseApportionMenu == 1 && receipt.ExcludeFlag == 0 && !receipt.ExcludeCategoryId.HasValue)
                    {
                        var ignoreKana = (await ignoreKanaByCodeQueryProcessor.GetAsync(new IgnoreKana {
                            CompanyId = companyId,
                            Kana = receipt.PayerNameRaw,
                        }, token)).FirstOrDefault();
                        if (ignoreKana != null)
                        {
                            receipt.ExcludeFlag       = 1;
                            receipt.ExcludeCategoryId = ignoreKana.ExcludeCategoryId;
                            receipt.ExcludeAmount     = receipt.ReceiptAmount;
                        }
                    }
                }
            }
            return(entities);
        }
Esempio n. 16
0
        public async Task <IEnumerable <Collation> > CollateAsync(CollationSearch collationSearch,
                                                                  CancellationToken token    = default(CancellationToken),
                                                                  IProgressNotifier notifier = null)
        {
            var orders = (await getCollationOrderQueryProcessor.GetItemsAsync(collationSearch.CompanyId, token))
                         .Where(x => x.Available == 1)
                         .OrderBy(x => x.ExecutionOrder).ToArray();

            using (var scope = transactionScopeBuilder.Create())
            {
                var collationSetting = (await getCollationSettingQueryProcessor.GetAsync(collationSearch.CompanyId, token));
                collationSearch.SortOrderDirection = collationSetting.SortOrderDirection;

                await collationQueryProcessor.InitializeAsync(collationSearch, token);

                notifier?.UpdateState();

                foreach (var order in orders)
                {
                    switch (order.CollationTypeId)
                    {
                    case 0: await collationQueryProcessor.CollatePayerCodeAsync(collationSearch, token); break;

                    case 1: await collationQueryProcessor.CollateCustomerIdAsync(collationSearch, token); break;

                    case 2: await collationQueryProcessor.CollateHistoryAsync(collationSearch, token); break;

                    case 3: await collationQueryProcessor.CollatePayerNameAsync(collationSearch, token); break;

                    case 4: await collationQueryProcessor.CollateKeyAsync(collationSearch, token); break;
                    }
                    notifier?.UpdateState();
                }
                await collationQueryProcessor.CollateMissingAsync(collationSearch, token);

                notifier?.UpdateState();
                var items = await collationQueryProcessor.GetItemsAsync(collationSearch, token);

                notifier?.UpdateState();

                scope.Complete();
                return(items);
            }
        }
Esempio n. 17
0
        public async Task <IEnumerable <ExportFieldSetting> > GetAsync(ExportFieldSetting setting, CancellationToken token = default(CancellationToken))
        {
            var items = (await exportFieldSettingQueryProcessor.GetAsync(setting, token)).ToList();
            var app   = await applicationControlQueryProcessor.GetAsync(setting.CompanyId, token);

            foreach (var item in items)
            {
                if (app.UseForeignCurrency == 0 && item.ColumnName == "CurrencyCode")
                {
                    item.AllowExport = 0;
                }
                if (app.UseReceiptSection == 0 &&
                    (item.ColumnName == "SectionCode" || item.ColumnName == "SectionName"))
                {
                    item.AllowExport = 0;
                }
            }

            return(items);
        }
Esempio n. 18
0
        public async Task <byte[]> GetAsync(MatchingSequentialReportSource source, CancellationToken token = default(CancellationToken))
        {
            if (!(source.Items?.Any() ?? false))
            {
                return(null);
            }

            var companyTask = companyQueryProcessor.GetAsync(new CompanySearch {
                Id = source.CompanyId,
            }, token);
            var appConTask = applicationControlGetByCompanyQueryProcessor.GetAsync(source.CompanyId, token);

            await Task.WhenAll(companyTask, appConTask);

            var company = companyTask.Result.First();
            var appCon  = appConTask.Result;

            GrapeCity.ActiveReports.SectionReport report;
            if (source.PriorReceipt)
            {
                var reportTemp = new MatchingSequentialReceiptBillingSectionReport();
                reportTemp.SetBasicPageSetting(company.Code, company.Name);
                reportTemp.SetPageDataSetting(source.Items, true, appCon.UseForeignCurrency, source.Precision, null);

                report = reportTemp;
            }
            else
            {
                var reportTemp = new MatchingSequentialSectionReport();
                reportTemp.SetBasicPageSetting(company.Code, company.Name);
                reportTemp.SetPageDataSetting(source.Items, true, appCon.UseForeignCurrency, source.Precision, null);

                report = reportTemp;
            }

            report.Name = "一括消込チェックリスト" + DateTime.Today.ToString("yyyyMMdd");
            report.Run();

            return(report.Convert());
        }
Esempio n. 19
0
        public async Task <byte[]> GetAsync(ReceiptSearch option, CancellationToken token = default(CancellationToken))
        {
            var companyTask = companyQueryProcessor.GetAsync(new CompanySearch {
                Id = option.CompanyId,
            }, token);
            var appConTask = applicationControlGetByCompanyQueryProcessor.GetAsync(option.CompanyId, token);
            var gridTask   = gridSettingQueryProcessor.GetAsync(new GridSettingSearch {
                CompanyId = option.CompanyId, GridId = GridId.ReceiptSearch,
            }, token);
            var loadTask = receiptSearchQueryProcessor.GetAsync(option, token);

            await Task.WhenAll(companyTask, appConTask, gridTask, loadTask);

            var company      = companyTask.Result.First();
            var appCon       = appConTask.Result;
            var gridSettings = gridTask.Result.ToList();
            var items        = loadTask.Result.ToList();

            if (!items.Any())
            {
                return(null);
            }

            var useSection = appCon.UseReceiptSection == 1;
            var precition  = 0;

            var report = new ReceiptSearchSectionReport();

            report.SetBasicPageSetting(company.Code, company.Name);
            report.Name = "入金データ一覧" + DateTime.Today.ToString("yyyyMMdd");
            report.SetData(items, precition, useSection, option.DeleteFlg == 1, gridSettings);

            report.Run();

            return(report.Convert());
        }
        public async Task <byte[]> GetAsync(JournalizingOption option, CancellationToken token = default(CancellationToken))
        {
            var companyTask = companyQueryProcessor.GetAsync(new CompanySearch {
                Id = option.CompanyId,
            }, token);
            var appConTask = applicationControlGetByCompanyQueryProcessor.GetAsync(option.CompanyId, token);
            var nameTask   = columnNameSettingQueryProcessor.GetAsync(new ColumnNameSetting {
                CompanyId = option.CompanyId, TableName = nameof(Receipt),
            }, token);
            var loadTask = receiptJournalizingQueryProcessor.ExtractAsync(option, token);

            await Task.WhenAll(companyTask, appConTask, nameTask, loadTask);

            var company = companyTask.Result.First();
            var appCon  = appConTask.Result;
            var naming  = nameTask.Result.ToList();
            var items   = loadTask.Result.ToList();

            if (!items.Any())
            {
                return(null);
            }

            var report = new ReceiptJournalizingSectionReport();

            var reoutput = option.OutputAt?.Any() ?? false;
            var fileName = $"{(reoutput ? "再出力" : "")}入金仕訳{DateTime.Now:yyyyMMdd_HHmmss}";

            report.SetBasicPageSetting(company.Code, company.Name);
            report.Name = fileName;
            report.SetData(items, option.Precision, appCon.UseForeignCurrency == 1, naming);

            report.Run();

            return(report.Convert());
        }
Esempio n. 21
0
        public async Task <MatchingResult> MatchAsync(
            MatchingSource source,
            CancellationToken token    = default(CancellationToken),
            IProgressNotifier notifier = null)
        {
            var matchings        = source.Matchings;
            var loginUserId      = source.LoginUserId;
            var companyId        = source.CompanyId;
            var customerId       = source.CustomerId ?? 0;
            var paymentAgencyId  = source.PaymentAgencyId ?? 0;
            var childCustomerIds = source.ChildCustomerIds;
            var useKanaLearning  = source.UseKanaLearning == 1;
            var useFeeLearning   = source.UseFeeLearning == 1;

            var appControl = await applicationControlQueryProcessor.GetAsync(companyId, token);

            var updateAt = await dbSystemDateTimeQueryProcessor.GetAsync(token);

            source.UpdateAt = updateAt;

            var useAuthorization = appControl?.UseAuthorization == 1;
            var nettingReceipts  = new List <Receipt>();
            // DBサーバーから取得する

            var billings = new List <Billing>();
            var receipts = new List <Receipt>();
            var matchingBillingDiscounts = new List <MatchingBillingDiscount>();
            var billingScheduledIncomes  = new List <BillingScheduledIncome>();
            var billingDiscounts         = new HashSet <long>();

            MatchingResult validateResult = null;

            if (!(await ValidateMatchingDataAsync(source,
                                                  x => validateResult = x,
                                                  token)))
            {
                return(validateResult);
            }

            var currencyId = source.Matchings.First().CurrencyId;


            using (var scope = transactionScopeBuilder.Create())
            {
                #region 相殺データ変換
                nettingReceipts = await PrepareNettingDataAsync(source, loginUserId, updateAt, token);

                foreach (var r in nettingReceipts)
                {
                    var item = source.Receipts.First(x => x.Id == r.Id);
                    item.UpdateAt = r.UpdateAt;
                }
                #endregion

                #region matchingHeader
                var header = source.MatchingHeader;
                header.MatchingProcessType = 1;
                header.Approved            = useAuthorization ? 0 : 1;
                header.CreateBy            = loginUserId;
                header.UpdateBy            = loginUserId;
                header.CreateAt            = updateAt;
                header.UpdateAt            = updateAt;
                #endregion

                #region 手数料学習
                var bankFee = header.BankTransferFee;
                if (useFeeLearning)
                {
                    await SaveBankTransferFeeAsync(customerId, paymentAgencyId, currencyId, bankFee, updateAt, loginUserId, token);
                }
                #endregion

                #region 債権代表者登録
                if (childCustomerIds.Any())
                {
                    var isParent = 1;
                    await updateCustomerQueryProcessor.UpdateIsParentAsync(isParent, loginUserId, new[] { customerId }, token);

                    foreach (var childId in childCustomerIds)
                    {
                        var group = new CustomerGroup();
                        group.ParentCustomerId = customerId;
                        group.ChildCustomerId  = childId;
                        group.CreateAt         = updateAt;
                        group.CreateBy         = loginUserId;
                        group.UpdateAt         = updateAt;
                        group.UpdateBy         = loginUserId;
                        await addCustomerGroupQueryProcessor.SaveAsync(group, token);
                    }
                }
                #endregion

                #region  学習履歴の登録
                if (useKanaLearning)
                {
                    await SaveKanaLearningAsync(matchings, companyId, customerId, paymentAgencyId, loginUserId, updateAt);
                }
                #endregion

                var matchingResult = await matchingSaveProcessor.SaveAsync(source, appControl, token);

                if (matchingResult.ProcessResult.Result)
                {
                    scope.Complete();
                }

                matchingResult.NettingReceipts = nettingReceipts;

                return(matchingResult);
            }
        }
Esempio n. 22
0
 public async Task <ClosingSetting> GetAsync(int companyId, CancellationToken token = default(CancellationToken))
 => await closingSettingGetByCompanyIdQueryProcessor.GetAsync(companyId, token);
Esempio n. 23
0
        public async Task <MatchingSource> SolveAsync(
            MatchingSource source,
            CollationSearch option,
            ApplicationControl control = null,
            CancellationToken token    = default(CancellationToken))
        {
            if (control == null)
            {
                control = await applicationControlQueryProcessor.GetAsync(option.CompanyId, token);
            }

            var useCashOnDueDates       = control.UseCashOnDueDates;
            var useScheduledPayment     = control.UseScheduledPayment;
            var useDeclaredAmount       = control.UseDeclaredAmount;
            int?doCreateAdvanceReceived = option.DoTransferAdvanceReceived ? 1 : 0;
            var taxDifference           = source.TaxDifference;
            var bankTransferFee         = source.BankTransferFee;


            var billingItems = source.Billings;
            var receiptItems = source.Receipts;

            if (!(billingItems?.Any() ?? false))
            {
                throw new ArgumentNullException("Billings");
            }

            if (!(receiptItems?.Any() ?? false))
            {
                throw new ArgumentNullException("Receipts");
            }

            int companyId;
            int currencyId;
            {
                var billing = billingItems.First();
                companyId  = billing.CompanyId;
                currencyId = billing.CurrencyId;
            }

            var isAllMinusBilling = true;
            var billingTotal      = 0M;

            var billingPair = GetBillingPair(billingItems, useScheduledPayment, useDeclaredAmount,
                                             ref doCreateAdvanceReceived, ref billingTotal, ref isAllMinusBilling);

            var isAllMinusReceipt = true;
            var receiptTotal      = 0M;
            var receiptPair       = GetReceiptPair(receiptItems, ref receiptTotal, ref isAllMinusReceipt);

            var isAllMinus = isAllMinusBilling && isAllMinusReceipt;
            var taxDiff    = taxDifference;
            var bankFee    = bankTransferFee;
            var isEqual    = (billingTotal == receiptTotal + bankFee - taxDiff);
            Func <decimal, decimal, decimal> amountSolver = Math.Min;

            if (isAllMinus)
            {
                amountSolver = Math.Max;
            }
            var header = new MatchingHeader
            {
                Id              = 1,
                CompanyId       = companyId,
                CurrencyId      = currencyId,
                BankTransferFee = bankFee,
                TaxDifference   = taxDiff,
            };

            var recordedAt = option.AdvanceReceivedRecordedAt;

            var matchings = new List <Matching>();
            var billingScheduledIncomes  = new List <BillingScheduledIncome>();
            var matchingBillingDiscounts = new List <MatchingBillingDiscount>();
            var billingDiscounts         = new HashSet <long>();
            var discountTotal            = 0M;
            var beforBillingRemainTotal  = 0M;
            var beforReceiptRemainTotal  = 0M;

            var     bindex      = 0;
            var     rindex      = 0;
            var     nextBilling = true;
            var     nextReceipt = true;
            Billing bill        = null;
            Receipt rcpt        = null;

            while (bindex < billingItems.Count &&
                   rindex < receiptItems.Count &&
                   (nextBilling || nextReceipt))
            {
                if (token.IsCancellationRequested)
                {
                    throw new OperationCanceledException();
                }

                if (nextBilling)
                {
                    bill = billingItems[bindex];
                }
                if (nextReceipt)
                {
                    rcpt = receiptItems[rindex];
                }
                var isLastBill = bindex == billingItems.Count - 1;
                var isLastRcpt = rindex == receiptItems.Count - 1;

                var discount    = bill.DiscountAmount;
                var billTaxDiff = (0M < taxDiff) ? taxDiff : 0M;
                var rcptTaxDiff = (0M < taxDiff) ? 0M : -taxDiff;

                var matching = new Matching();
                matching.Id               = matchings.Count;
                matching.CompanyId        = companyId;
                matching.CurrencyId       = currencyId;
                matching.MatchingHeaderId = header.Id;
                matching.ReceiptId        = rcpt.NettingId ?? rcpt.Id;
                matching.PayerName        = rcpt.PayerName;
                matching.SourceBankName   = rcpt.SourceBankName;
                matching.SourceBranchName = rcpt.SourceBranchName;
                matching.IsNetting        = rcpt.NettingId.HasValue;
                matching.RecordedAt       = (rcpt.OriginalReceiptId.HasValue ? recordedAt : null) ?? rcpt.RecordedAt;
                matching.ReceiptHeaderId  = rcpt.ReceiptHeaderId;
                if (useCashOnDueDates == 1 && rcpt.UseCashOnDueDates == 1)
                {
                    matching.UseCashOnDueDates = 1;
                }

                matching.BillingId = bill.Id;
                if (useScheduledPayment == 1 && useDeclaredAmount == 1)
                {
                    matching.OffsetAmount = bill.OffsetAmount;
                }

                if (discount != 0M)
                {
                    #region billing discount
                    matching.DiscountAmount1 = bill.DiscountAmount1;
                    matching.DiscountAmount2 = bill.DiscountAmount2;
                    matching.DiscountAmount3 = bill.DiscountAmount3;
                    matching.DiscountAmount4 = bill.DiscountAmount4;
                    matching.DiscountAmount5 = bill.DiscountAmount5;
                    if (!billingDiscounts.Contains(bill.Id))
                    {
                        billingDiscounts.Add(bill.Id);
                    }
                    matchingBillingDiscounts.AddRange(ConvertBillingToDiscounts(bill, matching.Id));
                    discountTotal       += discount;
                    bill.DiscountAmount  = 0M;
                    bill.DiscountAmount1 = 0M;
                    bill.DiscountAmount2 = 0M;
                    bill.DiscountAmount3 = 0M;
                    bill.DiscountAmount4 = 0M;
                    bill.DiscountAmount5 = 0M;
                    #endregion
                }
                matching.BankTransferFee = bankFee;
                matching.TaxDifference   = taxDiff;
                matching.Memo            = bill.Memo;
                var billAmount = billingPair[bindex] - rcptTaxDiff - bankFee - discount;
                var rcptAmount = receiptPair[rindex] - billTaxDiff;

                matching.Amount
                    = (isEqual && isLastRcpt && !isLastBill) ? billAmount
                    : (isEqual && !isLastRcpt && isLastBill) ? rcptAmount
                    : amountSolver(billAmount, rcptAmount);

                header.Amount += matching.Amount;

                if (matching.Amount == 0M && taxDiff == 0M && bankFee == 0M && discount == 0M)
                {
                    break;
                }

                var billAssignAmount = (matching.Amount + rcptTaxDiff + bankFee + discount);
                var rcptAssignAmount = (matching.Amount + billTaxDiff);
                if (nextBilling)
                {
                    beforBillingRemainTotal += bill.RemainAmount;
                    bill.AssignmentAmount    = billAssignAmount;
                }
                else
                {
                    bill.AssignmentAmount += billAssignAmount;
                }

                if (nextReceipt)
                {
                    beforReceiptRemainTotal += rcpt.RemainAmount;
                    rcpt.AssignmentAmount    = rcptAssignAmount;
                }
                else
                {
                    rcpt.AssignmentAmount += rcptAssignAmount;
                }

                billingPair[bindex] -= billAssignAmount;
                receiptPair[rindex] -= rcptAssignAmount;

                nextBilling = billingPair[bindex] == 0M && !isLastBill;
                nextReceipt = receiptPair[rindex] == 0M && !isLastRcpt;

                matchings.Add(matching);


                if (!isEqual)
                {
                    if (!nextBilling && isLastBill && receiptPair[rindex] > 0M && !rcpt.OriginalReceiptId.HasValue)
                    {
                        matching.AdvanceReceivedOccured = 1;
                    }
                    if (!nextBilling && isLastBill && receiptPair[rindex] != 0M)
                    {
                        foreach (var m in matchings.Where(x => x.ReceiptId == rcpt.Id))
                        {
                            m.ReceiptRemain = receiptPair[rindex];
                        }
                    }
                    if (!nextReceipt && isLastRcpt && billingPair[bindex] != 0M)
                    {
                        foreach (var m in matchings.Where(x => x.BillingId == bill.Id))
                        {
                            m.BillingRemain = billingPair[bindex];
                        }
                    }
                    if (billingPair[bindex] == 0M && isLastBill ||
                        receiptPair[rindex] == 0M && isLastRcpt)
                    {
                        break;
                    }
                }

                if (nextBilling)
                {
                    bindex++;
                }
                if (nextReceipt)
                {
                    rindex++;
                }

                taxDiff = 0M;
                bankFee = 0M;
            }

            var remainType = 0;

            var billingRemainTotal = billingPair.Sum(x => x.Value);
            var receiptRemainTotal = receiptPair.Sum(x => x.Value);
            if (billingRemainTotal == 0M && receiptRemainTotal == 0M)
            {
                remainType = 0;
            }
            else if (billingRemainTotal != 0M)
            {
                remainType = 1;
            }
            else
            {
                if (!rcpt.OriginalReceiptId.HasValue &&
                    option.UseAdvanceReceived &&
                    receiptPair[rindex] > 0M)
                {
                    remainType = 3;
                }
                else
                {
                    remainType = 2;
                }
            }

            if (useCashOnDueDates == 1)
            {
                billingScheduledIncomes.AddRange(ConvertMatchingToScheduled(matchings));
            }


            billingItems        = billingItems.Take(bindex + 1).ToList();
            receiptItems        = receiptItems.Take(rindex + 1).ToList();
            header.BillingCount = billingItems.Count;
            header.ReceiptCount = receiptItems.Count;

            if (token.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }

            return(new MatchingSource
            {
                RemainType = remainType,
                Matchings = matchings,
                Billings = billingItems,
                Receipts = receiptItems,
                BillingDiscounts = billingDiscounts,
                MatchingBillingDiscounts = matchingBillingDiscounts,
                MatchingHeader = header,
                BillingScheduledIncomes = billingScheduledIncomes,
                BillingRemainTotal = beforBillingRemainTotal,
                ReceiptRemainTotal = beforReceiptRemainTotal,
                BillingDiscountTotal = discountTotal
            });
        }
Esempio n. 24
0
        public async Task <MatchingResult> SaveAsync(
            MatchingSource source,
            ApplicationControl applicationControl,
            CancellationToken token = default(CancellationToken))
        {
            var companyId = source.Billings.First().CompanyId;

            if (applicationControl == null)
            {
                applicationControl = await applicationControlQueryProcessor.GetAsync(companyId, token);
            }

            var billings  = source.Billings;
            var receipts  = source.Receipts;
            var matchings = source.Matchings;
            var header    = source.MatchingHeader;
            var matchingBillingDiscounts = source.MatchingBillingDiscounts;
            var billingDiscounts         = source.BillingDiscounts;
            var billingScheduledIncomes  = source.BillingScheduledIncomes;
            var loginUserId               = source.LoginUserId;
            var updateAt                  = source.UpdateAt;
            var matchingProcessType       = source.MatchingProcessType;
            var customerId                = source.CustomerId;
            var paymentAgencyId           = source.PaymentAgencyId;
            var advanceReceivedCustomerId = source.AdvanceReceivedCustomerId;

            var matchingResults        = new List <Matching>();
            var advanceReceivedResults = new List <AdvanceReceived>();
            var clientKey = source.ClientKey;

            foreach (var billing in billings)
            {
                billing.UpdateBy    = loginUserId;
                billing.NewUpdateAt = updateAt;
                if (applicationControl.UseDeclaredAmount == 0)
                {
                    billing.OffsetAmount = 0;
                }
                var result = await addMatchingQueryProcessor.UpdateBillingForMatchingAsync(billing, token);

                if (result != 1)
                {
                    return new MatchingResult {
                               MatchingErrorType = MatchingErrorType.BillingRemainChanged
                    }
                }
                ;
            }

            foreach (var receipt in receipts)
            {
                receipt.UpdateBy    = loginUserId;
                receipt.NewUpdateAt = updateAt;
                var result = await addMatchingQueryProcessor.UpdateReceiptForMatchingAsync(receipt, token);

                if (result != 1)
                {
                    return new MatchingResult {
                               MatchingErrorType = MatchingErrorType.ReceiptRemainChanged
                    }
                }
                ;
                if (receipt.ReceiptHeaderId.HasValue)
                {
                    var receiptHeaderId = receipt.ReceiptHeaderId.Value;

                    await matchingQueryProcessor.UpdateReceiptHeaderAsync(receiptHeaderId, loginUserId, updateAt, token);
                }
            }

            header.MatchingProcessType = matchingProcessType;
            header.CustomerId          = customerId;
            header.PaymentAgencyId     = paymentAgencyId;
            header.Memo     = header.Memo ?? string.Empty;
            header.Approved = (applicationControl.UseAuthorization == 1) ? 0 : 1;
            header.CreateBy = loginUserId;
            header.UpdateBy = loginUserId;
            header.CreateAt = updateAt;
            header.UpdateAt = updateAt;

            var headerResult = await addMatchingQueryProcessor.SaveMatchingHeaderAsync(header, token);

            if (headerResult == null)
            {
                return new MatchingResult {
                           MatchingErrorType = MatchingErrorType.DBError
                }
            }
            ;

            var advanceRecievedReciptId = new HashSet <long>();

            foreach (var matching in matchings)
            {
                matching.MatchingHeaderId = headerResult.Id;

                matching.CreateBy = loginUserId;
                matching.CreateAt = updateAt;
                matching.UpdateBy = loginUserId;
                matching.UpdateAt = updateAt;
                if (!advanceReceivedCustomerId.HasValue &&
                    matching.AdvanceReceivedOccured == 1)
                {
                    matching.AdvanceReceivedOccured = 0;
                }

                var matchingResult = await addMatchingQueryProcessor.SaveMatchingAsync(matching, token);

                matchingResults.Add(matchingResult);

                if (applicationControl.UseDiscount == 1)
                {
                    foreach (var matchingBillingDiscount in matchingBillingDiscounts.Where(x => x.MatchingId == matching.Id))
                    {
                        matchingBillingDiscount.MatchingId = matchingResult.Id;
                        await addMatchingBillingDiscountQueryProcessor.SaveAsync(matchingBillingDiscount, token);
                    }
                }

                if (advanceReceivedCustomerId.HasValue &&
                    matching.ReceiptRemain > 0M &&
                    !advanceRecievedReciptId.Contains(matching.ReceiptId))
                {
                    var originalReceiptId = matching.ReceiptId;
                    advanceRecievedReciptId.Add(originalReceiptId);

                    var receiptItem = receipts.Find(item => (item.Id == originalReceiptId));
                    if (matchingProcessType == 1 && advanceReceivedCustomerId != 0)
                    {
                        receiptItem.CustomerId = advanceReceivedCustomerId;
                    }
                    var advReceipt = await addReceiptQueryProcessor.AddAdvanceReceivedAsync(
                        originalReceiptId, advanceReceivedCustomerId, loginUserId, updateAt, updateAt, token);

                    if (advReceipt != null)
                    {
                        advanceReceivedResults.Add(new AdvanceReceived
                        {
                            ReceiptId         = advReceipt.Id,
                            OriginalReceiptId = advReceipt.OriginalReceiptId.Value,
                            UpdateAt          = advReceipt.UpdateAt,
                            ReceiptCategoryId = advReceipt.ReceiptCategoryId,
                            LoginUserId       = advReceipt.UpdateBy,
                        });
                        var receipt = (await matchingQueryProcessor.SearchReceiptByIdAsync(new long[] { advReceipt.Id }, token)).First();
                        await matchingQueryProcessor.SaveWorkReceiptTargetAsync(clientKey, receipt.Id,
                                                                                receipt.CompanyId, receipt.CurrencyId, receipt.PayerName,
                                                                                receipt.BankCode, receipt.BranchCode, receipt.PayerCode,
                                                                                receipt.SourceBankName, receipt.SourceBranchName, receipt.CollationKey, receipt.CustomerId,
                                                                                token);

                        await matchingQueryProcessor.SaveWorkCollationAsync(clientKey, advReceipt.Id, customerId ?? 0, paymentAgencyId ?? 0, advanceReceivedCustomerId ?? 0,
                                                                            receipt.PayerName, receipt.PayerCode,
                                                                            receipt.BankCode, receipt.BranchCode,
                                                                            receipt.SourceBankName, receipt.SourceBranchName, receipt.CollationKey, receipt.ReceiptAmount,
                                                                            token);
                    }

                    await updateReceiptQueryProcessor.UpdateOriginalRemainAsync(originalReceiptId, loginUserId, updateAt, token);

                    if (matchingResult != null)
                    {
                        var advanceReceipt_matching = matching;
                        advanceReceipt_matching.Id = matchingResult.Id;
                        await addMatchingQueryProcessor.UpdateMatchingAsync(advanceReceipt_matching, token);
                    }
                }

                #region 期日入金データ消込
                if (matching.UseCashOnDueDates == 1)
                {
                    Billing b = null;
                    Receipt r = null;
                    if (matchingProcessType == 0)
                    {
                        b = billings.FirstOrDefault(x => x.Id == matching.BillingId);
                        r = receipts.FirstOrDefault(x => x.Id == matching.ReceiptId);
                    }
                    else
                    {
                        b = await billingGetByIdQueryProcessor.GetByIdAsync(matching.BillingId, token);

                        r = await receiptGetByIdQueryProcessor.GetByIdAsync(matching.ReceiptId, token);
                    }
                    var newbill = b.ConvertScheduledIncome(r, matching.Amount);
                    newbill.CreateBy = loginUserId;
                    newbill.CreateAt = updateAt;
                    newbill.UpdateBy = loginUserId;
                    newbill.UpdateAt = updateAt;
                    var scheduled_billing_result = await addMatchingQueryProcessor.SaveMatchingBillingAsync(newbill, token);

                    foreach (var income in billingScheduledIncomes.Where(x => x.MatchingId == matching.Id))
                    {
                        income.BillingId  = scheduled_billing_result.Id;
                        income.MatchingId = matchingResult.Id;
                        income.CreateBy   = loginUserId;
                        income.CreateAt   = updateAt;
                        await addBillingScheduledIncomeQueryProcessor.SaveAsync(income);
                    }
                }
                #endregion
            }

            if (applicationControl.UseDiscount == 1) //歩引き対応
            {
                foreach (var billingId in billingDiscounts)
                {
                    await updateBillingDiscountQueryProcessor.UpdateAssignmentFlagAsync(billingId, AssignmentFlag : 1, token : token);
                }
            }
            return(new MatchingResult
            {
                ProcessResult = new ProcessResult {
                    Result = true
                },
                Matchings = matchingResults,
                AdvanceReceiveds = advanceReceivedResults,
            });
        }
    }
}
Esempio n. 25
0
        public async Task <MatchingResult> MatchAsync(
            IEnumerable <Collation> collations,
            CollationSearch option,
            CancellationToken token    = default(CancellationToken),
            IProgressNotifier notifier = null)
        {
            var appControl = await applicationControlQueryProcessor.GetAsync(option.CompanyId, token);

            var nettingReceipts = new List <Receipt>();

            var updateAt = await dbSystemDateTimeQueryProcessor.GetAsync(token);

            var matchingOrders = await matchingOrderQueryProcessor.GetItemsAsync(option.CompanyId, token);

            var matchingBillingOrder = matchingOrders.Where(x => x.TransactionCategory == 1 && x.Available == 1).ToArray();
            var matchingReceiptOrder = matchingOrders.Where(x => x.TransactionCategory == 2 && x.Available == 1).ToArray();

            var            matchings        = new List <Matching>();
            var            advanceReceiveds = new List <AdvanceReceived>();
            List <Billing> billings         = null;
            List <Netting> nettings         = null;
            List <Receipt> receipts         = null;
            var            index            = 0;

            using (var scope = transactionScopeBuilder.Create())
            {
                foreach (var collation in collations)
                {
                    // 請求データ取得
                    var billingSearchOption = new MatchingBillingSearch
                    {
                        ClientKey        = option.ClientKey,
                        ParentCustomerId = collation.CustomerId,
                        PaymentAgencyId  = collation.PaymentAgencyId,
                        CurrencyId       = collation.CurrencyId,
                    };

                    billings = (await matchingQueryProcessor.GetBillingsForSequentialMatchingAsync(billingSearchOption, matchingBillingOrder, token)).ToList();
                    var billingAmount = billings.Sum(item => (item.RemainAmount - item.DiscountAmount - item.OffsetAmount));
                    var billingCount  = billings.Count;

                    // 請求データチェック
                    if (billingAmount != collation.BillingAmount ||
                        billingCount != collation.BillingCount)
                    {
                        notifier?.Abort();
                        return(new MatchingResult
                        {
                            MatchingErrorType = MatchingErrorType.BillingRemainChanged,
                            ErrorIndex = index,
                        });
                    }

                    // 相殺データ取得
                    nettings = (await matchingQueryProcessor.SearchMatchingNettingAsync(option, collation, token)).ToList();

                    // 相殺データ登録
                    var createdReceipstFromNetting = new List <Receipt>();
                    foreach (var netting in nettings)
                    {
                        var receipt        = netting.ConvertToReceiptInput(option.LoginUserId, updateAt);
                        var nettingReceipt = await matchingQueryProcessor.SaveMatchingReceiptAsync(receipt, token);

                        if (!string.IsNullOrEmpty(netting.ReceiptMemo))
                        {
                            await addReceiptMemoQueryProcessor.SaveAsync(nettingReceipt.Id, netting.ReceiptMemo, token);
                        }
                        netting.ReceiptId = nettingReceipt.Id;
                        createdReceipstFromNetting.Add(nettingReceipt);
                    }

                    // 入金データ取得
                    var receiptSearch = new MatchingReceiptSearch
                    {
                        ClientKey           = option.ClientKey,
                        CompanyId           = option.CompanyId,
                        CurrencyId          = collation.CurrencyId,
                        ParentCustomerId    = collation.CustomerId,
                        PaymentAgencyId     = collation.PaymentAgencyId,
                        UseScheduledPayment = appControl.UseScheduledPayment,
                    };

                    receipts = (await matchingQueryProcessor.GetReceiptsForSequentialMatchingAsync(receiptSearch, matchingReceiptOrder, token)).ToList();

                    var receiptAmount      = receipts.Sum(item => (item.RemainAmount));
                    var receiptCount       = receipts.Count();
                    var hasAdvanceReceived = receipts.Exists(item => item.UseAdvanceReceived == 1);

                    // 入金データチェック
                    if (receiptAmount != collation.ReceiptAmount ||
                        receiptCount != collation.ReceiptCount)
                    {
                        notifier?.Abort();
                        return(new MatchingResult
                        {
                            MatchingErrorType = MatchingErrorType.ReceiptRemainChanged,
                            ErrorIndex = index,
                        });
                    }

                    foreach (var netting in nettings)
                    {
                        await updateNettingQueryProcessor.UpdateMatchingNettingAsync(netting.CompanyId, netting.ReceiptId.Value, netting.Id, CancelFlg : 0, token : token);

                        foreach (var receipt in receipts
                                 .Where(x => x.NettingId.HasValue && x.NettingId == netting.Id))
                        {
                            receipt.Id = netting.ReceiptId.Value;
                        }
                    }

                    // 前受処理日付取得
                    var recordedAt = option.GetRecordedAt(hasAdvanceReceived ? billings : null);
                    option.AdvanceReceivedRecordedAt = recordedAt;

                    var requestSource = new MatchingSource
                    {
                        Billings        = billings,
                        Receipts        = receipts,
                        BankTransferFee = collation.BankTransferFee,
                        TaxDifference   = collation.TaxDifference,
                    };
                    var source = await matchingSolveProcessor.SolveAsync(requestSource, option, appControl, token);

                    foreach (var netting in nettings)
                    {
                        foreach (var matching in source.Matchings.Where(x => x.IsNetting && x.ReceiptId == netting.Id))
                        {
                            matching.ReceiptId = netting.ReceiptId.Value;
                        }
                    }

                    if (collation.UseFeeLearning == 1 && collation.BankTransferFee != 0M)
                    {
                        await SaveBankTransferFeeAsync(collation, option, updateAt, token);
                    }

                    // データの更新処理
                    int?customerId = collation.CustomerId;
                    if (customerId == 0)
                    {
                        customerId = null;
                    }

                    int?paymentAgencyId = collation.PaymentAgencyId;
                    if (paymentAgencyId == 0)
                    {
                        paymentAgencyId = null;
                    }

                    source.LoginUserId               = option.LoginUserId;
                    source.UpdateAt                  = updateAt;
                    source.MatchingProcessType       = 0;
                    source.CustomerId                = customerId;
                    source.PaymentAgencyId           = paymentAgencyId;
                    source.AdvanceReceivedCustomerId = option.DoTransferAdvanceReceived ? customerId : null;
                    source.ClientKey                 = option.ClientKey;

                    foreach (var r in createdReceipstFromNetting)
                    {
                        var item = receipts.First(x => x.Id == r.Id);
                        item.UpdateAt = r.UpdateAt;
                    }

                    var matchingResult = await matchingSaveProcessor.SaveAsync(source, appControl, token);

                    if (!matchingResult.ProcessResult.Result)
                    {
                        notifier?.Abort();
                        return(matchingResult);
                    }
                    matchings.AddRange(matchingResult.Matchings);
                    advanceReceiveds.AddRange(matchingResult.AdvanceReceiveds);
                    nettingReceipts.AddRange(createdReceipstFromNetting);

                    notifier?.UpdateState();
                    index++;
                }

                scope.Complete();
            }


            return(new MatchingResult
            {
                ProcessResult = new ProcessResult {
                    Result = true
                },
                Matchings = matchings,
                AdvanceReceiveds = advanceReceiveds,
                NettingReceipts = nettingReceipts
            });
        }
 public async Task <BillingDivisionSetting> GetAsync(int CompanyId, CancellationToken token = default(CancellationToken))
 => await billingDivisionSettingQueryProcessor.GetAsync(CompanyId, token);
Esempio n. 27
0
        public async Task <ImportResult> ImportAsync(
            IEnumerable <LoginUser> InsertList,
            IEnumerable <LoginUser> UpdateList,
            IEnumerable <LoginUser> DeleteList, CancellationToken token = default(CancellationToken))
        {
            using (var scope = transactionScopeBuilder.Create())
            {
                var deleteCount = 0;
                var updateCount = 0;
                var insertCount = 0;


                var first = InsertList.FirstOrDefault() ??
                            UpdateList.FirstOrDefault() ??
                            DeleteList.FirstOrDefault();
                if (first == null)
                {
                    throw new ArgumentNullException($"{nameof(InsertList)} or {nameof(UpdateList)}");
                }

                var companyId   = first.CompanyId;
                var loginUserId = first.UpdateBy;

                var isNotUseDistribution = (await applicationControlByCompanyId.GetAsync(companyId, token)).UseDistribution == 0;

                foreach (var delete in DeleteList)
                {
                    await deleteIdenticalQueryProcessor.DeleteAsync(delete.Id, token);

                    deleteCount++;
                }

                foreach (var update in UpdateList)
                {
                    if (isNotUseDistribution)
                    {
                        update.UseClient = 1;
                    }
                    await addLoginUserQueryProcessor.SaveAsync(update);

                    updateCount++;
                }

                foreach (var add in InsertList)
                {
                    if (isNotUseDistribution)
                    {
                        add.UseClient = 1;
                    }
                    var saveResult = await addLoginUserQueryProcessor.SaveAsync(add);

                    if (saveResult != null && !string.IsNullOrEmpty(add.InitialPassword))
                    {
                        await loginUserPasswordProcessor.SaveAsync(saveResult.CompanyId, saveResult.Id, add.InitialPassword);
                    }
                    insertCount++;
                }

                var result = new ImportResultLoginUser
                {
                    ProcessResult = new ProcessResult {
                        Result = true
                    },
                    InsertCount = insertCount,
                    UpdateCount = updateCount,
                    DeleteCount = deleteCount,
                };

                await ValidateLicenses(result, companyId, loginUserId, token);

                if (!(result.LicenseIsOrver || result.NotExistsLoginUser || result.LoginUserHasNotLoginLicense))
                {
                    scope.Complete();
                }

                return(result);
            }
        }
        public async Task <byte[]> GetAsync(BillingAgingListSearch option, IProgressNotifier notifier = null, CancellationToken token = default(CancellationToken))
        {
            var companyTask = companyQueryProcessor.GetAsync(new CompanySearch {
                Id = option.CompanyId,
            }, token);
            var appConTask  = applicationControlGetByCompanyQueryProcessor.GetAsync(option.CompanyId, token);
            var settingTask = reportSettingQueryProcessor.GetAsync(option.CompanyId, ReportId, token);
            var loadTask    = billingAgingListProcessor.GetAsync(option, notifier, token);


            var tasks = new List <Task> {
                companyTask, appConTask, settingTask, loadTask
            };

            Task <IEnumerable <Currency> > currenciesTask = null;

            if (option.CurrencyId.HasValue)
            {
                currenciesTask = currencyGetByIdsQueryProcessor.GetByIdsAsync(new[] { option.CurrencyId.Value }, token);
                tasks.Add(currenciesTask);
            }
            await Task.WhenAll(tasks);

            var company   = companyTask.Result.First();
            var appCon    = appConTask.Result;
            var settings  = settingTask.Result.ToList();
            var items     = loadTask.Result.ToList();
            var precition = currenciesTask?.Result.FirstOrDefault().Precision ?? 0;

            if (!items.Any())
            {
                return(null);
            }

            var remianType  = settings.GetReportSetting <ReportAdvanceReceivedType>(BillingRemainType);
            var displayCode = settings.GetReportSetting <ReportDoOrNot>(DisplayCustomerCode) == ReportDoOrNot.Do;


            var processor = remianType == ReportAdvanceReceivedType.UseMatchingAmount ?
                            (IProcessor) new BillingAgingListDocumentProcessor {
                Company             = company,
                Items               = items,
                Option              = option,
                Precision           = precition,
                DisplayCustomerCode = displayCode,
                UseForeignCurrency  = appCon.UseForeignCurrency == 1,
            } : new BillingAgingListReceiptDocumentProcessor {
                Company             = company,
                Items               = items,
                Option              = option,
                Precision           = precition,
                DisplayCustomerCode = displayCode,
                UseForeignCurrency  = appCon.UseForeignCurrency == 1,
            };

            using (var stream = new MemoryStream())
            {
                using (var document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
                {
                    processor.Process(document);
                }
                return(stream.ToArray());
            }
        }
Esempio n. 29
0
        public async Task <MatchingResult> CancelAsync(IEnumerable <MatchingHeader> headers, int loginUserId,
                                                       CancellationToken token    = default(CancellationToken),
                                                       IProgressNotifier notifier = null)
        {
            var headersArray = headers.ToArray();

            var updateAt = await dbSystemDatetimeQueryProcessor.GetAsync(token);

            List <Matching> details  = null;
            List <Billing>  billings = null;
            List <Receipt>  receipts = null;

            var deleteMatchings = new List <Matching>();
            var deleteReceipts  = new List <Receipt>();

            var companyId  = headers.Select(x => x.CompanyId).First();
            var appControl = await applicationControlGetByCompanyIdQueryProcessor.GetAsync(companyId, token);

            var useCashOnDueDates = appControl.UseCashOnDueDates == 1;

            using (var scope = transactionScopeBuilder.Create())
            {
                foreach (var header in headers)
                {
                    if (token.IsCancellationRequested)
                    {
                        return new MatchingResult {
                                   MatchingErrorType = MatchingErrorType.ProcessCanceled
                        }
                    }
                    ;

                    #region 1.消込データ(Matching)取得

                    details = (await cancelMatchingQueryProcessor.GetByHeaderIdAsync(header.Id, token)).ToList();

                    deleteMatchings.AddRange(details);

                    #endregion

                    #region 2.消込済請求データ取得
                    // billing deleteAt など matching 以外の情報が必要なので、 query で呼び出し必須
                    billings = (await cancelMatchingQueryProcessor.GetMatchedBillingsForCancelAsync(header.Id, token)).ToList();

                    #endregion

                    if (billings.Count == 0)
                    {
                        notifier?.Abort();

                        return(new MatchingResult {
                            MatchingErrorType = MatchingErrorType.NotExistBillingData
                        });
                    }

                    //3.請求データチェック

                    if (billings.Any(e => e.DeleteAt.HasValue))
                    {
                        notifier?.Abort();
                        return(new MatchingResult
                        {
                            MatchingErrorType = MatchingErrorType.BillingOmitted,
                            ErrorIndex = Array.IndexOf(headersArray, header),
                        });
                    }

                    if (useCashOnDueDates &&
                        await cancelMatchingQueryProcessor.ExistAssignmentScheduledIncomeAsync(details.Select(x => x.Id).ToArray(), token))
                    {
                        notifier?.Abort();
                        return(new MatchingResult
                        {
                            MatchingErrorType = MatchingErrorType.CashOnDueDateOmitted,
                            ErrorIndex = Array.IndexOf(headersArray, header),
                        });
                    }

                    #region 4.請求データ消込解除処理

                    // 期日現金管理用 請求ID -> 消込ID の Dictionary
                    Dictionary <long, long[]> billingIdToMatchingIds = null;
                    if (useCashOnDueDates)
                    {
                        billingIdToMatchingIds = details.GroupBy(x => x.BillingId)
                                                 .ToDictionary(x => x.Key, x => x.Select(y => y.Id).ToArray());
                    }

                    foreach (var billing in billings)
                    {
                        var item           = billing;
                        var matchingAmount = billing.AssignmentAmount;
                        var bankFee        = billing.BankTransferFee;
                        var taxDiff        = billing.TaxDifference;
                        var discount       = billing.DiscountAmount;
                        var amount         = matchingAmount + bankFee + discount - (taxDiff < 0 ? taxDiff : 0M);

                        item.CompanyId        = header.CompanyId;
                        item.RemainAmount     = amount;
                        item.AssignmentAmount = amount;
                        item.UpdateBy         = loginUserId;
                        item.UpdateAt         = updateAt;

                        var updatedBilling = await cancelMatchingQueryProcessor.UpdateBillingForCancelMatchingAsync(item, token);

                        if (updatedBilling == null)
                        {
                            notifier?.Abort();
                            return(new MatchingResult {
                                MatchingErrorType = MatchingErrorType.CancelError
                            });
                        }

                        await cancelMatchingQueryProcessor.UpdatePreviousBillingLogsAsync(header.Id, billing.Id, amount, loginUserId, updateAt, token);

                        if (useCashOnDueDates)
                        {
                            foreach (var matchingId in billingIdToMatchingIds[billing.Id])
                            {
                                var income = await cancelMatchingQueryProcessor.GetBillingScheduledIncomeAsync(matchingId, token);

                                if (income != null)
                                {
                                    await cancelMatchingQueryProcessor.DeleteBillingShceduledIncomeAsync(income.BillingId, token);

                                    await deleteBillingByIdQueryProcessor.DeleteAsync(income.BillingId, token);
                                }
                            }
                        }
                    }

                    #endregion

                    #region 5.相殺データ消込解除処理

                    var nettings          = (await nettingQueryProcessor.GetByMatchingHeaderIdAsync(header.Id, token)).ToList();
                    var nettingReceiptIds = new List <long>();
                    foreach (var netting in nettings)
                    {
                        nettingReceiptIds.Add((long)netting.ReceiptId);
                        var cancelFlag = 1;
                        await updateNettingQueryProcessor.UpdateMatchingNettingAsync(header.CompanyId, 0, netting.Id, cancelFlag, token);
                    }

                    if (nettings.Any())
                    {
                        var receiptsForNetting = await receiptGetByIdsQueryProcessor.GetByIdsAsync(nettings.Select(n => (long)n.ReceiptId), token);

                        deleteReceipts.AddRange(receiptsForNetting);
                    }
                    #endregion

                    #region 7.消込済入金データ取得

                    receipts = (await cancelMatchingQueryProcessor.GetMatchedReceiptsForCancelAsync(header, token)).ToList();

                    #endregion

                    if (receipts.Count == 0)
                    {
                        notifier?.Abort();
                        return(new MatchingResult {
                            MatchingErrorType = MatchingErrorType.NotExistReceiptData
                        });
                    }

                    #region 8.入金データチェック

                    if (receipts.Any(e => e.DeleteAt.HasValue))
                    {
                        notifier?.Abort();
                        return(new MatchingResult
                        {
                            MatchingErrorType = MatchingErrorType.ReceiptOmitted,
                            ErrorIndex = Array.IndexOf(headersArray, header),
                        });
                    }

                    #endregion

                    #region 9.入金データ消込解除処理

                    var hasAdvanceReceivedOccured = details.Any(x => (x.AdvanceReceivedOccured == 1));
                    foreach (var receipt in receipts)
                    {
                        var prepare_receipt_update = receipt;

                        var receiptId = receipt.Id;

                        var amount = prepare_receipt_update.AssignmentAmount;

                        prepare_receipt_update.RemainAmount     = amount;
                        prepare_receipt_update.AssignmentAmount = amount;
                        prepare_receipt_update.CompanyId        = header.CompanyId;
                        prepare_receipt_update.UpdateBy         = loginUserId;
                        prepare_receipt_update.UpdateAt         = updateAt;

                        await cancelMatchingQueryProcessor.UpdateReceiptForCancelMatchingAsync(prepare_receipt_update, token);

                        // 入金残ログ洗替え
                        await cancelMatchingQueryProcessor.UpdatePreviousReceiptLogsAsync(header.Id, receiptId, amount, loginUserId, updateAt, token);

                        if (!hasAdvanceReceivedOccured)
                        {
                            continue;
                        }
                        //前受データの削除
                        var maeuke_receipt_flg = details.Exists(x => ((x.AdvanceReceivedOccured == 1) && (x.ReceiptId == receipt.Id)));

                        if (!maeuke_receipt_flg)
                        {
                            continue;
                        }
                        var originalReceiptId = receipt.Id;

                        //前受のテータ取得
                        var maeuke_Receipts = (await cancelMatchingQueryProcessor.GetByOriginalIdAsync(originalReceiptId)).ToList();

                        foreach (var maeuke_receipt in maeuke_Receipts)
                        {
                            int canel_flg = await deleteReceiptQueryProcessor.CancelAdvanceReceivedAsync(maeuke_receipt.Id, token);

                            if (canel_flg != 1)
                            {
                                continue;
                            }
                            // データ同期用
                            deleteReceipts.Add(maeuke_receipt);

                            var originalReceipt = receipts.Find(x => (x.Id == originalReceiptId));
                            originalReceipt.RemainAmount     = maeuke_receipt.ReceiptAmount;
                            originalReceipt.AssignmentAmount = 0; //消込額から減算は不要なので
                            originalReceipt.UpdateBy         = loginUserId;
                            originalReceipt.UpdateAt         = updateAt;

                            await cancelMatchingQueryProcessor.UpdateReceiptForCancelMatchingAsync(originalReceipt, token);
                        }
                    }
                    #endregion

                    #region 8.その他処理

                    #region 消込履歴データ検索・出力済データ(MatchingOutputed)の削除

                    await cancelMatchingQueryProcessor.DeleteMatchingOutputedAsync(header.Id, token);

                    #endregion

                    #region 消込歩引データ(MatchingBillingDiscount)の削除

                    foreach (var matching in details)
                    {
                        await deleteMatchingBillingDiscountQueryProcessor.DeleteByMatchingIdAsync(matching.Id, token);
                    }

                    #endregion

                    #region 消込データ(Matching)の削除

                    var deleteMatchingResult = await cancelMatchingQueryProcessor.DeleteMatchingAsync(header.Id, header.MatchingUpdateAt, token);

                    if (deleteMatchingResult <= 0)
                    {
                        notifier?.Abort();
                        return(new MatchingResult
                        {
                            MatchingErrorType = MatchingErrorType.MatchingHeaderChanged,
                            ErrorIndex = Array.IndexOf(headersArray, header),
                        });
                    }

                    #endregion

                    #region MatchingHeaderの削除

                    var deleteResult = await deleteMatchingHeaderQueryProcessor.DeleteAsync(header, token);

                    if (deleteResult <= 0)
                    {
                        notifier?.Abort();
                        return(new MatchingResult
                        {
                            MatchingErrorType = MatchingErrorType.MatchingHeaderChanged,
                            ErrorIndex = Array.IndexOf(headersArray, header),
                        });
                    }

                    #endregion

                    #region 相殺データから変換した入金データの削除
                    foreach (long receiptId in nettingReceiptIds)
                    {
                        await deleteReceiptByIdQueryProcessor.DeleteAsync(receiptId, token);
                    }
                    #endregion

                    #endregion

                    notifier?.UpdateState();
                }

                scope.Complete();

                return(new MatchingResult
                {
                    ProcessResult = new ProcessResult {
                        Result = true
                    },
                    Matchings = deleteMatchings,
                    DeleteReceipts = deleteReceipts,
                });
            }
        }
    }
Esempio n. 30
0
 public Task <ReminderCommonSetting> GetItemAsync(int CompanyId, CancellationToken token = default(CancellationToken))
 => getReminderCommonSettingQueryProcessor.GetAsync(CompanyId, token);