private async Task <Customer> PrepareDataForCustomerAsync(BillingImport billingImport, int CompanyId, List <ImporterSettingDetail> ImporterSettingDetailList, int LoginUserId, CancellationToken token)
        {
            var      customer        = new Customer();
            Category collectCategory = null;

            if (!string.IsNullOrEmpty(billingImport.CollectCategoryCode))
            {
                collectCategory = (await categoryByCodeQueryProcessor.GetAsync(new CategorySearch {
                    CompanyId = CompanyId,
                    CategoryType = Rac.VOne.Common.CategoryType.Collect,
                    Codes = new[] { billingImport.CollectCategoryCode },
                }, token)).FirstOrDefault();
            }
            else
            {
                collectCategory = (await categoryByCodeQueryProcessor.GetAsync(
                                       new CategorySearch {
                    Ids = new[] { billingImport.CollectCategoryId }
                }, token)).FirstOrDefault();
            }

            var existCustomer = (await customerQueryProcessor.GetAsync(
                                     new CustomerSearch {
                CompanyId = CompanyId, Codes = new[] { billingImport.CustomerCode }
            }, token)).FirstOrDefault();

            if (existCustomer == null)
            {
                customer = billingImport.ConvertToCustomer(ImporterSettingDetailList, LoginUserId, collectCategory);
            }
            else
            {
                customer = existCustomer;
                var updExBankCode      = (ImporterSettingDetailList.FirstOrDefault(c => c.Sequence == (int)Fields.ExclusiveBankCode).ImportDivision == 1) && string.IsNullOrEmpty(billingImport.ExclusiveBankCode ?? "");
                var updExBranchCode    = (ImporterSettingDetailList.FirstOrDefault(c => c.Sequence == (int)Fields.ExclusiveBranchCode).ImportDivision == 1) && string.IsNullOrEmpty(billingImport.ExclusiveBranchCode ?? "");
                var updVirBranchCode   = (ImporterSettingDetailList.FirstOrDefault(c => c.Sequence == (int)Fields.ExclusiveVirtualBranchCode).ImportDivision == 1) && string.IsNullOrEmpty(billingImport.ExclusiveVirtualBranchCode ?? "");
                var updExAccountNumber = (ImporterSettingDetailList.FirstOrDefault(c => c.Sequence == (int)Fields.ExclusiveAccountNumber).ImportDivision == 1) && string.IsNullOrEmpty(billingImport.ExclusiveAccountNumber ?? "");

                if (updExBankCode)
                {
                    customer.ExclusiveBankCode = billingImport.ExclusiveBankCode;
                }
                if (updExBranchCode)
                {
                    customer.ExclusiveBranchCode = billingImport.ExclusiveBranchCode;
                }
                if (updVirBranchCode || updExAccountNumber)
                {
                    var exclusiveVirtualBranchCode = updVirBranchCode ? billingImport.ExclusiveVirtualBranchCode : customer.ExclusiveAccountNumber.Substring(0, 3);
                    var exclusiveAccountNumber     = updExAccountNumber ? billingImport.ExclusiveAccountNumber : customer.ExclusiveAccountNumber.Substring(3, 7);
                    customer.ExclusiveAccountNumber = exclusiveVirtualBranchCode + exclusiveAccountNumber;
                }
                customer.UpdateBy = LoginUserId;
            }
            return(customer);
        }
Beispiel #2
0
 public async Task <IEnumerable <Category> > GetAsync(CategorySearch option, CancellationToken token = default(CancellationToken))
 => await categoryByCodeQueryProcessor.GetAsync(option, token);
Beispiel #3
0
 private async Task <Dictionary <string, int> > GetBillingCategoryDictionary(int companyId, IEnumerable <string> codes, CancellationToken token)
 => (await categoryByCodeQueryProcessor.GetAsync(new CategorySearch {
     CompanyId = companyId,
     CategoryType = Rac.VOne.Common.CategoryType.Billing,
     Codes = codes.ToArray(),
 }, token)).ToDictionary(x => x.Code, x => x.Id);
        /// <summary>
        /// 前受振替(分割)処理
        /// </summary>
        /// <param name="source"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <remarks>
        /// 前受入金 仕訳出力済 の場合に、入金データを 別テーブル AdvanceReceivedBackup へ退避
        /// 条件 前受振替処理の対象となる 入金データは、未消込のデータのみ
        /// 分割前、分割後で、ID が 変更されるので、 関連テーブル ReceiptMemo などは 削除する
        /// ReceiptExclude は、未消込なので、存在しない
        /// </remarks>
        public async Task <int> SplitAsync(AdvanceReceivedSplitSource source, CancellationToken token = default(CancellationToken))
        {
            var result = 0;

            using (var scope = transactionScopeBuilder.Create())
            {
                var advanceReceipts = (await receiptQueryProcessor.GetAdvanceReceiptsAsync(source.OriginalReceiptId, token))
                                      .Where(ar => ar.AssignmentFlag == 0).ToArray();

                var receiptMemoDictionary = (await receiptMemoQueryProcessor.GetItemsAsync(advanceReceipts.Select(ar => ar.Id).ToArray(), token))
                                            .ToDictionary(memo => memo.ReceiptId);

                var advanceReceivedBackup = await advanceReceivedBackupQueryProcessor.GetByOriginalReceiptIdAsync(source.OriginalReceiptId, token);

                if (advanceReceivedBackup == null &&
                    advanceReceipts.Count() != 0 && advanceReceipts.First().OutputAt.HasValue)
                {
                    ReceiptMemo receiptMemo;

                    foreach (var receipt in advanceReceipts)
                    {
                        advanceReceivedBackup = receipt.ConvertToAdvanceReceivedBackup(id
                                                                                       => receiptMemoDictionary.TryGetValue(id, out receiptMemo) ? receiptMemo.Memo : "");
                        await advanceReceivedBackupQueryProcessor.SaveAsync(advanceReceivedBackup, token);
                    }
                }

                foreach (var memo in receiptMemoDictionary.Values)
                {
                    await deleteReceiptMemoQueryProcessor.DeleteAsync(memo.ReceiptId, token);
                }
                foreach (var receipt in advanceReceipts)
                {
                    await deleteReceiptByIdQueryProcessor.DeleteAsync(receipt.Id, token);
                }

                var originalReceipt = await receiptGetByIdQueryProcessor.GetByIdAsync(source.OriginalReceiptId, token);

                var advanceReceiptCategoryId = (await categoryByCodeQueryProcessor.GetAsync(new CategorySearch {
                    CompanyId = source.CompanyId,
                    CategoryType = Rac.VOne.Common.CategoryType.Receipt,
                    Codes = new[] { "99" },
                }, token)).First().Id;

                foreach (var split in source.Items)
                {
                    var receipt = split.ConvertToReceipt(originalReceipt, advanceReceiptCategoryId, source.LoginUserId);
                    receipt = await addReceiptQueryProcessor.SaveAsync(receipt, token : token);

                    if (!string.IsNullOrEmpty(split.Memo))
                    {
                        await addReceiptMemoQueryProcessor.SaveAsync(receipt.Id, split.Memo, token);
                    }
                }

                result = source.Items.Length;

                scope.Complete();
            }
            return(result);
        }
        /// <summary>回収予定表 データ抽出/整形</summary>
        /// <param name="searchOption"></param>
        /// <returns></returns>
        /// <remarks>
        /// 得意先 回収区分の情報をどのように取り扱うか ビジネスロジックはここに寄せる
        /// </remarks>
        public async Task <IEnumerable <CollectionSchedule> > GetAsync(CollectionScheduleSearch searchOption, CancellationToken token, IProgressNotifier notifier)
        {
            var initializeResult = searchOption.InitializeYearMonth();

            var schedules = (await collectionScheduleQueryProcessor.GetAsync(searchOption, token, notifier))
                            .Where(x => x.HasAnyValue).ToList();

            if (!(schedules?.Any() ?? false))
            {
                notifier?.UpdateState();
                return(Enumerable.Empty <CollectionSchedule>());
            }

            const int    collectCategoryType = 3;
            const string ContractCode        = "00";
            var          categories          = (await categoryByCodeQueryProcessor.GetAsync(new CategorySearch {
                CompanyId = searchOption.CompanyId, CategoryType = collectCategoryType
            }, token)).ToList();
            var contractId  = categories.FirstOrDefault(x => x.Code == ContractCode)?.Id ?? 0;
            var customerIds = schedules.Where(x => x.CustomerCollectCategoryId == contractId)
                              .Select(x => x.CustomerId).Distinct().ToArray();
            var contracts = await customerPaymentContractQueryProcessor.GetAsync(customerIds, token);


            var result     = new List <CollectionSchedule>();
            var groupCount = 0;

            var subtotal = new Dictionary <string, Dictionary <int, decimal> >();
            var subDpt   = new Dictionary <string, Dictionary <int, decimal> >();
            var subStf   = new Dictionary <string, Dictionary <int, decimal> >();
            var deptBuf  = string.Empty;
            var stafBuf  = string.Empty;
            var requireDepartmentSubtotal = searchOption.IsPrint && searchOption.NewPagePerDepartment;
            var requireStaffSubtotal      = searchOption.IsPrint && searchOption.NewPagePerStaff;

            foreach (var group in schedules.GroupBy(x => x.CustomerId))
            {
                var detail       = group.First();
                var category     = categories.FirstOrDefault(x => x.Id != contractId && x.Id == detail.CustomerCollectCategoryId);
                var contract     = contracts.FirstOrDefault(x => x.CustomerId == detail.CustomerId);
                var customerInfo = GetCustomerInfo(detail, category, contract);

                if (requireStaffSubtotal &&
                    !string.IsNullOrEmpty(stafBuf) && stafBuf != detail.StaffCode)
                {
                    result.AddRange(GetSubtotalRecords(subStf, categories, deptBuf, stafBuf, 1, "担当者計", ref groupCount));
                }

                if (requireDepartmentSubtotal &&
                    !string.IsNullOrEmpty(deptBuf) && deptBuf != detail.DepartmentCode)
                {
                    result.AddRange(GetSubtotalRecords(subDpt, categories, deptBuf, stafBuf, 2, "部門計", ref groupCount));
                }

                var list = new List <CollectionSchedule>();

                CollectionSchedule contractPayment = null;
                foreach (var item in group)
                {
                    if (item.CollectCategoryCode == ContractCode)
                    {
                        contractPayment = item;
                        continue;
                    }
                    list.Add(item);
                }

                if (contractPayment != null && contract != null)
                {
                    foreach (var divided in Divide(contractPayment, contract))
                    {
                        var index = list.FindIndex(x => x.CollectCategoryCode == divided.CollectCategoryCode);
                        if (index < 0)
                        {
                            list.Add(divided);
                            continue;
                        }
                        list[index].UncollectedAmountLast += divided.UncollectedAmountLast;
                        list[index].UncollectedAmount0    += divided.UncollectedAmount0;
                        list[index].UncollectedAmount1    += divided.UncollectedAmount1;
                        list[index].UncollectedAmount2    += divided.UncollectedAmount2;
                        list[index].UncollectedAmount3    += divided.UncollectedAmount3;
                    }
                    list.Sort((x, y) => string.Compare(x.CollectCategoryCode, y.CollectCategoryCode));
                }

                for (var i = 0; i < list.Count; i++)
                {
                    if (i == 0)
                    {
                        list[i].RowId = ++groupCount;
                    }
                    else
                    {
                        list[i].DepartmentName = string.Empty;
                        list[i].StaffName      = string.Empty;
                        list[i].ClosingDay     = null;
                    }

                    var code = list[i].CollectCategoryCode;
                    if (!subtotal.ContainsKey(code))
                    {
                        subtotal.Add(code, Pivot(null));
                    }
                    if (requireDepartmentSubtotal && !subDpt.ContainsKey(code))
                    {
                        subDpt.Add(code, Pivot(null));
                    }
                    if (requireStaffSubtotal && !subStf.ContainsKey(code))
                    {
                        subStf.Add(code, Pivot(null));
                    }

                    if (!list[i].HasAnyValue)
                    {
                        continue;
                    }

                    AddValue(subtotal[code], list[i]);
                    if (requireDepartmentSubtotal)
                    {
                        AddValue(subDpt[code], list[i]);
                    }
                    if (requireStaffSubtotal)
                    {
                        AddValue(subStf[code], list[i]);
                    }
                }

                for (var i = 0; i < customerInfo.Count; i++)
                {
                    if (list.Count <= i)
                    {
                        var item = new CollectionSchedule();
                        item.CustomerId     = detail.CustomerId;
                        item.StaffCode      = detail.StaffCode;
                        item.DepartmentCode = detail.DepartmentCode;
                        list.Add(item);
                    }
                    list[i].CustomerInfo = customerInfo[i];
                }
                result.AddRange(list);

                deptBuf = detail.DepartmentCode;
                stafBuf = detail.StaffCode;
            }

            if (requireStaffSubtotal)
            {
                result.AddRange(GetSubtotalRecords(subStf, categories, deptBuf, stafBuf, 1, "担当者計", ref groupCount));
            }

            if (requireDepartmentSubtotal)
            {
                result.AddRange(GetSubtotalRecords(subDpt, categories, deptBuf, stafBuf, 2, "部門計", ref groupCount));
            }

            // grand total
            {
                // category total
                result.AddRange(GetSubtotalRecords(new Dictionary <string, Dictionary <int, decimal> >(subtotal), categories, "", "", 3, "合計", ref groupCount));

                var item = GetNewItem(string.Empty, string.Empty);
                item.CustomerInfo = "総合計";
                item.RowId        = ++groupCount;
                item.RecordType   = 4;
                foreach (var key in subtotal.Keys)
                {
                    foreach (var field in subtotal[key].Keys)
                    {
                        SetValue(item, field, subtotal[key][field]);
                    }
                }

                result.Add(item);
            }

            if (searchOption.UnitPrice != 1M)
            {
                foreach (var item in result)
                {
                    item.Truncate(searchOption.UnitPrice);
                }
            }
            notifier?.UpdateState();
            return(result);
        }