Beispiel #1
0
 /// <summary>
 /// Takes the specified receipt voucher.
 /// </summary>
 /// <param name="deposit">The receipt voucher.</param>
 /// <returns></returns>
 private object[] Take(DepositEntity deposit)
 {
     return(new object[]
     {
         @"RefID", deposit.RefId,
         @"RefTypeID", deposit.RefTypeId,
         @"RefNo", deposit.RefNo,
         @"RefDate", deposit.RefDate,
         @"PostedDate", deposit.PostedDate,
         @"AccountingObjectType", deposit.AccountingObjectType,
         @"AccountingObjectID", deposit.AccountingObjectId,
         @"Trader", deposit.Trader,
         @"CustomerID", deposit.CustomerId,
         @"VendorID", deposit.VendorId,
         @"EmployeeID", deposit.EmployeeId,
         @"BankAccountCode", deposit.BankAccountCode,
         @"CurrencyCode", deposit.CurrencyCode,
         @"ExchangeRate", deposit.ExchangeRate,
         @"TotalAmountOC", deposit.TotalAmountOc,
         @"TotalAmountExchange", deposit.TotalAmountExchange,
         @"JournalMemo", deposit.JournalMemo,
         @"BankID", deposit.BankId,
         @"IsIncludeCharge", deposit.IsIncludeCharge
     });
 }
Beispiel #2
0
        /// <summary>
        /// Gets the deposit by refdate and reftype.
        /// </summary>
        /// <param name="obDepositEntity">The ob deposit entity.</param>
        /// <returns></returns>
        public DepositEntity GetDepositByRefdateAndReftype(DepositEntity obDepositEntity)
        {
            const string procedures = @"uspGet_Deposit_ForSalary";

            object[] parms = { "@RefTypeID", obDepositEntity.RefTypeId, "@PostedDate", obDepositEntity.PostedDate, "@RefNo", obDepositEntity.RefNo };
            return(Db.Read(procedures, true, Make, parms));
        }
Beispiel #3
0
        public string DeleteDeposit(DepositEntity deposit)
        {
            const string sql = @"uspDelete_Deposit";

            object[] parms = { "@RefID", deposit.RefId };
            return(Db.Delete(sql, true, parms));
        }
Beispiel #4
0
        public async Task <bool> DeleteAsync(DepositEntity deposit)
        {
            _context.Remove(deposit);
            await _context.SaveChangesAsync();

            return(true);
        }
 public static DepositDto AsDto(this DepositEntity deposit)
 {
     return(new DepositDto
     {
         CustomerCID = deposit.CustomerCID,
         LastAmount = deposit.LastAmount,
         Balance = deposit.Balance
     });
 }
 public static DepositDto AsDto(this DepositEntity deposit, string customerName)
 {
     return(new DepositDto
     {
         CustomerCID = deposit.CustomerCID,
         LastAmount = deposit.LastAmount,
         Balance = deposit.Balance,
         CustomerName = customerName
     });
 }
Beispiel #7
0
        public async Task <bool> CreateAsync(DepositEntity deposit)
        {
            if (!IsIDExistsAsync(deposit.CustomerCID).Result)
            {
                _context.Add(deposit);
                await _context.SaveChangesAsync();

                return(true);
            }
            return(false);
        }
Beispiel #8
0
        public async Task <ActionResult <DepositDto> > PostAsync(CreateDepositDto depositDto)
        {
            var deposit = new DepositEntity
            {
                CustomerCID = depositDto.CustomerCID,
                LastAmount  = depositDto.LastAmount,
                Balance     = depositDto.Balance
            };

            await _depositRepository.CreateAsync(deposit);

            await _publishEndpoint.Publish(new DepositCreated(
                                               deposit.CustomerCID, deposit.LastAmount, deposit.Balance
                                               ));

            return(CreatedAtAction(nameof(GetByIDAsync), new { id = deposit.CustomerCID }, deposit));
        }
 internal static DepositModel FromDataTransferObject(DepositEntity entity)
 {
     return(entity == null ? null : AutoMapper.Mapper.Map <DepositEntity, DepositModel>(entity));
 }
Beispiel #10
0
        /// <summary>
        /// Updates the deposit.
        /// </summary>
        /// <param name="deposit">The deposit.</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public string UpdateDeposit(DepositEntity deposit)
        {
            const string sql = @"uspUpdate_Deposit";

            return(Db.Update(sql, true, Take(deposit)));
        }
Beispiel #11
0
        /// <summary>
        /// Inserts the deposit.
        /// </summary>
        /// <param name="deposit">The deposit.</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public int InsertDeposit(DepositEntity deposit)
        {
            const string sql = @"uspInsert_Deposit";

            return(Db.Insert(sql, true, Take(deposit)));
        }
Beispiel #12
0
        public async Task <AddCardDepositResponse> AddCirclePayment(AddCardDepositRequest request)
        {
            request.AddToActivityAsJsonTag("add-circle-payment");

            _logger.LogInformation("Request to handle payment to Circle: {transferJson}",
                                   JsonConvert.SerializeObject(request));

            request.BrokerId.AddToActivityAsTag("brokerId");
            request.ClientId.AddToActivityAsTag("clientId");
            request.WalletId.AddToActivityAsTag("walletId");

            var matchingEngineId = "Deposit:" + Guid.NewGuid();

            var card = await _circleCardsService.GetCircleClientCard(new GetClientCardRequest
            {
                BrokerId = request.BrokerId,
                ClientId = request.ClientId,
                CardId   = request.CardId
            });

            if (!card.IsSuccess)
            {
                return new AddCardDepositResponse
                       {
                           Status = AddCardDepositResponse.StatusCode.CardNotFound
                       }
            }
            ;

            var response = await _circlePaymentsService.AddCirclePayment(new AddPaymentRequest
            {
                BrokerId       = request.BrokerId,
                ClientId       = request.ClientId,
                IdempotencyKey = request.RequestId,
                KeyId          = request.KeyId,
                SessionId      = request.SessionId,
                IpAddress      = request.IpAddress,
                Amount         = (double)request.Amount,
                Currency       = request.Currency,
                Verification   = "cvv",
                SourceId       = card.Data.CircleCardId,
                SourceType     = "card",
                Description    = $"{request.BrokerId}|-|{request.ClientId}|-|{request.WalletId}",
                EncryptedData  = request.EncryptedData
            });

            try
            {
                await using var ctx = DatabaseContext.Create(_dbContextOptionsBuilder);

                var deposit = new DepositEntity
                {
                    BrokerId      = request.BrokerId,
                    WalletId      = request.WalletId,
                    ClientId      = request.ClientId,
                    TransactionId = response.Data != null ? response.Data.Id : "",
                    Amount        = request.Amount,
                    AssetSymbol   = request.Currency,
                    Comment       =
                        $"Circle card deposit [{request.Currency}:{request.WalletId}, card: {request.CardId}]",
                    Integration = "CircleCard",
                    Txid        = response.Data != null ? response.Data.Id : "",
                    Status      = response.IsSuccess && response.Data != null && response.Data.Status != PaymentStatus.Failed
                        ? DepositStatus.Processing
                        : DepositStatus.Error,
                    EventDate        = DateTime.UtcNow,
                    UpdateDate       = DateTime.UtcNow,
                    CardLast4        = card.Data.Last4,
                    Network          = card.Data.Network,
                    FeeAmount        = 0,
                    FeeAssetSymbol   = request.Currency,
                    MatchingEngineId = matchingEngineId,
                };

                await ctx.InsertAsync(deposit);

                await _depositPublisher.PublishAsync(new Deposit(deposit));

                if (!response.IsSuccess || response.Data == null)
                {
                    return new AddCardDepositResponse {
                               Status = AddCardDepositResponse.StatusCode.PaymentFailed
                    }
                }
                ;

                if (response.Data.Status == PaymentStatus.Failed)
                {
                    switch (response.Data.ErrorCode)
                    {
                    case PaymentErrorCode.CardFailed:
                    case PaymentErrorCode.CardInvalid:
                        return(new AddCardDepositResponse {
                            Status = AddCardDepositResponse.StatusCode.CardFailed
                        });

                    case PaymentErrorCode.CardAddressMismatch:
                        return(new AddCardDepositResponse
                        {
                            Status = AddCardDepositResponse.StatusCode.CardAddressMismatch
                        });

                    case PaymentErrorCode.CardZipMismatch:
                        return(new AddCardDepositResponse
                        {
                            Status = AddCardDepositResponse.StatusCode.CardZipMismatch
                        });

                    case PaymentErrorCode.CardCvvInvalid:
                        return(new AddCardDepositResponse
                        {
                            Status = AddCardDepositResponse.StatusCode.CardCvvInvalid
                        });

                    case PaymentErrorCode.CardExpired:
                        return(new AddCardDepositResponse
                        {
                            Status = AddCardDepositResponse.StatusCode.CardExpired
                        });

                    default:
                        return(new AddCardDepositResponse
                        {
                            Status = AddCardDepositResponse.StatusCode.PaymentFailed
                        });
                    }
                }

                return(new AddCardDepositResponse
                {
                    Status = AddCardDepositResponse.StatusCode.Ok,
                    DepositId = matchingEngineId
                });
            }
            catch (Exception e)
            {
                _logger.LogError("Unable to update deposit entry", e);
                throw;
            }
        }
    }
        /// <summary>
        /// Set the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>SalaryResponse.</returns>
        public SalaryResponse SetSalaries(SalaryRequest request)
        {
            var response           = new SalaryResponse();
            var obJourentryAccount = new JournalEntryAccountEntity();
            IList <JournalEntryAccountEntity> listJournalEntryAccountEntity = new List <JournalEntryAccountEntity>();
            IList <AccountBalanceEntity>      listAccountBalanceEntity      = new List <AccountBalanceEntity>();
            var mapper = request.Salary;

            if (request.Action != PersistType.Delete)
            {
                if (!mapper.Validate())
                {
                    foreach (string error in mapper.ValidationErrors)
                    {
                        response.Message += error + Environment.NewLine;
                    }
                    response.Acknowledge = AcknowledgeType.Failure;
                    return(response);
                }
            }
            try
            {
                if (request.LoadOptions.Contains("CalSalary"))
                {
                    var lstDeposit = SalaryDao.GetSalaryByRefNo(mapper.RefNo);
                    if (lstDeposit.Count > 0)
                    {
                        response.Message     = "Đã tồn tại số chứng từ " + mapper.RefNo + " !";
                        response.Acknowledge = AcknowledgeType.Failure;
                        return(response);
                    }
                    foreach (var employees in mapper.Employees)
                    {
                        mapper.EmployeeId = employees.EmployeeId;
                        response.SalaryId = SalaryDao.CalSalary(mapper);
                    }
                    var autoNumber = AutoNumberDao.GetAutoNumberByRefType(600);
                    //------------------------------------------------------------------
                    //LinhMC 29/11/2014
                    //Lưu giá trị số tự động tăng theo loại tiền
                    //---------------------------------------------------------------
                    if (request.Salary.CurrencyCode == "USD")
                    {
                        autoNumber.Value += 1;
                    }
                    else
                    {
                        autoNumber.ValueLocalCurency += 1;
                    }


                    response.Message = AutoNumberDao.UpdateAutoNumber(autoNumber);
                }

                if (request.LoadOptions.Contains("SavePostedSalary"))
                {
                    /* Danh sách các khoản lương
                     * Nhân viên liên kết Danh sách các khoản lương
                     * Lưu Chứng từ lương:  Nhân viên lấy từ lấy các khoản lương theo nhân viên==> tổng số tiền lương
                     * ==> Đồng thời lưu vào chứng từ Phiếu chi hoặc Giấy báo Nợ đặt mặc định RefType=600 vs Số chứng từ (RefNo) và ngày chứng từ lương
                     * ==> Khi lưu chứng từ Phiếu Chi hoặc Giấy báo Có được lưu dựa trên cách lưu của Phiếu Chi hoặc Giấy Báo Có
                     * ==> Để xác định chứng từ là Phiếu Chi hay Giấy báo Nợ phải dựa báo TK có trên Danh mục khoản lương
                     */
                    var depositEntity = new DepositEntity()
                    {
                        RefId                = 0,
                        RefTypeId            = mapper.RefTypeId,//
                        RefDate              = mapper.RefDate,
                        RefNo                = mapper.RefNo,
                        PostedDate           = mapper.PostedDate,
                        AccountingObjectType = 0,
                        AccountingObjectId   = null,
                        Trader               = "",
                        CustomerId           = null,
                        VendorId             = null,
                        EmployeeId           = null,// mapper.EmployeeId,
                        BankAccountCode      = "112",
                        CurrencyCode         = mapper.CurrencyCode,
                        ExchangeRate         = mapper.ExchangeRate,
                        TotalAmountOc        = 0, // employeePayItem.Amount,
                        TotalAmountExchange  = 0, // employeePayItem.Amount,
                        JournalMemo          = "Chứng từ lương tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                    };
                    depositEntity.DepositDetails = new List <DepositDetailEntity>();
                    var cashEntity = new CashEntity
                    {
                        RefId              = 0,
                        RefTypeId          = mapper.RefTypeId,//
                        RefNo              = mapper.RefNo,
                        RefDate            = mapper.RefDate,
                        PostedDate         = mapper.PostedDate,
                        AccountingObjectId = null,
                        CustomerId         = null,
                        VendorId           = null,
                        Trader             = "",
                        CurrencyCode       = mapper.CurrencyCode,
                        ExchangeRate       = mapper.ExchangeRate,

                        TotalAmount         = 0,
                        TotalAmountExchange = 0,
                        AccountNumber       = "",

                        JournalMemo          = "Chứng từ lương tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                        DocumentInclude      = "",
                        AccountingObjectType = 2,
                        //     CashDetails = cashDetails;
                        EmployeeId = null,
                    };
                    cashEntity.CashDetails = new List <CashDetailEntity>();

                    // var lstDeposit = SalaryDao.GetSalaryByRefNo(mapper.RefNo);
                    //if (lstDeposit.Count > 0)
                    //{
                    //    response.Message = "Đã tồn tại số chứng từ " + mapper.RefNo + " !";
                    //    response.Acknowledge = AcknowledgeType.Failure;
                    //    return response;
                    //}
                    //  var Cash
                    mapper.Employees = EmployeeDao.GetEmployeesForSalary(mapper.RefDate, mapper.RefNo);
                    foreach (var employee in mapper.Employees)
                    {
                        //Tính lại lương cho nhân viên trước khi ghi sổ
                        mapper.EmployeeId = employee.EmployeeId;
                        response.SalaryId = SalaryDao.CalSalary(mapper);

                        //Từng nhân viên - từng khoảng lương - tiền tương ứng.
                        IList <EmployeePayItemEntity> listPayItems = EmployeePayItemDao.GetEmployeeForViewtEmployeePayItem(employee.EmployeeId, mapper.RefDate, mapper.ExchangeRate);
                        // mapper.EmployeePayItemId = EmployeePayItemDao.GetEmployeePayItemsByEmployeeId(employee.EmployeeId);
                        foreach (var employeePayItemEntity in listPayItems)
                        {
                            mapper.EmployeePayItemId = employeePayItemEntity.EmployeePayItemId;
                            var payItems = PayItemDao.GetPayItem(employeePayItemEntity.PayItemId);
                            //Chi
                            if (payItems.CreditAccountCode.Substring(0, 3).Contains("111"))
                            {
                                // khởi tạo phieu chi chi tiết
                                CashDetailEntity cashDetailEntity = new CashDetailEntity()
                                {
                                    RefDetailId   = 0,
                                    RefId         = 0,
                                    AccountNumber = payItems.DebitAccountCode,
                                    CorrespondingAccountNumber = payItems.CreditAccountCode,
                                    Description        = payItems.PayItemName + " tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                                    AmountOc           = employeePayItemEntity.Amount * mapper.ExchangeRate,
                                    AmountExchange     = employeePayItemEntity.Amount,
                                    VoucherTypeId      = null,
                                    BudgetSourceCode   = payItems.BudgetSourceCode,
                                    BudgetItemCode     = payItems.BudgetItemCode,
                                    AccountingObjectId = null,
                                    MergerFundId       = null
                                };
                                bool flag = false;
                                for (int i = 0; i < cashEntity.CashDetails.Count; i++)
                                {
                                    if (cashEntity.CashDetails[i].CorrespondingAccountNumber == cashDetailEntity.CorrespondingAccountNumber && cashEntity.CashDetails[i].AccountNumber == cashDetailEntity.AccountNumber && cashEntity.CashDetails[i].BudgetItemCode == cashDetailEntity.BudgetItemCode && cashEntity.CashDetails[i].BudgetSourceCode == cashDetailEntity.BudgetSourceCode)
                                    {
                                        cashEntity.CashDetails[i].AmountOc       = cashEntity.CashDetails[i].AmountOc + cashDetailEntity.AmountOc;
                                        cashEntity.CashDetails[i].AmountExchange = cashEntity.CashDetails[i].AmountExchange + cashDetailEntity.AmountExchange;
                                        flag = true;
                                    }
                                }
                                if (flag == false)
                                {
                                    if (cashDetailEntity.AmountOc > 0)
                                    {
                                        cashEntity.CashDetails.Add(cashDetailEntity);
                                    }
                                }
                                //Tính lại TotalAmountOc - TotalAmountExchange
                                cashEntity.TotalAmount         = cashEntity.TotalAmount + cashDetailEntity.AmountOc;
                                cashEntity.TotalAmountExchange = cashEntity.TotalAmountExchange + cashDetailEntity.AmountExchange;
                                //Get Bank Acount
                                cashEntity.AccountNumber = payItems.CreditAccountCode;
                            }
                            //Nợ
                            if (payItems.CreditAccountCode.Substring(0, 3).Contains("112") == true)
                            {
                                DepositDetailEntity depositDetailEntity = new DepositDetailEntity()
                                {
                                    RefDetailId   = mapper.RefTypeId,
                                    RefId         = 0,
                                    Description   = payItems.PayItemName + " tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                                    AccountNumber = payItems.DebitAccountCode,
                                    CorrespondingAccountNumber = payItems.CreditAccountCode,
                                    AmountOc           = employeePayItemEntity.Amount * mapper.ExchangeRate,
                                    AmountExchange     = employeePayItemEntity.Amount,
                                    VoucherTypeId      = 1,
                                    BudgetSourceCode   = payItems.BudgetSourceCode,
                                    AccountingObjectId = null,
                                    BudgetItemCode     = payItems.BudgetItemCode,
                                    //DepartmentId = mapper.DepartmentId,
                                    MergerFundId = null
                                };
                                bool flag = false;
                                for (int i = 0; i < depositEntity.DepositDetails.Count; i++)
                                {
                                    if (depositEntity.DepositDetails[i].CorrespondingAccountNumber == depositDetailEntity.CorrespondingAccountNumber && depositEntity.DepositDetails[i].BudgetItemCode == depositDetailEntity.BudgetItemCode && depositEntity.DepositDetails[i].BudgetSourceCode == depositDetailEntity.BudgetSourceCode)
                                    {
                                        depositEntity.DepositDetails[i].AmountOc       = depositEntity.DepositDetails[i].AmountOc + depositDetailEntity.AmountOc;
                                        depositEntity.DepositDetails[i].AmountExchange = depositEntity.DepositDetails[i].AmountExchange + depositDetailEntity.AmountExchange;
                                        flag = true;
                                    }
                                }
                                if (flag == false)
                                {
                                    if (depositDetailEntity.AmountOc > 0)
                                    {
                                        depositEntity.DepositDetails.Add(depositDetailEntity);
                                    }
                                }
                                //Tính lại TotalAmountOc - TotalAmountExchange
                                depositEntity.TotalAmountOc       = depositEntity.TotalAmountOc + depositDetailEntity.AmountOc;
                                depositEntity.TotalAmountExchange = depositEntity.TotalAmountExchange + depositDetailEntity.AmountExchange;
                                //Get bank Acount
                                depositEntity.BankAccountCode = payItems.CreditAccountCode;
                            }
                        }
                    }
                    var autoNumber = AutoNumberDao.GetAutoNumberByRefType(600);
                    //------------------------------------------------------------------
                    //LinhMC 29/11/2014
                    //Lưu giá trị số tự động tăng theo loại tiền
                    //---------------------------------------------------------------
                    if (request.Salary.CurrencyCode == "USD")
                    {
                        autoNumber.Value += 1;
                    }
                    else
                    {
                        autoNumber.ValueLocalCurency += 1;
                    }

                    response.Message = AutoNumberDao.UpdateAutoNumber(autoNumber);
                    // insert or update giấy báo nợ

                    {
                        var checkDepositEntity = DepositDao.GetDepositByRefdateAndReftype(depositEntity);
                        if (checkDepositEntity == null)
                        {
                            if (depositEntity.DepositDetails.Count > 0)
                            {
                                var depositRequest = new DepositRequest();
                                var oDepositFacade = new DepositFacade();
                                depositRequest.Action  = PersistType.Insert;
                                depositRequest.Deposit = depositEntity;
                                oDepositFacade.SetDeposits(depositRequest);
                            }
                        }
                        //Sẽ không còn trường hợp này nữa
                        //else
                        //{
                        //    //Update CheckDepositEntity with amuont depositEntity,..
                        //    checkDepositEntity.DepositDetails = new List<DepositDetailEntity>();
                        //    checkDepositEntity.RefDate = depositEntity.RefDate;
                        //    checkDepositEntity.RefNo = depositEntity.RefNo;
                        //    checkDepositEntity.ExchangeRate = depositEntity.ExchangeRate;
                        //    checkDepositEntity.CurrencyCode = depositEntity.CurrencyCode;
                        //    checkDepositEntity.ExchangeRate = depositEntity.ExchangeRate;
                        //    checkDepositEntity.TotalAmountOc = depositEntity.TotalAmountOc;
                        //    checkDepositEntity.TotalAmountExchange = depositEntity.TotalAmountExchange;
                        //    checkDepositEntity.BankAccountCode = depositEntity.BankAccountCode;
                        //    //Thêm các details mới+
                        //    foreach (var depositDetail in depositEntity.DepositDetails)
                        //    {
                        //        if (!depositDetail.Validate())
                        //        {
                        //            foreach (string error in depositDetail.ValidationErrors)
                        //                response.Message += error + Environment.NewLine;
                        //            response.Acknowledge = AcknowledgeType.Failure;
                        //            return response;
                        //        }
                        //        depositDetail.RefId = checkDepositEntity.RefId;
                        //        checkDepositEntity.DepositDetails.Add(depositDetail);
                        //    }
                        //    var depositRequest = new DepositRequest();
                        //    var oDepositFacade = new DepositFacade();
                        //    depositRequest.Action = PersistType.Update;
                        //    depositRequest.Deposit = checkDepositEntity;
                        //    oDepositFacade.SetDeposits(depositRequest);
                        //}
                    }
                    // Insert phieu chi
                    //if (cashEntity.CashDetails.Count > 0)
                    //{
                    var checkCashEntity = CashDao.GetCashByRefdateAndReftype(cashEntity);
                    if (checkCashEntity == null)
                    {
                        if (cashEntity.CashDetails.Count > 0)
                        {
                            var cashRequest = new CashRequest();
                            var oCashFacade = new CashFacade();
                            cashRequest.Action     = PersistType.Insert;
                            cashRequest.CashEntity = cashEntity;
                            oCashFacade.SetCashes(cashRequest);
                        }
                    }
                    //Sẽ không có trường hợp này nữa
                    //else
                    //{
                    //    //Update
                    //    checkCashEntity.CashDetails = new List<CashDetailEntity>();
                    //    checkCashEntity.RefDate = cashEntity.RefDate;
                    //    checkCashEntity.RefNo = cashEntity.RefNo;
                    //    checkCashEntity.ExchangeRate = cashEntity.ExchangeRate;
                    //    checkCashEntity.CurrencyCode = cashEntity.CurrencyCode;
                    //    checkCashEntity.ExchangeRate = cashEntity.ExchangeRate;
                    //    checkCashEntity.TotalAmount = cashEntity.TotalAmount;
                    //    checkCashEntity.TotalAmountExchange = cashEntity.TotalAmountExchange;
                    //    checkCashEntity.AccountNumber = cashEntity.AccountNumber;
                    //    //Thêm các details mới+
                    //    foreach (var cashDetail in cashEntity.CashDetails)
                    //    {
                    //        if (!cashDetail.Validate())
                    //        {
                    //            foreach (string error in cashDetail.ValidationErrors)
                    //                response.Message += error + Environment.NewLine;
                    //            response.Acknowledge = AcknowledgeType.Failure;
                    //            return response;
                    //        }
                    //        cashDetail.RefId = checkCashEntity.RefId;
                    //        checkCashEntity.CashDetails.Add(cashDetail);
                    //    }
                    //    var cashRequest = new CashRequest();
                    //    var oCashFacade = new CashFacade();
                    //    cashRequest.Action = PersistType.Update;
                    //    cashRequest.CashEntity = checkCashEntity;
                    //    oCashFacade.SetCashes(cashRequest);
                    //}
                }

                if (request.LoadOptions.Contains("CheckCalSalaryState"))
                {
                    var salaries = SalaryDao.GetSalaryByRefDateAndEmployId(mapper.RefDate, mapper.EmployeeId);
                    if (salaries.Count > 0)
                    {
                        response.Acknowledge = AcknowledgeType.Success;
                        response.Message     = @"Nhân viên đã được tính lương !";
                        response.Salary      = salaries[0];
                        return(response);
                    }
                    response.Message = null;
                }

                if (request.LoadOptions.Contains("CheckCalSalaryPostedState"))
                {
                    var salaries = SalaryDao.GetSalaryPostedByRefDateAndEmployId(mapper.RefDate, mapper.EmployeeId);
                    if (salaries.Count > 0)
                    {
                        response.Acknowledge = AcknowledgeType.Success;
                        response.Message     = @"Nhân viên đã được tính lương !";
                        response.Salary      = salaries[0];
                        return(response);
                    }
                    response.Message = null;
                }

                if (request.LoadOptions.Contains("DeleteCalSalary"))
                {
                    //foreach (var employee in mapper.Employees)
                    //{
                    //    mapper.EmployeeId = employee.EmployeeId;
                    //    response.SalaryId = SalaryDao.DeleteCalSalary(mapper);
                    //}

                    var depositEntity = new DepositEntity()
                    {
                        RefId                = 0,
                        RefTypeId            = mapper.RefTypeId,//
                        RefDate              = mapper.RefDate,
                        RefNo                = mapper.RefNo,
                        PostedDate           = mapper.PostedDate,
                        AccountingObjectType = 0,
                        AccountingObjectId   = null,
                        Trader               = "",
                        CustomerId           = null,
                        VendorId             = null,
                        EmployeeId           = null,// mapper.EmployeeId,
                        BankAccountCode      = "112",
                        CurrencyCode         = mapper.CurrencyCode,
                        ExchangeRate         = mapper.ExchangeRate,
                        TotalAmountOc        = 0, // employeePayItem.Amount,
                        TotalAmountExchange  = 0, // employeePayItem.Amount,
                        JournalMemo          = "Chứng từ lương tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                    };
                    depositEntity.DepositDetails = new List <DepositDetailEntity>();
                    var cashEntity = new CashEntity()
                    {
                        RefId              = 0,
                        RefTypeId          = mapper.RefTypeId,//
                        RefNo              = mapper.RefNo,
                        RefDate            = mapper.RefDate,
                        PostedDate         = mapper.PostedDate,
                        AccountingObjectId = null,
                        CustomerId         = null,
                        VendorId           = null,
                        Trader             = "",
                        CurrencyCode       = mapper.CurrencyCode,
                        ExchangeRate       = mapper.ExchangeRate,

                        TotalAmount         = 0,
                        TotalAmountExchange = 0,
                        AccountNumber       = "",

                        JournalMemo          = "Chứng từ lương tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                        DocumentInclude      = "",
                        AccountingObjectType = 2,
                        //     CashDetails = cashDetails;
                        EmployeeId = null,
                    };
                    cashEntity.CashDetails = new List <CashDetailEntity>();

                    //  var Cash
                    foreach (var employee in mapper.Employees)
                    {
                        //Xóa EmployeePayroll
                        mapper.EmployeeId = employee.EmployeeId;
                        response.SalaryId = SalaryDao.DeleteCalSalary(mapper);
                        //End Xóa EmployeePayroll
                        //Từng nhân viên - từng khoảng lương - tiền tương ứng.
                        IList <EmployeePayItemEntity> listPayItems = EmployeePayItemDao.GetEmployeePayItemsByEmployeeId(employee.EmployeeId);
                        foreach (var employeePayItemEntity in listPayItems)
                        {
                            mapper.EmployeePayItemId = employeePayItemEntity.EmployeePayItemId;
                            var payItems = PayItemDao.GetPayItem(employeePayItemEntity.PayItemId);
                            //Chi
                            if (payItems.CreditAccountCode.Substring(0, 3).Contains("111"))
                            {
                                // khởi tạo phieu chi chi tiết
                                var cashDetailEntity = new CashDetailEntity()
                                {
                                    RefDetailId   = 0,
                                    RefId         = 0,
                                    AccountNumber = payItems.DebitAccountCode,
                                    CorrespondingAccountNumber = payItems.CreditAccountCode,
                                    Description        = payItems.PayItemName + " tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                                    AmountOc           = employeePayItemEntity.Amount,
                                    AmountExchange     = employeePayItemEntity.Amount / mapper.ExchangeRate,
                                    VoucherTypeId      = null,
                                    BudgetSourceCode   = payItems.BudgetSourceCode,
                                    BudgetItemCode     = payItems.BudgetItemCode,
                                    AccountingObjectId = null,
                                    MergerFundId       = null
                                };
                                bool flag = false;
                                for (int i = 0; i < cashEntity.CashDetails.Count; i++)
                                {
                                    if (cashEntity.CashDetails[i].CorrespondingAccountNumber == cashDetailEntity.CorrespondingAccountNumber &&
                                        cashEntity.CashDetails[i].AccountNumber == cashDetailEntity.AccountNumber &&
                                        cashEntity.CashDetails[i].BudgetItemCode == cashDetailEntity.BudgetItemCode &&
                                        cashEntity.CashDetails[i].BudgetSourceCode == cashDetailEntity.BudgetSourceCode)
                                    {
                                        cashEntity.CashDetails[i].AmountOc       = cashEntity.CashDetails[i].AmountOc + cashDetailEntity.AmountOc;
                                        cashEntity.CashDetails[i].AmountExchange = cashEntity.CashDetails[i].AmountExchange + cashDetailEntity.AmountExchange;
                                        flag = true;
                                        //   break;
                                    }
                                }

                                if (flag == false)
                                {
                                    cashEntity.CashDetails.Add(cashDetailEntity);
                                }

                                //Tính lại TotalAmountOc - TotalAmountExchange
                                cashEntity.TotalAmount         = cashEntity.TotalAmount + cashDetailEntity.AmountOc;
                                cashEntity.TotalAmountExchange = cashEntity.TotalAmountExchange + cashDetailEntity.AmountExchange;
                                //Get Bank Acount
                                cashEntity.AccountNumber = payItems.CreditAccountCode;
                            }
                            //Nợ
                            if (payItems.CreditAccountCode.Substring(0, 3).Contains("112"))
                            {
                                var depositDetailEntity = new DepositDetailEntity()
                                {
                                    RefDetailId   = mapper.RefTypeId,
                                    RefId         = 0,
                                    Description   = payItems.PayItemName + " tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                                    AccountNumber = payItems.DebitAccountCode,
                                    CorrespondingAccountNumber = payItems.CreditAccountCode,
                                    AmountOc           = employeePayItemEntity.Amount,
                                    AmountExchange     = employeePayItemEntity.Amount / mapper.ExchangeRate,
                                    VoucherTypeId      = 1,
                                    BudgetSourceCode   = payItems.BudgetSourceCode,
                                    AccountingObjectId = null,
                                    BudgetItemCode     = payItems.BudgetItemCode,
                                    //    DepartmentId = mapper.DepartmentId,
                                    MergerFundId = null
                                };
                                bool flag = false;
                                for (int i = 0; i < depositEntity.DepositDetails.Count; i++)
                                {
                                    if (depositEntity.DepositDetails[i].CorrespondingAccountNumber == depositDetailEntity.CorrespondingAccountNumber &&
                                        depositEntity.DepositDetails[i].BudgetItemCode == depositDetailEntity.BudgetItemCode &&
                                        depositEntity.DepositDetails[i].BudgetSourceCode == depositDetailEntity.BudgetSourceCode)
                                    {
                                        depositEntity.DepositDetails[i].AmountOc       = depositEntity.DepositDetails[i].AmountOc + depositDetailEntity.AmountOc;
                                        depositEntity.DepositDetails[i].AmountExchange = depositEntity.DepositDetails[i].AmountExchange + depositDetailEntity.AmountExchange;
                                        flag = true;
                                        //  break;
                                    }
                                }

                                if (flag == false)
                                {
                                    depositEntity.DepositDetails.Add(depositDetailEntity);
                                }
                                //Tính lại TotalAmountOc - TotalAmountExchange
                                depositEntity.TotalAmountOc       = depositEntity.TotalAmountOc + depositDetailEntity.AmountOc;
                                depositEntity.TotalAmountExchange = depositEntity.TotalAmountExchange +
                                                                    depositDetailEntity.AmountExchange;
                                //Get bank Acount
                                depositEntity.BankAccountCode = payItems.CreditAccountCode;
                            }
                        }
                    }
                    var cashRequest = new CashRequest();
                    var oCashFacade = new CashFacade();
                    cashRequest.Action = PersistType.Delete;
                    var cashForDelete = CashDao.GetCashByRefdateAndReftype(cashEntity);
                    if (cashForDelete != null)
                    {
                        cashRequest.RefId     = cashForDelete.RefId;
                        cashRequest.RefTypeId = cashForDelete.RefTypeId;
                        //    cashRequest.CashEntity = cashEntity;
                        oCashFacade.SetCashes(cashRequest);
                    }

                    var depositRequest = new DepositRequest();
                    var oDepositFacade = new DepositFacade();
                    depositRequest.Action = PersistType.Delete;
                    var depositForDelete = DepositDao.GetDepositByRefdateAndReftype(depositEntity);
                    if (depositForDelete != null)
                    {
                        depositRequest.RefId   = depositForDelete.RefId;
                        depositRequest.RefType = depositForDelete.RefTypeId;
                        //    depositRequest.Deposit = depositEntity;
                        oDepositFacade.SetDeposits(depositRequest);
                    }
                }
            }
            catch (Exception ex)
            {
                response.Acknowledge = AcknowledgeType.Failure;
                response.Message     = ex.Message;
                return(response);
            }
            response.Acknowledge = response.Message != null ? AcknowledgeType.Failure : AcknowledgeType.Success;
            return(response);
        }
Beispiel #14
0
        public SalaryVoucherResponse SetSalaryVouchers(SalaryVoucherRequest request)
        {
            var     response     = new SalaryVoucherResponse();
            string  currencyCode = "";
            decimal exchangeRate = 1;


            #region Ghi sổ

            if (request.LoadOptions.Contains("SaveSalaryVoucher"))
            {
                // Lấy voucherType là thực chi
                var voucherType = VoucherTypeDao.GetVoucherTypeByCode("SalaryVoucher") ?? new VoucherTypeEntity();
                // Lấy tất cả các loại khoản lương nhân viên
                List <EmployeeEntity> employees = EmployeeDao.GetEmployeesForSalaryInMonthAndRefNo(request.PostedDate, request.RefNo);

                var obj = SalaryVoucherDao.GetSalaryVoucherMonthDate(request.PostedDate).FirstOrDefault();
                if (obj != null)
                {
                    currencyCode = obj.CurrencyCode;
                    exchangeRate = obj.ExchangeRate;
                }

                //string[] words = request.PostedDate.Split('/');//Chuyển lại ngày tháng cho hợp lý trên C# # SQL
                DateTime postedDate = Convert.ToDateTime(request.PostedDate);

                var depositEntity = new DepositEntity()
                {
                    RefId                = 0,
                    RefTypeId            = request.ReftypeId, //
                    RefDate              = postedDate,        //DateTime.Parse(words[1] + "/" + words[0] + "/" + words[2]),
                    RefNo                = request.RefNo,
                    PostedDate           = postedDate,        //DateTime.Parse(words[1] + "/" + words[0] + "/" + words[2]),
                    AccountingObjectType = 1,
                    AccountingObjectId   = null,
                    Trader               = "",
                    CustomerId           = null,
                    VendorId             = null,
                    EmployeeId           = null, // mapper.EmployeeId,
                    BankAccountCode      = "112",
                    CurrencyCode         = currencyCode,
                    ExchangeRate         = exchangeRate,
                    TotalAmountOc        = 0, // employeePayItem.Amount,
                    TotalAmountExchange  = 0, // employeePayItem.Amount,
                    JournalMemo          =
                        "Chứng từ lương tháng " + postedDate.Month + "/" + postedDate.Year,
                };
                depositEntity.DepositDetails = new List <DepositDetailEntity>();
                var cashEntity = new CashEntity
                {
                    RefId               = 0,
                    RefTypeId           = request.ReftypeId, //
                    RefNo               = request.RefNo,
                    RefDate             = postedDate,        //DateTime.Parse(words[1] + "/" + words[0] + "/" + words[2]),
                    PostedDate          = postedDate,        //DateTime.Parse(words[1] + "/" + words[0] + "/" + words[2]),
                    AccountingObjectId  = null,
                    CustomerId          = null,
                    VendorId            = null,
                    Trader              = "",
                    CurrencyCode        = currencyCode,
                    ExchangeRate        = exchangeRate,
                    TotalAmount         = 0,
                    TotalAmountExchange = 0,
                    AccountNumber       = "",
                    JournalMemo         =
                        "Chứng từ lương tháng " + postedDate.Month + "/" + postedDate.Year,
                    DocumentInclude      = "",
                    AccountingObjectType = 1,
                    EmployeeId           = null,
                };
                cashEntity.CashDetails = new List <CashDetailEntity>();

                foreach (var employee in employees)
                {
                    //Từng nhân viên - từng khoảng lương - tiền tương ứng.
                    IList <EmployeePayItemEntity> listPayItems = EmployeePayItemDao.GetEmployeeForViewtEmployeePayItem(employee.EmployeeId, postedDate, exchangeRate);
                    foreach (var employeePayItemEntity in listPayItems)
                    {
                        var payItems = PayItemDao.GetPayItem(employeePayItemEntity.PayItemId);
                        //Chi
                        if (payItems != null && (payItems.CreditAccountCode ?? "").StartsWith("111"))
                        {
                            // khởi tạo phieu chi chi tiết
                            CashDetailEntity cashDetailEntity = new CashDetailEntity()
                            {
                                RefDetailId   = 0,
                                RefId         = 0,
                                AccountNumber = payItems.DebitAccountCode,
                                CorrespondingAccountNumber = payItems.CreditAccountCode,
                                Description        = payItems.PayItemName + " tháng " + postedDate.Month + "/" + postedDate.Year,
                                AmountOc           = employeePayItemEntity.Amount,
                                AmountExchange     = employeePayItemEntity.AmountExchange,
                                VoucherTypeId      = null, //voucherType.VoucherTypeId,
                                BudgetSourceCode   = payItems.BudgetSourceCode,
                                BudgetItemCode     = payItems.BudgetItemCode,
                                AccountingObjectId = null,
                                // dùng tạm MergerFundId để lưu payitemid
                                MergerFundId = payItems.PayItemId
                            };
                            bool flag = false;
                            for (int i = 0; i < cashEntity.CashDetails.Count; i++)
                            {
                                if (cashEntity.CashDetails[i].MergerFundId == cashDetailEntity.MergerFundId && cashEntity.CashDetails[i].CorrespondingAccountNumber == cashDetailEntity.CorrespondingAccountNumber && cashEntity.CashDetails[i].AccountNumber == cashDetailEntity.AccountNumber && cashEntity.CashDetails[i].BudgetItemCode == cashDetailEntity.BudgetItemCode && cashEntity.CashDetails[i].BudgetSourceCode == cashDetailEntity.BudgetSourceCode)
                                {
                                    cashEntity.CashDetails[i].AmountOc       = cashEntity.CashDetails[i].AmountOc + cashDetailEntity.AmountOc;
                                    cashEntity.CashDetails[i].AmountExchange = cashEntity.CashDetails[i].AmountExchange + cashDetailEntity.AmountExchange;
                                    flag = true;
                                }
                            }
                            if (flag == false)
                            {
                                if (cashDetailEntity.AmountOc > 0)
                                {
                                    cashEntity.CashDetails.Add(cashDetailEntity);
                                }
                            }
                            //Tính lại TotalAmountOc - TotalAmountExchange
                            cashEntity.TotalAmount         = cashEntity.TotalAmount + cashDetailEntity.AmountOc;
                            cashEntity.TotalAmountExchange = cashEntity.TotalAmountExchange + cashDetailEntity.AmountExchange;
                            //Get Bank Acount
                            cashEntity.AccountNumber = payItems.CreditAccountCode;
                        }
                        //Nợ
                        if (payItems != null && (payItems.CreditAccountCode ?? "").StartsWith("112"))
                        {
                            DepositDetailEntity depositDetailEntity = new DepositDetailEntity()
                            {
                                RefDetailId = request.ReftypeId,
                                RefId       = 0,
                                Description = payItems.PayItemName + " tháng " + postedDate.Month + "/" + postedDate.Year,

                                AccountNumber = payItems.DebitAccountCode,
                                CorrespondingAccountNumber = payItems.CreditAccountCode,
                                AmountOc           = employeePayItemEntity.Amount,
                                AmountExchange     = employeePayItemEntity.AmountExchange,
                                VoucherTypeId      = null, //voucherType.VoucherTypeId,
                                BudgetSourceCode   = payItems.BudgetSourceCode,
                                AccountingObjectId = null,
                                BudgetItemCode     = payItems.BudgetItemCode,
                                // dùng tạm MergerFundId để lưu payitemid
                                MergerFundId = payItems.PayItemId
                            };
                            bool flag = false;
                            for (int i = 0; i < depositEntity.DepositDetails.Count; i++)
                            {
                                // old
                                //if (depositEntity.DepositDetails[i].CorrespondingAccountNumber == depositDetailEntity.CorrespondingAccountNumber && depositEntity.DepositDetails[i].BudgetItemCode == depositDetailEntity.BudgetItemCode && depositEntity.DepositDetails[i].BudgetSourceCode == depositDetailEntity.BudgetSourceCode)
                                //{
                                //    depositEntity.DepositDetails[i].AmountOc = depositEntity.DepositDetails[i].AmountOc + depositDetailEntity.AmountOc;
                                //    depositEntity.DepositDetails[i].AmountExchange = depositEntity.DepositDetails[i].AmountExchange + depositDetailEntity.AmountExchange;
                                //    flag = true;
                                //}

                                if (depositEntity.DepositDetails[i].MergerFundId == depositDetailEntity.MergerFundId && depositEntity.DepositDetails[i].CorrespondingAccountNumber == depositDetailEntity.CorrespondingAccountNumber && depositEntity.DepositDetails[i].BudgetItemCode == depositDetailEntity.BudgetItemCode && depositEntity.DepositDetails[i].BudgetSourceCode == depositDetailEntity.BudgetSourceCode)
                                {
                                    depositEntity.DepositDetails[i].AmountOc       = depositEntity.DepositDetails[i].AmountOc + depositDetailEntity.AmountOc;
                                    depositEntity.DepositDetails[i].AmountExchange = depositEntity.DepositDetails[i].AmountExchange + depositDetailEntity.AmountExchange;
                                    flag = true;
                                }
                            }
                            if (flag == false)
                            {
                                if (depositDetailEntity.AmountOc > 0)
                                {
                                    depositEntity.DepositDetails.Add(depositDetailEntity);
                                }
                            }
                            //Tính lại TotalAmountOc - TotalAmountExchange
                            depositEntity.TotalAmountOc       = depositEntity.TotalAmountOc + depositDetailEntity.AmountOc;
                            depositEntity.TotalAmountExchange = depositEntity.TotalAmountExchange + depositDetailEntity.AmountExchange;
                            //Get bank Acount
                            depositEntity.BankAccountCode = payItems.CreditAccountCode;
                        }
                    }
                }

                // xóa MergerFundId đi không thì lưu nó lỗi á
                cashEntity.CashDetails.Select(c => { c.MergerFundId = null; return(c); }).ToList();
                depositEntity.DepositDetails.Select(c => { c.MergerFundId = null; return(c); }).ToList();

                long?cashId    = null;
                long?depositId = null;
                //Insert chứng từ phiếu chi
                var cashRequest = new CashRequest();
                var oCashFacade = new CashFacade();
                cashRequest.Action     = PersistType.Insert;
                cashRequest.CashEntity = cashEntity;
                // sinh định khoản đồng thời
                cashRequest.isAutoGenerateParallel = true;
                if (cashRequest.CashEntity.TotalAmount > 0)
                {
                    var cashResponse = oCashFacade.SetCashes(cashRequest);
                    cashId = cashResponse.RefId;
                }

                //Insert chứng từ giấy báo nợ
                var depositRequest = new DepositRequest();
                var oDepositFacade = new DepositFacade();
                depositRequest.Action  = PersistType.Insert;
                depositRequest.Deposit = depositEntity;
                if (depositRequest.Deposit.TotalAmountOc > 0)
                {
                    var depositRespone = oDepositFacade.SetDeposits(depositRequest, true);
                    depositId = depositRespone.RefId;
                }

                // update id phiếu chi, thu tiền gửi vào bảng
                string updateEmployeePayroll = SalaryVoucherDao.Update_EmployeePayroll_Voucher(request.RefNo, cashId, depositId);
            }


            #endregion

            #region Hủy tính ghi sổ + tính lương

            if (request.LoadOptions.Contains("CancelSalaryVoucher"))
            {
                var obj = SalaryVoucherDao.GetSalaryVoucherMonthDateIsPostedDate(request.PostedDate).FirstOrDefault();
                if (obj != null)
                {
                    currencyCode = obj.CurrencyCode;
                }



                var cashRequest = new CashRequest();
                var oCashFacade = new CashFacade();
                cashRequest.Action     = PersistType.Delete;
                cashRequest.CashEntity = CashDao.GetCash(SalaryVoucherDao.GetEmployeePayroll_VoucherID(request.RefNo, 201)); //CashDao.GetCashBySalary(request.ReftypeId, request.PostedDate, request.RefNo, currencyCode);

                var depositRequest = new DepositRequest();
                var oDepositFacade = new DepositFacade();
                depositRequest.Action  = PersistType.Delete;
                depositRequest.Deposit = DepositDao.GetDeposit(SalaryVoucherDao.GetEmployeePayroll_VoucherID(request.RefNo, 301)); //DepositDao.GetDepositsBySalary(request.ReftypeId, request.PostedDate, request.RefNo, currencyCode);

                //Xóa chứng từ lương ở phiểu chi
                if (cashRequest.CashEntity != null)
                {
                    cashRequest.RefId = cashRequest.CashEntity.RefId;
                    cashRequest.CashEntity.CashDetails = CashDetailDao.GetCashDetailsByCash(cashRequest.CashEntity.RefId);
                    if (cashRequest.CashEntity.CashDetails != null)
                    {
                        oCashFacade.SetCashes(cashRequest);
                        response.Message = CashDao.DeleteEmployeePayroll(cashRequest.CashEntity.RefNo,
                                                                         cashRequest.CashEntity.PostedDate.Month + "/" + cashRequest.CashEntity.PostedDate.Day + "/" + cashRequest.CashEntity.PostedDate.Year);
                    }
                }

                //Xóa chứng từ lương ở giấy báo nợ
                if (depositRequest.Deposit != null)
                {
                    depositRequest.RefId = depositRequest.Deposit.RefId;
                    depositRequest.Deposit.DepositDetails = DepositDetailDao.GetDepositDetailsByDeposit(depositRequest.Deposit.RefId);
                    if (depositRequest.Deposit.DepositDetails != null)
                    {
                        oDepositFacade.SetDeposits(depositRequest);
                        response.Message = DepositDao.DeleteEmployeePayroll(depositRequest.Deposit.RefNo,
                                                                            depositRequest.Deposit.PostedDate.Value.Month + "/" + depositRequest.Deposit.PostedDate.Value.Day + "/" + depositRequest.Deposit.PostedDate.Value.Year);
                    }
                }
            }

            #endregion

            #region  Hủy tính lương

            if (request.LoadOptions.Contains("CancelCalc"))
            {
                response.Message = SalaryVoucherDao.CanclCalc(request.PostedDate, request.RefNo);
            }

            #endregion

            return(response);
        }
Beispiel #15
0
        public async Task HandledDepositAsync(FireblocksDepositSignal deposit)
        {
            deposit.AddToActivityAsJsonTag("fireblocks-deposit");

            _logger.LogInformation("Request to handle deposit from fireblocks: {transferJson}",
                                   JsonConvert.SerializeObject(deposit));


            deposit.BrokerId.AddToActivityAsTag("brokerId");
            deposit.WalletId.AddToActivityAsTag("walletId");
            deposit.ClientId.AddToActivityAsTag("clientId");

            var accuracy = _assetsDictionary.GetAssetById(new AssetIdentity
            {
                Symbol   = deposit.AssetSymbol,
                BrokerId = deposit.BrokerId
            }).Accuracy;

            var amount = deposit.Amount;
            //var feeAmount = double.Parse(string.IsNullOrEmpty(deposit.PaymentInfo?.Fees?.Amount)
            //    ? "0.0"
            //    : deposit.PaymentInfo.Fees.Amount);

            var roundedAmount = Math.Round(amount, accuracy, MidpointRounding.ToNegativeInfinity);

            try
            {
                await using var ctx = DatabaseContext.Create(_dbContextOptionsBuilder);
                var existingEntity =
                    await ctx.Deposits.Where(e => e.TransactionId == deposit.TransactionId).FirstOrDefaultAsync();

                if (existingEntity == null)
                {
                    _logger.LogInformation("Got deposit from fireblocks, adding entry");
                    existingEntity = new DepositEntity
                    {
                        BrokerId      = deposit.BrokerId,
                        WalletId      = deposit.WalletId,
                        ClientId      = deposit.ClientId,
                        TransactionId = deposit.TransactionId,
                        Amount        = amount,
                        AssetSymbol   = deposit.AssetSymbol,
                        Comment       = "",
                        Integration   = "Fireblocks",
                        Txid          = deposit.TransactionId,
                        Status        = DepositStatus.New,
                        EventDate     = deposit.EventDate.ToUniversalTime(),
                        UpdateDate    = DateTime.UtcNow,
                        //FeeAmount = feeAmount,
                        FeeAssetSymbol = deposit.FeeAssetSymbol,
                        //    ? deposit.PaymentInfo.Amount.Currency
                        //    : deposit.PaymentInfo.Fees.Currency,
                        Network          = deposit.Network,
                        MatchingEngineId = "Deposit:" + Guid.NewGuid(),
                    };
                }
                else
                {
                    existingEntity.Amount     = amount;
                    existingEntity.UpdateDate = DateTime.UtcNow;
                    //existingEntity.FeeAmount = feeAmount;
                    existingEntity.FeeAssetSymbol = deposit.FeeAssetSymbol;
                }

                await ctx.UpsertAsync(existingEntity);

                await _depositPublisher.PublishAsync(new Deposit(existingEntity));
            }
            catch (Exception)
            {
                _logger.LogError("Unable to update deposit entry");
                throw;
            }

            _logger.LogInformation("Deposit request from Circle {transferIdString} is handled",
                                   deposit.TransactionId);
        }
        public async Task HandledDepositAsync(SignalCircleTransfer transfer)
        {
            transfer.AddToActivityAsJsonTag("circle-transfer");

            _logger.LogInformation("Request to handle transfer from Circle: {transferJson}",
                                   JsonConvert.SerializeObject(transfer));

            if (transfer.PaymentInfo.Source.Type != "blockchain" && transfer.PaymentInfo.Source.Type != "card")
            {
                _logger.LogInformation("Skip withdrawal transfer {type}", transfer.PaymentInfo.Source.Type);
                return;
            }

            transfer.BrokerId.AddToActivityAsTag("brokerId");
            transfer.WalletId.AddToActivityAsTag("walletId");
            transfer.ClientId.AddToActivityAsTag("clientId");

            var    circleAsset = _circleAssetMapper.CircleAssetToAsset(transfer.BrokerId, transfer.PaymentInfo.Amount.Currency);
            string asset       = null;

            if (transfer.PaymentInfo.Source.Type == "card")
            {
                asset = circleAsset?.AssetSymbol;
            }
            else if (transfer.PaymentInfo.Source.Type == "blockchain")
            {
                asset = circleAsset?.AssetTokenSymbol;
            }

            if (string.IsNullOrEmpty(asset))
            {
                _logger.LogError("Unknown circle asset {asset}", transfer.PaymentInfo.Amount.Currency);
                return;
            }

            var accuracy = _assetsDictionary.GetAssetById(new AssetIdentity
            {
                Symbol   = asset,
                BrokerId = transfer.BrokerId
            }).Accuracy;

            var amount    = (decimal)double.Parse(transfer.PaymentInfo.Amount.Amount);
            var feeAmount = (decimal)double.Parse(string.IsNullOrEmpty(transfer.PaymentInfo?.Fees?.Amount)
                ? "0.0"
                : transfer.PaymentInfo.Fees.Amount);

            var roundedAmount = Math.Round(amount - feeAmount, accuracy, MidpointRounding.ToNegativeInfinity);

            var isBlockchain     = transfer.PaymentInfo.Source.Type == "blockchain";
            var circleBlockchain =
                _circleBlockchainMapper.BlockchainToCircleBlockchain(transfer.BrokerId,
                                                                     transfer.PaymentInfo.Source.Chain);

            try
            {
                await using var ctx = DatabaseContext.Create(_dbContextOptionsBuilder);
                var existingEntity =
                    await ctx.Deposits.Where(e => e.TransactionId == transfer.PaymentInfo.Id).FirstOrDefaultAsync();

                if (existingEntity == null)
                {
                    _logger.LogInformation("Got unknown deposit from circle, adding entry");
                    existingEntity = new DepositEntity
                    {
                        BrokerId      = transfer.BrokerId,
                        WalletId      = transfer.WalletId,
                        ClientId      = transfer.ClientId,
                        TransactionId = transfer.PaymentInfo.Id,
                        Amount        = (decimal)roundedAmount,
                        AssetSymbol   = asset,
                        Comment       = isBlockchain
                            ? $"Circle blockchain {transfer.PaymentInfo.Source.Chain} deposit [{asset}]"
                            :
                                        $"Circle card deposit [{asset}:{transfer.WalletId}, card: {transfer.PaymentInfo.Source.Id}]",
                        Integration    = isBlockchain ? "CircleBlockchain" : "CircleCard",
                        Txid           = isBlockchain ? transfer.PaymentInfo.TransactionHash : transfer.PaymentInfo.Id,
                        Status         = ConvertExternalStatus(transfer.PaymentInfo.Status),
                        EventDate      = DateTime.UtcNow,
                        UpdateDate     = DateTime.UtcNow,
                        FeeAmount      = feeAmount,
                        FeeAssetSymbol = string.IsNullOrEmpty(transfer.PaymentInfo?.Fees?.Currency)
                            ? transfer.PaymentInfo.Amount.Currency
                            : transfer.PaymentInfo.Fees.Currency,
                        Network = circleBlockchain != null
                            ? circleBlockchain.Blockchain
                            : transfer.PaymentInfo.Source.Chain,
                        MatchingEngineId = "Deposit:" + Guid.NewGuid(),
                    };
                }
                else
                {
                    existingEntity.Amount         = roundedAmount;
                    existingEntity.UpdateDate     = DateTime.UtcNow;
                    existingEntity.FeeAmount      = feeAmount;
                    existingEntity.FeeAssetSymbol = string.IsNullOrEmpty(transfer.PaymentInfo?.Fees?.Currency)
                        ? transfer.PaymentInfo.Amount.Currency
                        : transfer.PaymentInfo.Fees.Currency;
                    existingEntity.Status = ConvertExternalStatus(transfer.PaymentInfo.Status);
                }

                await ctx.UpsertAsync(existingEntity);

                await _depositPublisher.PublishAsync(new Deposit(existingEntity));
            }
            catch (Exception)
            {
                _logger.LogError("Unable to update deposit entry");
                throw;
            }

            _logger.LogInformation("Deposit request from Circle {transferIdString} is handled",
                                   transfer.PaymentInfo.Id);
        }
        public async Task <int> UpsertAsync(DepositEntity entity)
        {
            var result = await Deposits.Upsert(entity).On(e => e.TransactionId).RunAsync();

            return(result);
        }