public void RemoveFromPairedEntitySetInDisconnectedSessionTest()
        {
            var configuration = base.BuildConfiguration();

            configuration.Types.Register(typeof(AccountingDocument).Assembly, typeof(AccountingDocument).Namespace);
            configuration.UpgradeMode = DomainUpgradeMode.PerformSafely;
            var defaultConfiguration = configuration.Sessions.Default;

            defaultConfiguration.Options = SessionOptions.ClientProfile | SessionOptions.AutoActivation;

            var domain = BuildDomain(configuration);

            using (var session = domain.OpenSession()) {
                var document = new AccountingDocument();
                for (var i = 0; i < 40; i++)
                {
                    document.Employees.Add(new Employee());
                }
                session.SaveChanges();

                var documentEntityes = document.Employees.ToList();
                foreach (var documentEntity in documentEntityes)
                {
                    document.Employees.Remove(documentEntity);
                }
                session.SaveChanges();
            }
        }
Beispiel #2
0
        private async Task <AccountingDocument> GetInformationForMonthEndTA(
            bool postOpClosedPrivilege,
            long docId,
            int docTypeId,
            AccountingSetupDto accountingSetup,
            Company company,
            DateTime companyDate,
            MonthEndTADocumentDto monthEndTADocument)
        {
            AccountingDocument accountingDocument = null;

            DateTime documentDate = new DateTime(monthEndTADocument.ValueDate.Value.Year, monthEndTADocument.ValueDate.Value.Month, 1).AddDays(-1);

            var fxRates = CommonRules.GetFxRateInformation(documentDate, monthEndTADocument.CurrencyCode, company);

            if (monthEndTADocument != null && fxRates.AreAllFilled())
            {
                accountingDocument = await CommonRules.CreateAccountingDocument(_masterDataService, _identityService.GetUserAtlasId(), postOpClosedPrivilege, docId, docTypeId, CommonRules.BaseCurrency, fxRates.FxRateInvoiceCurrency, accountingSetup, null, null, null, null, null, monthEndTADocument);

                if (accountingDocument != null)
                {
                    accountingDocument.AccountingDocumentLines = await CreateAccountingDocumentLines(docTypeId, company, accountingSetup, fxRates, null, null, null, null, null, null, monthEndTADocument);

                    accountingDocument.StatusId = await CommonRules.GetAccountingDocumentStatus(accountingSetup, _accountingQueries, accountingDocument, company.CompanyId, companyDate, null, null);
                }
            }

            return(accountingDocument);
        }
Beispiel #3
0
        internal static bool MandatoryFieldValidation(AccountingDocument accountingDocument)
        {
            bool isAnyNullOrEmpty = true;

            if (!IsNullOrEmptyOrZero(accountingDocument.AccountingPeriod) &&
                !IsNullOrEmptyOrZero(accountingDocument.DocumentDate) &&
                !IsNullOrEmptyOrZero(accountingDocument.GLDate) &&
                !IsNullOrEmptyOrZero(accountingDocument.AccountingDate) &&
                !IsNullOrEmptyOrZero(accountingDocument.TransactionDocumentTypeId) &&
                !IsNullOrEmptyOrZero(accountingDocument.CurrencyCode))
            {
                foreach (var accountingDocumentLine in accountingDocument.AccountingDocumentLines)
                {
                    if (!IsNullOrEmptyOrZero(accountingDocumentLine.PostingLineId) &&
                        !IsNullOrEmptyOrZero(accountingDocumentLine.AccountLineTypeId) &&
                        !IsNullOrEmptyOrZero(accountingDocumentLine.CostTypeCode) &&
                        !IsNullOrEmptyOrZero(accountingDocumentLine.DepartmentId) &&
                        !IsNullOrEmptyOrZero(accountingDocumentLine.AccountingCategoryId) &&
                        !IsNullOrEmptyOrZero(accountingDocumentLine.AccountReference))
                    {
                        isAnyNullOrEmpty = false;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            return(isAnyNullOrEmpty);
        }
Beispiel #4
0
        internal static bool CheckFxRateConverted(AccountingDocument accountingDocument)
        {
            bool isFunctionalCurrencyNull = accountingDocument.AccountingDocumentLines.Where(x => x.FunctionalCurrency == null).Count() == 0;
            bool isStatutoryCurrencyNull  = accountingDocument.AccountingDocumentLines.Where(x => x.StatutoryCurrency == null).Count() == 0;

            return(isFunctionalCurrencyNull && isStatutoryCurrencyNull);
        }
        public void RemoveFromEntitySetTest()
        {
            using (var session = Domain.OpenSession()) {
                Key documentKey;
                using (var transaction = session.OpenTransaction()) {
                    var document = new AccountingDocument();
                    documentKey = document.Key;
                    for (var i = 0; i < 40; i++)
                    {
                        document.Employees.Add(new Employee());
                    }
                    transaction.Complete();
                }

                using (var transaction = session.OpenTransaction()) {
                    var document         = session.Query.Single <AccountingDocument>(documentKey);
                    var documentEntityes = document.Employees.ToList();
                    foreach (var documentEntity in documentEntityes)
                    {
                        document.Employees.Remove(documentEntity);
                    }
                    transaction.Complete();
                }
            }
        }
Beispiel #6
0
        internal static bool CheckSanityCheck(AccountingDocument accountingDocument)
        {
            bool    isValid = accountingDocument.AccountingDocumentLines.Select(x => x.Amount).Sum() == 0;
            decimal remainingamount;

            if (isValid)
            {
                bool isFunctionalCurrencyConverted = accountingDocument.AccountingDocumentLines.Where(x => x.FunctionalCurrency == null).Count() == 0;
                bool isStatutoryCurrencyConverted  = accountingDocument.AccountingDocumentLines.Where(x => x.StatutoryCurrency == null).Count() == 0;
                if (isFunctionalCurrencyConverted)
                {
                    remainingamount = accountingDocument.AccountingDocumentLines.Select(x => (decimal)x.FunctionalCurrency).Sum();

                    if (remainingamount != 0)
                    {
                        accountingDocument.AccountingDocumentLines.OrderByDescending(x => Math.Abs((decimal)x.FunctionalCurrency)).FirstOrDefault().FunctionalCurrency = accountingDocument.AccountingDocumentLines.OrderByDescending(x => Math.Abs((decimal)x.FunctionalCurrency)).FirstOrDefault().FunctionalCurrency - remainingamount;
                    }
                }

                if (isStatutoryCurrencyConverted)
                {
                    remainingamount = accountingDocument.AccountingDocumentLines.Select(x => (decimal)x.StatutoryCurrency).Sum();

                    if (remainingamount != 0)
                    {
                        accountingDocument.AccountingDocumentLines.OrderByDescending(x => Math.Abs((decimal)x.StatutoryCurrency)).FirstOrDefault().StatutoryCurrency = accountingDocument.AccountingDocumentLines.OrderByDescending(x => Math.Abs((decimal)x.StatutoryCurrency)).FirstOrDefault().StatutoryCurrency - remainingamount;
                    }
                }
            }

            return(isValid);
        }
Beispiel #7
0
        public ActionResult DeleteConfirmed(int id)
        {
            AccountingDocument accountingDocument = db.AccountingDocuments.Find(id);

            db.AccountingDocuments.Remove(accountingDocument);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Beispiel #8
0
        internal static async Task <AccountingDocument> CalculateFunctionalAndStatutoryCurrencyAccountingLine(IForeignExchangeRateService foreignExchangeRateService, AccountingDocument document)
        {
            AccountingDocument accountingDocumentStatus = new AccountingDocument();

            accountingDocumentStatus.AccountingId = document.AccountingId;

            foreach (AccountingDocumentLine documentLine in document.AccountingDocumentLines)
            {
                documentLine.Amount = Math.Round(documentLine.Amount, CommonRules.RoundDecimals);

                decimal?amountInUSD = documentLine.Amount;

                if (document.CurrencyCode != null && document.CurrencyCode.ToUpperInvariant() != CommonRules.BaseCurrency)
                {
                    var result = await foreignExchangeRateService.Convert(document.CurrencyCode, CommonRules.BaseCurrency, documentLine.Amount, (DateTime)document.GLDate);

                    amountInUSD  = result.ConvertedValue;
                    document.Roe = result.Rate;
                }

                if (amountInUSD != null)
                {
                    documentLine.StatutoryCurrency = amountInUSD;

                    if (document.StatutoryCurrencyCode != null && document.StatutoryCurrencyCode.ToUpperInvariant() != CommonRules.BaseCurrency)
                    {
                        var result = await foreignExchangeRateService.Convert(CommonRules.BaseCurrency, document.StatutoryCurrencyCode, (decimal)amountInUSD, (DateTime)document.GLDate);

                        documentLine.StatutoryCurrency = result.ConvertedValue;
                    }

                    documentLine.FunctionalCurrency = amountInUSD;
                    if (document.FunctionalCurrencyCode != null && document.FunctionalCurrencyCode.ToUpperInvariant() != CommonRules.BaseCurrency)
                    {
                        var result = await foreignExchangeRateService.Convert(CommonRules.BaseCurrency, document.FunctionalCurrencyCode, (decimal)amountInUSD, (DateTime)document.GLDate);

                        documentLine.FunctionalCurrency = result.ConvertedValue;
                    }

                    if (documentLine.StatutoryCurrency != null)
                    {
                        documentLine.StatutoryCurrency = Math.Round((decimal)documentLine.StatutoryCurrency, CommonRules.RoundDecimals, MidpointRounding.AwayFromZero); // the default rounding option for .NET is MidPointRounding.ToEven, but that this option does not produce the desired result for some of values: -1119.965 was getting rounded to -1119.96 instead of -1119.97
                    }

                    if (documentLine.FunctionalCurrency != null)
                    {
                        documentLine.FunctionalCurrency = Math.Round((decimal)documentLine.FunctionalCurrency, CommonRules.RoundDecimals, MidpointRounding.AwayFromZero); // the default rounding option for .NET is MidPointRounding.ToEven, but that this option does not produce the desired result for some of values: -1119.965 was getting rounded to -1119.96 instead of -1119.97
                    }
                }
                else
                {
                    documentLine.FunctionalCurrency = null;
                    documentLine.StatutoryCurrency  = null;
                }
            }

            return(document);
        }
Beispiel #9
0
 public ActionResult Edit([Bind(Include = "AccountingDocumentId,Document,Description,SerialNumber,InitialNumber,FinalNumber,CurrentNumber,ResolutionNumber,ExpirationDate")] AccountingDocument accountingDocument)
 {
     if (ModelState.IsValid)
     {
         db.Entry(accountingDocument).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(accountingDocument));
 }
Beispiel #10
0
        public ActionResult Create([Bind(Include = "AccountingDocumentId,Document,Description,SerialNumber,InitialNumber,FinalNumber,ResolutionNumber,ExpirationDate")] AccountingDocument accountingDocument)
        {
            if (ModelState.IsValid)
            {
                db.AccountingDocuments.Add(accountingDocument);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(accountingDocument));
        }
        public void EntitySetStateCountsTest()
        {
            int addedItemsCount   = 0;
            int removedItemsCount = 0;

            using (var session = Domain.OpenSession()) {
                Key documentKey;
                Key employeeToRemoveKey;
                using (var transaction = session.OpenTransaction()) {
                    var document = new AccountingDocument();
                    documentKey = document.Key;
                    for (var i = 0; i < 40; i++)
                    {
                        document.Employees.Add(new Employee());
                        addedItemsCount++;
                    }
                    var employee = new Employee();
                    employeeToRemoveKey = employee.Key;
                    document.Employees.Add(employee);
                    addedItemsCount++;
                    var entitySetState = session.EntitySetChangeRegistry.GetItems().First();
                    Assert.AreEqual(addedItemsCount, entitySetState.CachedItemCount);
                    Assert.AreEqual(0, entitySetState.FetchedItemsCount);
                    Assert.AreEqual(addedItemsCount, entitySetState.AddedItemsCount);
                    Assert.AreEqual(removedItemsCount, entitySetState.RemovedItemsCount);
                    transaction.Complete();
                }

                using (var transaction = session.OpenTransaction()) {
                    var document = session.Query.Single <AccountingDocument>(documentKey);
                    var employee = session.Query.Single <Employee>(employeeToRemoveKey);
                    document.Employees.Remove(employee);
                    removedItemsCount++;
                    var entitySetState = session.EntitySetChangeRegistry.GetItems().First();
                    Assert.AreEqual(WellKnown.EntitySetPreloadCount + 1 - removedItemsCount, entitySetState.CachedItemCount);
                    Assert.AreEqual(WellKnown.EntitySetPreloadCount + 1, entitySetState.FetchedItemsCount);
                    Assert.AreEqual(0, entitySetState.AddedItemsCount);
                    Assert.AreEqual(removedItemsCount, entitySetState.RemovedItemsCount);

                    document.Employees.Prefetch(35);
                    Assert.AreEqual(35, entitySetState.CachedItemCount);
                    Assert.AreEqual(35, entitySetState.FetchedItemsCount);
                    Assert.AreEqual(0, entitySetState.AddedItemsCount);
                    Assert.AreEqual(0, entitySetState.RemovedItemsCount);
                    transaction.Complete();
                }

                using (var transaction = session.OpenTransaction()) {
                    var document  = session.Query.Single <AccountingDocument>(documentKey);
                    var employees = document.Employees.ToList();
                    Assert.AreEqual(addedItemsCount - removedItemsCount, employees.Count);
                }
            }
        }
Beispiel #12
0
        private void AddAccountingDocument(Invoice invoice, decimal totalPrice)
        {
            var accountingDocument = new AccountingDocument
            {
                InvoiceId = invoice.Id,
                DocumentRegistrationDate = (DateTime)invoice.CheckoutDate,
                DocumentNumber           = DateTime.UtcNow.ToShortDateString(),
                TotalPrice = totalPrice
            };

            _accountingDocumentRepository.Add(accountingDocument);
        }
Beispiel #13
0
        // GET: AccountingDocuments/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            AccountingDocument accountingDocument = db.AccountingDocuments.Find(id);

            if (accountingDocument == null)
            {
                return(HttpNotFound());
            }
            return(View(accountingDocument));
        }
        public void NonPairedEntitySetTest()
        {
            using (var session = Domain.OpenSession()) {
                Key documentKey;
                using (var transaction = session.OpenTransaction()) {
                    documentKey = new AccountingDocument().Key;
                    transaction.Complete();
                }

                using (var transaction = session.OpenTransaction()) {
                    var document = session.Query.Single <AccountingDocument>(documentKey);
                    document.Employees.Add(new Employee());
                    document.Employees.Add(new Employee());
                    transaction.Complete();
                }

                using (var transaction = session.OpenTransaction()) {
                    var document = session.Query.Single <AccountingDocument>(documentKey);
                    document.Employees.Add(new Employee());
                    document.Employees.Add(new Employee());
                }

                using (var transaction = session.OpenTransaction()) {
                    var document = session.Query.Single <AccountingDocument>(documentKey);
                    document.Employees.Add(new Employee());
                    document.Employees.Add(new Employee());
                    transaction.Complete();
                }

                using (var transaction = session.OpenTransaction()) {
                    var document = session.Query.Single <AccountingDocument>(documentKey);
                    for (var i = 0; i < 30; i++)
                    {
                        document.Employees.Add(new Employee());
                    }
                    transaction.Complete();
                }

                using (var transaction = session.OpenTransaction()) {
                    var document  = session.Query.Single <AccountingDocument>(documentKey);
                    var employees = document.Employees.ToList();
                    transaction.Complete();
                }
            }
        }
Beispiel #15
0
        public void Save(AccountingDocument entity)
        {
            try
            {
                if (entity.Id == Guid.Empty)
                {
                    entity.Id       = Guid.NewGuid();
                    entity.LastEdit = DateTime.Now;
                    this.Table.Add(entity);
                }

                this.SubmitChanges();
            }
            catch
            {
                throw;
            }
        }
        /// <summary>
        /// ثبت سند حسابداری
        /// </summary>
        /// <param name="date">تاریخ سند</param>
        /// <param name="salesInvoiceAmount">مبلغ یک کالا</param>
        /// <param name="salesInvoiceNumber">تعداد کالا</param>
        /// <param name="salesInvoiceId">شماره فاکتور فروش</param>
        /// <returns></returns>
        public bool RegistrationAccountingDocument(DateTime date, decimal salesInvoiceAmount, int salesInvoiceNumber, int salesInvoiceId)
        {
            try
            {
                AccountingDocument obj = new AccountingDocument();
                obj.DocumentDate   = date;
                obj.DocumentNumber = obj.CreateDocumentNumber();//شماره سند
                obj.Amount         = salesInvoiceAmount * salesInvoiceNumber;
                obj.SalesInvoiceId = salesInvoiceId;

                db.AccountingDocuments.Add(obj);
                db.SaveChanges();
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public void AddDoc(AddAccountingDocumentDto inputData)
        {
            var dataToAdd = new AccountingDocument
            {
                Id                     = Guid.NewGuid(),
                CreatedDate            = DateTime.Now,
                LastModifiedDate       = DateTime.Now,
                AccountingCodeId       = inputData.AccountingCodeId,
                BasicDefinitionId      = inputData.BasicDefinitionId,
                AccountingDocumentType = Enums.AccountingDocumentType.User,
                CurrencyType           = Enums.CurrencyType.Dollar,
                Price                  = inputData.Price,
                IsNegative             = inputData.IsNegative,
                Title                  = "[سند ثبتی]: " + inputData.Title,
                Description            = inputData.Description
            };

            dataToAdd.Price /= 130000;
            _repo.AddDoc(dataToAdd);
        }
Beispiel #18
0
        private async Task <(AccountingDocument, MonthEndTADocumentDto)> CreateAccountingForTAandJL(bool postOpClosedPrivilege, TransactionDocumentDto transactionDocument, long docId, int docTypeId, AccountingSetupDto accountingSetup, Company company, DateTime companyDate)
        {
            var monthEnd = await _accountingQueries.GetMonthEndTAbyTransactionDocumentId(company.CompanyId, docId);

            AccountingDocument accountingDocument = null;

            if (monthEnd == null)
            {
                accountingDocument = await GetInformationForManualJournal(postOpClosedPrivilege, docId, docTypeId, accountingSetup, company, companyDate);

                accountingDocument.StatusId     = transactionDocument.AuthorizedForPosting ? accountingDocument.StatusId : PostingStatus.Incomplete;
                accountingDocument.ErrorMessage = transactionDocument.AuthorizedForPosting ? accountingDocument.ErrorMessage : string.Empty;
            }
            else
            {
                accountingDocument = await GetInformationForMonthEndTA(postOpClosedPrivilege, docId, docTypeId, accountingSetup, company, companyDate, monthEnd);
            }

            return(accountingDocument, monthEnd);
        }
        public async Task <SectionPostingStatus> UpdateAccountingDocument(AccountingDocument accountingDocument, string company)
        {
            DynamicParameters queryParameters = new DynamicParameters();

            queryParameters.Add("@AccountingDocumentId", accountingDocument.AccountingId);
            queryParameters.Add("@CurrencyCode", accountingDocument.CurrencyCode);
            queryParameters.Add("@AccountingPeriod", accountingDocument.AccountingPeriod);
            queryParameters.Add("@DocumentDate", accountingDocument.DocumentDate);
            queryParameters.Add("@ValueDate", accountingDocument.ValueDate);
            queryParameters.Add("@GLDate", accountingDocument.GLDate);
            queryParameters.Add("@CompanyId", company);
            queryParameters.Add("@ToInterface", accountingDocument.ToInterface);
            queryParameters.Add("@DmsId", accountingDocument.DmsId);
            queryParameters.Add("@StatusId", accountingDocument.StatusId);
            queryParameters.Add("@ErrorMessage", accountingDocument.ErrorMessage);
            queryParameters.Add("@AccountingLines", ConvertAccountingDocumentLinesIntoDataTable(accountingDocument.AccountingDocumentLines, isUpdate: true));
            IEnumerable <SectionPostingStatus> sectionPostingStatus = await ExecuteQueryAsync <SectionPostingStatus>(StoredProcedureNames.UpdateAccountingDocument, queryParameters, true);

            return(sectionPostingStatus.AsList <SectionPostingStatus>().FirstOrDefault());
        }
Beispiel #20
0
        public async Task <SectionPostingStatus> Handle(UpdateAccountingDocumentCommand request, CancellationToken cancellationToken)
        {
            _unitOfWork.BeginTransaction();

            try
            {
                SectionPostingStatus reference;
                AccountingDocument   accountingDocument = new AccountingDocument();

                accountingDocument = await MapCommandToAccountingDocument(request);

                var isJLorTADocument = (accountingDocument.TransactionDocumentTypeId == (int)DocumentType.MTA || accountingDocument.TransactionDocumentTypeId == (int)DocumentType.MJL) ? true : false;
                var isPostedType     = accountingDocument.StatusId == PostingStatus.Posted ? true : false;

                var authorizationEditAccountingEntriesPolicy = await _authorizationService.AuthorizeAsync(_identityService.GetUser(), accountingDocument, Policies.EditAccountingEntriesPolicy);

                var authorizationCreateEditDocumentPolicy = await _authorizationService.AuthorizeAsync(_identityService.GetUser(), accountingDocument, Policies.CreateEditDocumentPolicy);

                var authorizationPostingManagementPolicy = await _authorizationService.AuthorizeAsync(_identityService.GetUser(), accountingDocument, Policies.PostingManagementPolicy);

                if ((authorizationEditAccountingEntriesPolicy.Succeeded && isPostedType) || ((authorizationCreateEditDocumentPolicy.Succeeded && isJLorTADocument) || (authorizationPostingManagementPolicy.Succeeded && !isJLorTADocument)))
                {
                    reference = await _accountingDocumentRepository.UpdateAccountingDocument(accountingDocument, request.Company);
                }
                else
                {
                    throw new AtlasSecurityException("One or more privileges are required to perform this action.");
                }

                _unitOfWork.Commit();

                _logger.LogInformation("Accounting Document updated", reference.PostingStatusId);
                return(reference);
            }
            catch
            {
                _unitOfWork.Rollback();

                throw;
            }
        }
        private async Task <AccountingDocument> CreateAccountingDocumentForFxDeal(bool postOpClosedPolicy, long docId, int docTypeId, AccountingSetupDto accountingSetup, Company company, string companyId, DateTime companyDate)
        {
            AccountingDocument      accountingDocument   = new AccountingDocument();
            FxSettlementDocumentDto fxSettlementDocument = null;
            FxRateInformation       fxRates = null;

            fxSettlementDocument = await _accountingQueries.GetFxSettlementbyTransactionDocumentId(docId, company.CompanyId);

            if (fxSettlementDocument.FxSettlementDocumentTypeId == FxSettlementDocumentType.FxDeal)
            {
                fxRates = CommonRules.GetFxRateInformation(fxSettlementDocument.DocumentDate, fxSettlementDocument.CurrencyCode, company);
            }
            else
            {
                fxRates = CommonRules.GetFxRateInformation(fxSettlementDocument.DocumentDate, fxSettlementDocument.SettlementCurrencyCode, company);
            }

            if (fxSettlementDocument != null && fxRates.AreAllFilled())
            {
                accountingDocument = await CommonRules.CreateAccountingDocument(_masterDataService, _identityService.GetUserAtlasId(), postOpClosedPolicy, docId, docTypeId, CommonRules.BaseCurrency, fxRates.FxRateInvoiceCurrency, accountingSetup, null, null, null, null, null, null, null, null, fxSettlementDocument);

                accountingDocument.AccountingPeriod = CommonRules.CalculateAccountPeriod(accountingSetup, fxSettlementDocument.DocumentDate, postOpClosedPolicy);
                accountingDocument.AccrualNumber    = CommonRules.IsLastMonthForOperationOpen(accountingSetup.LastMonthClosedForOperation, fxSettlementDocument.DocumentDate) ?
                                                      fxSettlementDocument.AccrualNumber :
                                                      null;
                accountingDocument.AccountingDate = accountingDocument.DocumentDate.Year == accountingDocument.AccountingPeriod.Year &&
                                                    accountingDocument.DocumentDate.Month == accountingDocument.AccountingPeriod.Month ?
                                                    accountingDocument.DocumentDate :
                                                    new DateTime(accountingDocument.AccountingPeriod.Year, accountingDocument.AccountingPeriod.Month, 1);

                if (accountingDocument != null)
                {
                    accountingDocument.AccountingDocumentLines = await CreateAccountingDocumentLines(docTypeId, company, accountingSetup, fxRates, null, null, null, null, null, null, null, fxSettlementDocument);

                    accountingDocument.StatusId = await CommonRules.GetAccountingDocumentStatus(accountingSetup, _accountingQueries, accountingDocument, company.CompanyId, companyDate, null, null);
                }
            }

            return(accountingDocument);
        }
Beispiel #22
0
        private async Task <IEnumerable <AccountingDocument> > CreateAccountingDocumentPerAccuralNumberTA(AccountingDocument accountingDocumentTA, MonthEndTADocumentDto monthEnd, string company, long docId)
        {
            List <AccountingDocument> accountingDocuments = new List <AccountingDocument>();

            IEnumerable <int> uniqueAccruals = accountingDocumentTA.AccountingDocumentLines.Where(t => t.AccrualNumber != null).Select(x => x.AccrualNumber).Distinct().Cast <int>();

            foreach (int uniqueAccrual in uniqueAccruals)
            {
                AccountingDocument adJL = accountingDocumentTA.ShallowCopy();
                adJL.AccrualNumber = uniqueAccrual;
                if (monthEnd != null)
                {
                    adJL.GLDate = monthEnd.MonthEndTALines.Where(x => x.AccrualNumber == uniqueAccrual).FirstOrDefault().BLDate;
                }

                adJL.AccountingDocumentLines = adJL.AccountingDocumentLines.Where(x => x.AccrualNumber == uniqueAccrual);

                accountingDocuments.Add(adJL);
            }

            return(accountingDocuments);
        }
Beispiel #23
0
        private async Task <AccountingDocument> GetInformationForManualJournal(bool postOpClosedPolicy, long docId, int docTypeId, AccountingSetupDto accountingSetup, Company company, DateTime companyDate)
        {
            AccountingDocument accountingDocument = null;

            ManualJournalDocumentDto manualJournal = null;

            manualJournal = await _accountingQueries.GetManualJournalbyTransactionDocumentId(docId, company.CompanyId);

            var fxRates = CommonRules.GetFxRateInformation(manualJournal.DocumentDate, manualJournal.CurrencyCode, company);

            if (manualJournal != null && fxRates.AreAllFilled())
            {
                accountingDocument = await CommonRules.CreateAccountingDocument(_masterDataService, _identityService.GetUserAtlasId(), postOpClosedPolicy, docId, docTypeId, CommonRules.BaseCurrency, fxRates.FxRateInvoiceCurrency, accountingSetup, null, null, null, manualJournal);

                if (accountingDocument != null)
                {
                    accountingDocument.AccountingDocumentLines = await CreateAccountingDocumentLines(docTypeId, company, accountingSetup, fxRates, null, null, null, null, manualJournal);

                    accountingDocument.StatusId = await CommonRules.GetAccountingDocumentStatus(accountingSetup, _accountingQueries, accountingDocument, company.CompanyId, companyDate, null, null);
                }
            }

            return(accountingDocument);
        }
Beispiel #24
0
        private async Task <PostingStatus> ReturnAccountingDocumentStatus(AccountingDocument accountingDocument, DateTime companyDate, string company, AccountingSetupDto accountingSetup)
        {
            accountingDocument.ErrorMessage = string.Empty;

            // Sanity Check
            bool isLegSumValid = CommonRules.CheckSanityCheck(accountingDocument);
            MappingErrorMessages messages;

            if (isLegSumValid)
            {
                if (CommonRules.CheckFxRateConverted(accountingDocument))
                {
                    bool ifInterface = await CommonRules.CheckIfInterface(_accountingQueries, accountingDocument.TransactionDocumentId, company);

                    messages = await CommonRules.CheckMappingError(_accountingQueries, accountingDocument.AccountingDocumentLines, company, accountingDocument.TransactionDocumentTypeId);

                    if (ifInterface)
                    {
                        if (messages.C2CCode == null)
                        {
                            accountingDocument.ErrorMessage = "C2C Code Is NULL ;";
                        }

                        if (!messages.CostAlternativeCode)
                        {
                            accountingDocument.ErrorMessage += "Cost Alternative Code  Is NULL ;";
                        }

                        if (!messages.TaxInterfaceCode)
                        {
                            accountingDocument.ErrorMessage += "Tax Interface Code Is NULL ;";
                        }

                        if (messages.DepartmentAlternativeCode == null)
                        {
                            accountingDocument.ErrorMessage += "Department Alternative Code Is NULL ;";
                        }

                        if (!messages.NominalAlternativeAccount)
                        {
                            accountingDocument.ErrorMessage += "Nominal Alternative Code Is NULL ;";
                        }

                        if (!string.IsNullOrEmpty(accountingDocument.ErrorMessage))
                        {
                            return(PostingStatus.MappingError);
                        }
                    }

                    if (CommonRules.MandatoryFieldValidation(accountingDocument))
                    {
                        accountingDocument.ErrorMessage = "Mandatory Field Missing";

                        return(PostingStatus.Held);
                    }

                    if (accountingDocument.DocumentDate.Date > companyDate.Date)
                    {
                        accountingDocument.ErrorMessage = "Future document date";
                        return(PostingStatus.Held);
                    }

                    if (!CommonRules.IsLastMonthForAccountingOpen(accountingSetup.LastMonthClosed, accountingDocument.AccountingDate, accountingSetup.NumberOfOpenPeriod))
                    {
                        accountingDocument.ErrorMessage = "Month is not yet open for accounting period";
                        return(PostingStatus.Held);
                    }

                    return(PostingStatus.Authorised);
                }
                else
                {
                    accountingDocument.ErrorMessage = "No Fxrates Found";
                    return(PostingStatus.Held);
                }
            }
            else
            {
                accountingDocument.ErrorMessage = "Unbalanced document";
                return(PostingStatus.Held);
            }
        }
        /// <summary>
        /// فاکتور فروش
        /// </summary>
        /// <param name="storeOrder"></param>
        /// <param name="document"></param>
        public void SaveAutomaticForSaleReturnInvoice(StoreOrder storeOrder, AccountingDocument document)
        {
            try
            {
                var accountingArticles       = new List <Data.AccountingArticle>();
                var accountingTafsilArticles = new List <Data.AccountingTafsilArticle>();
                var dictionary = new Dictionary <Data.AccountingArticle, Data.AccountingTafsilArticle>();

                var company = Business.GetCompanyBusiness().GetById(storeOrder.IdCompany.Value);
                if (!company.IdAccountingTafsillevelsDetails.HasValue)
                {
                    throw new Exception(string.Format(Localize.ex_company_no_accountingtafsillevelsdetails, company.CName));
                }
                var storeOrderDetails = Business.GetStoreOrderDetailBusiness().GetByStoreOrderId(storeOrder.Id).ToList();

                var accountingArticle = new AccountingArticle()
                {
                    IDAccountingDocument = document.Id,
                    ADescription         = null,
                    ADebtor   = null,
                    ACreditor = storeOrder.OSumMoney,
                    ACount    = 1
                };
                accountingArticles.Add(accountingArticle);

                var companyTafsilLevelsDetail         = Business.GetAccountingTafsilLevelDetailBusiness().GetById(company.IdAccountingTafsillevelsDetails.Value);
                var companyTafsilLevel                = Business.GetAccountingTafsilLevelBusiness().GetById(companyTafsilLevelsDetail.IdAccountingTafsilLevels.Value);
                var companyAccountingMoeinTafsilLevel = Business.GetAccountingMoeinTafsilLevelBusiness().GetByIdAccountingTafsilLevels(companyTafsilLevel.Id);

                var accountingTafsilArticle = new AccountingTafsilArticle()
                {
                    IDAccountingMoein          = companyAccountingMoeinTafsilLevel.IdAccountingMoein,
                    IdAccountingTafsilLDetails = companyTafsilLevelsDetail.Id,
                    //IdAccountingTafsilLevels = tafsilLevel.Id
                };

                accountingTafsilArticles.Add(accountingTafsilArticle);

                dictionary.Add(accountingArticle, accountingTafsilArticle);

                var commodities = Business.GetGoodiesBusiness().GetByIds(storeOrderDetails.Select(r => r.IdCommodity).ToList()).ToList();
                if (commodities.Any(r => !r.IdAccountingTafsillevelsDetails.HasValue))
                {
                    throw new Exception(string.Format(Localize.ex_commodity_no_accountingtafsillevelsdetails, commodities.First(r => !r.IdAccountingTafsillevelsDetails.HasValue).CName));
                }
                var tafsilLevelsDetails         = Business.GetAccountingTafsilLevelDetailBusiness().GetByIds(commodities.Where(r => r.IdAccountingTafsillevelsDetails.HasValue).Select(r => r.IdAccountingTafsillevelsDetails.Value).ToList());
                var tafsilLevels                = Business.GetAccountingTafsilLevelBusiness().GetByIds(tafsilLevelsDetails.Where(r => r.IdAccountingTafsilLevels.HasValue).Select(r => r.IdAccountingTafsilLevels.Value).ToList());
                var accountingMoeinTafsilLevels = Business.GetAccountingMoeinTafsilLevelBusiness().GetByIdAccountingTafsilLevels(tafsilLevels.Select(r => r.Id).ToList()).ToList();

                foreach (var item in storeOrderDetails)
                {
                    accountingArticle = new AccountingArticle()
                    {
                        IDAccountingDocument = document.Id,
                        ADescription         = item.ODDescription,
                        ADebtor   = item.ODMoney,
                        ACreditor = null,
                        ACount    = item.ODCount
                    };
                    accountingArticles.Add(accountingArticle);

                    var commodity                  = commodities.Find(r => r.ID == item.IdCommodity);
                    var tafsilLevelDetail          = tafsilLevelsDetails.Find(r => r.Id == commodity.IdAccountingTafsillevelsDetails);
                    var tafsilLevel                = tafsilLevels.Find(r => r.Id == tafsilLevelDetail.IdAccountingTafsilLevels);
                    var accountingMoeinTafsilLevel = accountingMoeinTafsilLevels.Find(r => r.IdAccountingTafsilLevels == tafsilLevel.Id);

                    accountingTafsilArticle = new AccountingTafsilArticle()
                    {
                        IDAccountingMoein          = accountingMoeinTafsilLevel.IdAccountingMoein,
                        IdAccountingTafsilLDetails = tafsilLevelDetail.Id,
                        //IdAccountingTafsilLevels = tafsilLevel.Id
                    };
                    accountingTafsilArticles.Add(accountingTafsilArticle);

                    dictionary.Add(accountingArticle, accountingTafsilArticle);
                }
                this.Save(accountingArticles);

                foreach (var item in dictionary)
                {
                    item.Value.IdAccountingArticle = item.Key.ID;
                }

                Business.GetAccountingTafsilArticleBusiness().Save(accountingTafsilArticles);
            }
            catch
            {
                throw;
            }
        }
Beispiel #26
0
        private async Task <AccountingDocument> MapCommandToAccountingDocument(UpdateAccountingDocumentCommand command)
        {
            AccountingDocument accountingDocument = new AccountingDocument();

            accountingDocument.AccountingPeriod          = command.AccountingPeriod;
            accountingDocument.AccountingId              = command.AccountingId;
            accountingDocument.CurrencyCode              = command.CurrencyCode;
            accountingDocument.DocumentDate              = command.DocumentDate;
            accountingDocument.ValueDate                 = command.ValueDate;
            accountingDocument.ToInterface               = command.ToInterface;
            accountingDocument.DmsId                     = command.DmsId;
            accountingDocument.TransactionDocumentTypeId = (int)command.TransactionDocumentTypeId;
            if (command.StatusId == PostingStatus.Posted)
            {
                accountingDocument.StatusId = command.StatusId;
            }
            else if (!command.IsAuthorizedControlEnabled)
            {
                accountingDocument.StatusId = PostingStatus.Incomplete;
            }

            accountingDocument.AccountingDocumentLines = command.AccountingDocumentLines;

            Company company = await _masterDataService.GetCompanyByIdAsync(command.Company);

            var fxRates = CommonRules.GetFxRateInformation(accountingDocument.DocumentDate, accountingDocument.CurrencyCode, company);

            if (fxRates.FxRateInvoiceCurrency != null)
            {
                foreach (AccountingDocumentLine accountingDocumentLine in accountingDocument.AccountingDocumentLines)
                {
                    if (accountingDocumentLine.AccountingCategoryId <= 0 && accountingDocumentLine.AccountLineTypeId >= 1)
                    {
                        if (accountingDocumentLine.AccountLineTypeId == (int)AccountLineType.C || accountingDocumentLine.AccountLineTypeId == (int)AccountLineType.V)
                        {
                            accountingDocumentLine.AccountingCategoryId = (int)AccountingCategory.C;
                        }
                        else if (accountingDocumentLine.AccountLineTypeId == (int)AccountLineType.B || accountingDocumentLine.AccountLineTypeId == (int)AccountLineType.L)
                        {
                            accountingDocumentLine.AccountingCategoryId = (int)AccountingCategory.N;
                        }
                    }

                    if (string.IsNullOrEmpty(accountingDocumentLine.Narrative) && accountingDocument.TransactionDocumentTypeId == (int)DocumentType.MTA)
                    {
                        accountingDocumentLine.Narrative = "Manual Accrual of " + accountingDocument.AccountingPeriod.ToString("MMM-yyyy", CultureInfo.InvariantCulture);
                    }

                    accountingDocumentLine.Amount = Math.Round(accountingDocumentLine.Amount, CommonRules.RoundDecimals);

                    decimal?amountInUSD = accountingDocumentLine.Amount;

                    if (accountingDocument.CurrencyCode != null && accountingDocument.CurrencyCode.ToUpperInvariant() != CommonRules.BaseCurrency)
                    {
                        amountInUSD = (await _foreignExchangeRateService.Convert(fxRates.FxRateInvoiceCurrency.FxCurrency, CommonRules.BaseCurrency, accountingDocumentLine.Amount, fxRates.FxRateInvoiceCurrency.FxDate)).ConvertedValue;
                    }

                    await CommonRules.CalculateFunctionalAndStatutoryCurrency(_foreignExchangeRateService, accountingDocumentLine, amountInUSD, fxRates, company, CommonRules.BaseCurrency, CommonRules.RoundDecimals);
                }
            }

            accountingDocument.GLDate = command.GLDate;
            return(accountingDocument);
        }
Beispiel #27
0
        internal static async Task <PostingStatus> GetAccountingDocumentStatus(AccountingSetupDto accountingSetup, IAccountingDocumentQueries accountingQuerie, AccountingDocument accountingDocument, string company, DateTime companyDate, InvoiceInformationDto invoiceInformation = null, CashInformationDto cashInformation = null, RevaluationInformationDto revalInformation = null, CounterpartyInformationDto counterpartyInformation = null)
        {
            accountingDocument.ErrorMessage = string.Empty;

            if (invoiceInformation != null)
            {
                if (!CheckPostingForAuthorized(invoiceInformation))
                {
                    return(PostingStatus.Incomplete);
                }
            }
            else if (cashInformation != null)
            {
                if (!CheckPostingForAuthorized(null, cashInformation))
                {
                    return(PostingStatus.Incomplete);
                }
            }
            else if (revalInformation != null)
            {
                if (!CheckPostingForAuthorized(null, null, revalInformation))
                {
                    return(PostingStatus.Incomplete);
                }
            }
            else if (counterpartyInformation != null)
            {
                if (!CheckPostingForAuthorized(null, null, null, counterpartyInformation))
                {
                    return(PostingStatus.Incomplete);
                }
            }

            if (CheckSanityCheck(accountingDocument))
            {
                if (CheckFxRateConverted(accountingDocument))
                {
                    bool ifInterface = await CheckIfInterface(accountingQuerie, accountingDocument.TransactionDocumentId, company);

                    MappingErrorMessages messages = await CheckMappingError(accountingQuerie, accountingDocument.AccountingDocumentLines, company, accountingDocument.TransactionDocumentTypeId);

                    if (ifInterface)
                    {
                        if (!messages.C2CCode)
                        {
                            accountingDocument.ErrorMessage = "C2C Code Is NULL ;";
                        }

                        if (!messages.CostAlternativeCode)
                        {
                            accountingDocument.ErrorMessage += "Cost Alternative Code Is NULL ;";
                        }

                        if (!messages.TaxInterfaceCode)
                        {
                            accountingDocument.ErrorMessage += "Tax Interface Code Is NULL ;";
                        }

                        if (!messages.NominalAlternativeAccount)
                        {
                            accountingDocument.ErrorMessage += "Nominal Alternative Code Is NULL ;";
                        }

                        if (!messages.DepartmentAlternativeCode)
                        {
                            accountingDocument.ErrorMessage += "Department Alternative Code Is NULL ;";
                        }

                        if (!string.IsNullOrEmpty(accountingDocument.ErrorMessage))
                        {
                            return(PostingStatus.MappingError);
                        }
                    }

                    if (MandatoryFieldValidation(accountingDocument))
                    {
                        accountingDocument.ErrorMessage = "Mandatory Field Missing";

                        return(PostingStatus.Held);
                    }

                    if (CheckFutureDate(accountingDocument, companyDate))
                    {
                        accountingDocument.ErrorMessage = "Future document date";
                        return(PostingStatus.Held);
                    }
                    if (!IsMonthOpenForAccounting(accountingSetup.LastMonthClosed, accountingDocument.AccountingDate, accountingSetup.NumberOfOpenPeriod))
                    {
                        accountingDocument.ErrorMessage = "Period is not open for accounting";
                        return(PostingStatus.Held);
                    }

                    return(PostingStatus.Authorised);
                }
                else
                {
                    accountingDocument.ErrorMessage = "No Fxrate found";
                    return(PostingStatus.Held);
                }
            }
            else
            {
                accountingDocument.ErrorMessage = "Unbalanced document";
                return(PostingStatus.Held);
            }
        }
Beispiel #28
0
 internal static bool CheckFutureDate(AccountingDocument accountingDocument, DateTime companyDate)
 {
     return(accountingDocument.DocumentDate.Date > companyDate.Date);
 }
Beispiel #29
0
 public void AddAccountingDo(AccountingDocument model)
 {
     _accountingDoc.Add(model);
 }
Beispiel #30
0
        public ActionResult Create(NewSaleView view)
        {
            if (ModelState.IsValid)
            {
                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        AccountingDocument dn = (from x in db.AccountingDocuments orderby x.InitialNumber descending select x).FirstOrDefault();
                        var docnumber         = dn.InitialNumber + 1;

                        var sale = new Sale
                        {
                            Datetime             = view.Date,
                            CellarId             = view.CellarId,
                            ClientId             = view.ClientId,
                            AccountingDocumentId = view.AccountingDocumentId,
                            PaymentMethodId      = view.PaymentMethodId,
                            DocumentNumber       = docnumber,
                        };

                        db.Sales.Add(sale);
                        db.SaveChanges();

                        var details = db.SaleDetailBkps.Where(pdb => pdb.User == User.Identity.Name).ToList();
                        foreach (var detail in details)
                        {
                            var saleDetail = new SaleDetail
                            {
                                SaleId        = sale.SaleId,
                                ProductId     = detail.ProductId,
                                Description   = detail.Description,
                                Price         = detail.Price,
                                Quantity      = detail.Quantity,
                                IVAPercentage = detail.IVAPercentage,
                                DiscountRate  = detail.DiscountRate
                            };


                            db.SaleDetails.Add(saleDetail);
                            db.SaleDetailBkps.Remove(detail);
                            var status = true;


                            if (status == true)
                            {
                                CellarProduct c = (from x in db.CellarProducts
                                                   where x.ProductId == detail.ProductId
                                                   select x).First();
                                c.Stock = c.Stock - detail.Quantity;
                                db.SaveChanges();
                            }
                        }



                        db.SaveChanges();
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        ModelState.AddModelError(string.Empty, ex.Message);
                    }
                }

                return(RedirectToAction("Index"));
            }

            ViewBag.CellarId             = new SelectList(db.Cellars, "CellarId", "Description", view.CellarId);
            ViewBag.ClientId             = new SelectList(db.Clients, "ClientId", "Cliente", view.ClientId);
            ViewBag.AccountingDocumentId = new SelectList(db.AccountingDocuments, "AccountingDocumentId", "Tipo de Documento", view.AccountingDocumentId);
            ViewBag.PaymentMethodId      = new SelectList(db.PaymentMethods, "PaymentMethodId", "Metodo de Pago", view.PaymentMethodId);
            view.Details = db.SaleDetailBkps.Where(pdb => pdb.User == User.Identity.Name).ToList();
            return(View(view));
        }