public static FaceAuthCard ProcessFaceAuthentication(NewRequest <SmartDoc> newReq)
        {
            FaceAuthCard result = DocumentMapper.MapDocument <FaceAuthCard>(newReq.RequestItem);

            result.DetectionNotes = "Invalid Face Verification";

            var faceStep = newReq.RequestItem.CognitivePipelineActions.Where(s => s.StepName == InstructionFlag.FaceAuthentication.ToString()).FirstOrDefault();

            if (faceStep != null)
            {
                var faceResult = JsonConvert.DeserializeObject <FaceAuth>(faceStep.Output);

                result.DetectedFaceName = "";

                //TODO: Update Owner Id to be verified against other faces than Request/Document Owner
                result.DetectedFaceOwnerId        = newReq.RequestItem.OwnerId;
                result.IsAuthenticationSuccessful = faceResult.IsIdentical;
                result.FaceDetails    = faceResult;
                result.DetectionNotes = faceResult.IsIdentical ? "Successful Face Verification" : "Invalid Face Verification";

                return(result);
            }

            return(result);
        }
Exemplo n.º 2
0
        public static bool TryCloseSalesOrder(CommercialDocument salesOrder)
        {
            if (salesOrder.DocumentType.DocumentCategory != DocumentCategory.SalesOrder)
            {
                return(false);
            }
            DocumentMapper mapper = DependencyContainerManager.Container.Get <DocumentMapper>();

            mapper.AddItemsToItemTypesCache(salesOrder);
            var dict = SessionManager.VolatileElements.ItemTypesCache;

            //sprawdzamy czy zamowienie ma wszelkie wz-ty i rw na pozycjach z towarami (pomijamy uslugi)
            foreach (var line in salesOrder.Lines)
            {
                if (!DictionaryMapper.Instance.GetItemType(dict[line.ItemId]).IsWarehouseStorable)
                {
                    continue;
                }

                decimal relQuantity = line.CommercialWarehouseRelations.Sum(r => r.Quantity);

                if (line.Quantity != relQuantity)
                {
                    return(false);
                }
            }

            SalesOrderFactory.CloseSalesOrder(salesOrder);
            salesOrder.DocumentStatus = DocumentStatus.Committed;

            return(true);
        }
Exemplo n.º 3
0
        public static void CreateCorrectiveDocument(XElement source, CommercialDocument destination)
        {
            Guid           sourceDocumentId = new Guid(source.Element("correctedDocumentId").Value);
            DocumentMapper mapper           = DependencyContainerManager.Container.Get <DocumentMapper>();

            ICollection <Guid> previousDocumentsId = mapper.GetCommercialCorrectiveDocumentsId(sourceDocumentId);

            CommercialDocument sourceDocument = (CommercialDocument)mapper.LoadBusinessObject(BusinessObjectType.CommercialDocument, sourceDocumentId);

            CommercialDocument lastDoc = sourceDocument;

            foreach (Guid corrId in previousDocumentsId)
            {
                CommercialDocument correctiveDoc = (CommercialDocument)mapper.LoadBusinessObject(BusinessObjectType.CommercialDocument, corrId);

                CommercialCorrectiveDocumentFactory.RelateTwoCorrectiveDocuments(lastDoc, correctiveDoc, true);

                lastDoc = correctiveDoc;
            }

            CommercialCorrectiveDocumentFactory.CalculateDocumentsAfterCorrection(lastDoc);
            CommercialCorrectiveDocumentFactory.CreateNextCorrectiveDocument(lastDoc, destination);
            DuplicableAttributeFactory.DuplicateAttributes(lastDoc, destination);

            var salesOrderRelation = sourceDocument.Relations.Where(r => r.RelationType == DocumentRelationType.SalesOrderToInvoice).FirstOrDefault();

            if (salesOrderRelation != null)             //dokument jest do ZS wiec korekte tez tam podpinamy
            {
                var relation = destination.Relations.CreateNew();
                relation.RelationType    = DocumentRelationType.SalesOrderToCorrectiveCommercialDocument;
                relation.RelatedDocument = salesOrderRelation.RelatedDocument;
            }
        }
Exemplo n.º 4
0
        public static void CreateOutcomeShiftFromWarehouseDocument(XElement source, WarehouseDocument destination)
        {
            /*
             * <root>
             *   <warehouseDocumentId>GUID</warehouseDocumentId>
             * </root>
             */
            DocumentMapper    mapper         = DependencyContainerManager.Container.Get <DocumentMapper>();
            WarehouseDocument incomeDocument = (WarehouseDocument)mapper.LoadBusinessObject(BusinessObjectType.WarehouseDocument, new Guid(source.Element("warehouseDocumentId").Value));

            destination.WarehouseId = incomeDocument.WarehouseId;

            //create lines
            foreach (var incLine in incomeDocument.Lines)
            {
                WarehouseDocumentLine line = destination.Lines.CreateNew();

                line.ItemId     = incLine.ItemId;
                line.ItemName   = incLine.ItemName;
                line.Quantity   = incLine.Quantity;
                line.UnitId     = incLine.UnitId;
                line.ItemTypeId = incLine.ItemTypeId;
            }

            //Duplicate attributes
            DuplicableAttributeFactory.DuplicateAttributes(incomeDocument, destination);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Sprawdza czy dokument realizuje zamknięte ZSP oraz opcjonalnie czy na liniach realizujących ZSP niekoniecznie zamknięte doszło do zmiany ilości
 /// </summary>
 /// <param name="checkQuantityChange">czy sprawdzać zmianę ilości na pozycjach realizujących ZSP</param>
 internal void ValidateSalesOrderRealizedLines(bool checkQuantityChange)
 {
     if (!this.IsNew && !this.SkipRealizeClosedSalesOrderCheck)
     {
         CommercialDocument alternateDocument = this.AlternateVersion != null ?
                                                (CommercialDocument)this.AlternateVersion : null;
         DocumentMapper mapper =
             (DocumentMapper)DependencyContainerManager.Container.Get <DocumentMapper>();
         foreach (CommercialDocumentLine commLine in this.Lines)
         {
             Guid?relatedSalesOrderId = commLine.Attributes.
                                        GetGuidValueByFieldName(DocumentFieldName.LineAttribute_RealizedSalesOrderLineId);
             //test czy realizuje zamknięte ZSP
             if (relatedSalesOrderId.HasValue)
             {
                 //test czy pozmieniały się ilości
                 if (checkQuantityChange && alternateDocument != null)
                 {
                     CommercialDocumentLine altLine = alternateDocument.Lines.Where(line => line.Id == commLine.Id).FirstOrDefault();
                     if (altLine != null && commLine.Quantity != altLine.Quantity)
                     {
                         throw new ClientException(ClientExceptionId.LineQuantityEditForbiddenRelatedSalesOrder, null, "order:" + commLine.Order);
                     }
                 }
                 CommercialDocument relatedSalesOrder =
                     mapper.GetCommercialDocumentByLineId(relatedSalesOrderId.Value);
                 if (SalesOrderFactory.IsSalesOrderClosed(relatedSalesOrder))
                 {
                     throw new ClientException(ClientExceptionId.DocumentEditForbiddenRelatedSalesOrderClosed);
                 }
             }
         }
     }
 }
Exemplo n.º 6
0
        public static void GenerateSalesOrderFromBill(XElement source, CommercialDocument destination)
        {
            Guid               docId  = new Guid(source.Element("salesDocumentId").Value);
            DocumentMapper     mapper = DependencyContainerManager.Container.Get <DocumentMapper>();
            CommercialDocument doc    = (CommercialDocument)mapper.LoadBusinessObject(BusinessObjectType.CommercialDocument, docId);

            SalesOrderFactory.CopyLinesToSalesOrder(doc, destination);
        }
Exemplo n.º 7
0
 public DocumentController(
     IDocumentService documentService,
     DocumentMapper mapper,
     ILogger <DocumentController> logger)
 {
     this.documentService = documentService;
     this.mapper          = mapper;
     this.logger          = logger;
 }
Exemplo n.º 8
0
        public ActionResult AddDocument([FromBody] DocumentModel document)
        {
            _logger.LogInformation("Adding a new document");

            document.UploadedOn = DateTime.UtcNow;
            var documentData = DocumentMapper.SerializeDocument(document);
            var newDocument  = _documentService.CreateDocument(documentData);

            return(Ok(newDocument));
        }
Exemplo n.º 9
0
 public static void AssignNumber(SimpleDocument document, DocumentMapper mapper)
 {
     if (document.IsNew && !document.Number.SkipAutonumbering)
     {
         document.Number.ComputedSeriesValue = mapper.ComputeSeries(document);
         document.Number.FullNumber          = mapper.ComputeFullDocumentNumber(document, null);
     }
     if (String.IsNullOrEmpty(document.Number.FullNumber))
     {
         throw new ClientException(ClientExceptionId.EmptyDocumentNumberError);
     }
 }
Exemplo n.º 10
0
        public ActionResult UpdateDocument([FromBody] DocumentModel document)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var documentData = DocumentMapper.SerializeDocument(document);
            var newDocument  = _documentService.UpdateDocument(documentData);

            return(Ok(newDocument));
        }
Exemplo n.º 11
0
        public void Setup()
        {
            _tsks      = new List <TSK>();
            _dataPath  = Path.GetTempPath();
            _documents = new Documents();
            _dataModel = new ApplicationDataModel {
                Documents = _documents
            };

            _loggedDataMapperMock = new Mock <ILoggedDataMapper>();
            _workOrderMapperMock  = new Mock <IWorkOrderMapper>();

            _documentMapper = new DocumentMapper(_loggedDataMapperMock.Object, _workOrderMapperMock.Object);
            _linkedIds      = new Dictionary <string, List <UniqueId> >();
        }
Exemplo n.º 12
0
        public static void GeneratePurchaseInvoiceFromMultipleSalesOrders(XElement source, CommercialDocument destination)
        {
            /*
             *  robimy fakture zakupową na pozycje usługowe
             */

            DocumentMapper mapper = DependencyContainerManager.Container.Get <DocumentMapper>();

            List <CommercialDocument> soDocs = new List <CommercialDocument>();

            CalculationType?calcType = CalculationType.Net;

            destination.CalculationType = calcType.Value;

            foreach (XElement soId in source.Elements("salesOrderId"))
            {
                Guid docId = new Guid(soId.Value);

                var exists = soDocs.Where(d => d.Id.Value == docId).FirstOrDefault();

                if (exists != null)
                {
                    continue;
                }

                CommercialDocument doc = (CommercialDocument)mapper.LoadBusinessObject(BusinessObjectType.CommercialDocument, docId);
                soDocs.Add(doc);
            }


            //kopiujemy atrybuty jezeli sa jakies takie
            DuplicableAttributeFactory.DuplicateAttributes(soDocs, destination);

            XElement tagXml = new XElement("salesOrders");

            foreach (CommercialDocument salesOrder in soDocs)
            {
                //Dla dokumentu zakupowego nie ma ograniczenia
                //if (salesOrder.Relations.Where(rr => rr.RelationType == DocumentRelationType.SalesOrderToInvoice).FirstOrDefault() != null)
                //    throw new ClientException(ClientExceptionId.UnableToCreateInvoiceToSalesOrder, null, "orderNumber:" + salesOrder.Number.FullNumber);

                SalesOrderFactory.CopyLinesFromSalesOrder(salesOrder, destination, true, false, true, false);
                tagXml.Add(new XElement("salesOrder", new XAttribute("id", salesOrder.Id.ToUpperString()), new XAttribute("version", salesOrder.Version.ToUpperString())));
            }

            destination.Calculate();
            destination.Tag = tagXml.ToString(SaveOptions.DisableFormatting);
        }
        public static EmployeeId ProcessEmployeeIdDocument(NewRequest <SmartDoc> newReq)
        {
            EmployeeId result = DocumentMapper.MapDocument <EmployeeId>(newReq.RequestItem);

            //In order to process document as Employee Id, we need a successful OCR
            var ocrStep = newReq.RequestItem.CognitivePipelineActions.Where(s => s.StepName == InstructionFlag.AnalyzeText.ToString()).FirstOrDefault();

            if (ocrStep != null)
            {
                var ocrResult = JsonConvert.DeserializeObject <OCR>(ocrStep.Output);

                //Employee Ids in general have a fixed layout, so it practical to assume that location of text will be identical for every id
                //OCR will return an array of lines in the 1st region: 1st is Name, 2nd is Title, 3rd is Employee Id (the rest of read data is not relevant)

                if (ocrResult.Regions.Length == 0)
                {
                    result.DetectionNotes = "Invalid Employee Id";
                }
                else
                {
                    var region = ocrResult.Regions[0];

                    if (region.Lines.Length >= 3)
                    {
                        result.EmployeeName                    = GetOCRLine(region.Lines[0]);
                        result.EmployeeJobTitle                = GetOCRLine(region.Lines[1]);
                        result.EmployeeNum                     = GetOCRLine(region.Lines[2]);
                        result.PrimaryClassification           = "EmployeeIdAuthentication";
                        result.PrimaryClassificationConfidence = 1;
                        result.DetectionNotes                  = "Valid Employee Id";
                    }
                    else
                    {
                        result.DetectionNotes = "Invalid Employee Id*";
                    }
                }
            }

            if (string.IsNullOrEmpty(result.DetectionNotes))
            {
                result.DetectionNotes = "No OCR Found";
            }

            return(result);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncServerClient"/> class.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="convention">The convention.</param>
        /// <param name="credentials">The credentials.</param>
        public AsyncServerClient(string url, DocumentConvention convention, ICredentials credentials)
        {
            Guard.Assert(() => !string.IsNullOrEmpty(url));
            Guard.Assert(() => convention != null);

            WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);

            DatabaseAddress = new Uri(url);
            Convention = convention;
            Credentials = credentials;

            ContextStorage = new Dictionary<HttpJsonRequest, SynchronizationContext>();
            DocumentMapper = new DocumentMapper();
            IndexMapper = new IndexMapper(Convention);
            AttachmentMapper = new AttachmentMapper();
            StatisticsMapper = new StatisticsMapper();
            QueryResultMapper = new QueryResultMapper();
        }
        public static ShelfCompliance ProcessShelfCompliance(NewRequest <SmartDoc> newReq, double threshold)
        {
            ShelfCompliance result = DocumentMapper.MapDocument <ShelfCompliance>(newReq.RequestItem);

            result.DetectionNotes = "Invalid Classification";

            var shelfComplianceStep = newReq.RequestItem.CognitivePipelineActions.Where(s => s.StepName == InstructionFlag.ShelfCompliance.ToString()).FirstOrDefault();

            if (shelfComplianceStep != null)
            {
                var classificationResult = JsonConvert.DeserializeObject <CustomVisionClassification>(shelfComplianceStep.Output);

                //Get the top classification for compliant and non-compliant tags
                var topPrediction = classificationResult.Predictions.OrderByDescending(p => p.Probability).FirstOrDefault();
                if (topPrediction != null)
                {
                    if (topPrediction.TagName == "Compliant")
                    {
                        result.IsCompliant = true;
                    }

                    if (topPrediction.Probability >= threshold)
                    {
                        result.Confidence                      = topPrediction.Probability;
                        result.IsConfidenceAcceptable          = true;
                        result.PrimaryClassification           = InstructionFlag.ShelfCompliance.ToString();
                        result.PrimaryClassificationConfidence = topPrediction.Probability;
                        result.DetectionNotes                  = "Successful Classification";
                    }
                    else
                    {
                        //Unidentified or low quality picture
                        result.Confidence                      = -1;
                        result.IsConfidenceAcceptable          = false;
                        result.PrimaryClassification           = InstructionFlag.ShelfCompliance.ToString();
                        result.PrimaryClassificationConfidence = topPrediction.Probability;
                        result.DetectionNotes                  = $"Below ({threshold}) threshold Classification";
                    }
                }
            }

            return(result);
        }
Exemplo n.º 16
0
        public async Task <IActionResult> GetDocument(string dbname, string index, string id)
        {
            if (await UserService.CheckAuthorize(Request, false, dbname) is null)
            {
                return(Unauthorized(ErrorDto.GetAuthError()));
            }
            if (Guid.TryParse(id, out var guid))
            {
                var result = await DatabaseService.FindById(new IndexModel(dbname, index), guid);

                if (result is null)
                {
                    return(NoContent());
                }
                return(Ok(DocumentMapper.MapToDto(result)));
            }

            return(BadRequest(new ErrorDto(ErrorsType.SyntaxError, $"{id} is not GUID")));
        }
Exemplo n.º 17
0
 public DocumentController(IHostingEnvironment hostingEnvironment,
                           IDocumentService documentService,
                           IBookmarkService bookmarkService,
                           ITableUtil tableUtil,
                           ITextUtil textUtil,
                           DocumentMapper documentMapper,
                           BookmarkMapper bookmarkMapper,
                           IDocumentCore documentCore,
                           IWordBookmarkParser bookmarkParser)
 {
     _hostingEnvironment = hostingEnvironment;
     _documentService    = documentService;
     _bookmarkService    = bookmarkService;
     _tableUtil          = tableUtil;
     _textUtil           = textUtil;
     _documentMapper     = documentMapper;
     _bookmarkMapper     = bookmarkMapper;
     _documentCore       = documentCore;
     _bookmarkParser     = bookmarkParser;
 }
Exemplo n.º 18
0
        public static void CreateFinancialReportToFinancialRegister(XElement source, FinancialReport destination)
        {
            Guid registerId            = new Guid(source.Element("financialRegisterId").Value);
            FinancialRegister register = DictionaryMapper.Instance.GetFinancialRegister(registerId);

            destination.Number.NumberSettingId = register.FinancialReportNumberSettingId;
            destination.FinancialRegisterId    = registerId;

            DocumentMapper mapper = DependencyContainerManager.Container.Get <DocumentMapper>();
            bool           exists = mapper.CheckReportExistence(registerId);

            if (!exists)
            {
                destination.IsFirstReport  = true;
                destination.InitialBalance = 0;
            }
            else
            {
                destination.InitialBalance = mapper.CalculateReportInitialBalance(registerId);
            }
        }
Exemplo n.º 19
0
        internal void CheckDoesRealizeClosedSalesOrder(DocumentCoordinator coordinator)
        {
            //to ma działać tylko dla RW i tylko gdy jest on zapisywany bezpośrednio a nie jako powiązany dokument
            if (!this.IsNew &&
                this.WarehouseDirection == Enums.WarehouseDirection.Outcome &&
                !this.HasAnyCommercialCommercialWarehouseRelations)
            {
                DocumentMapper mapper =
                    (DocumentMapper)DependencyContainerManager.Container.Get <DocumentMapper>();

                IEnumerable <Document> relatedSalesOrders = this.Relations.GetRelatedDocuments(DocumentRelationType.SalesOrderToWarehouseDocument);

                foreach (Document relatedSalesOrder in relatedSalesOrders)
                {
                    CommercialDocument salesOrder = (CommercialDocument)mapper.LoadBusinessObject(BusinessObjectType.CommercialDocument, relatedSalesOrder.Id.Value);
                    if (relatedSalesOrder.Id.HasValue && SalesOrderFactory.IsSalesOrderClosed(salesOrder))
                    {
                        throw new ClientException(ClientExceptionId.DocumentEditForbiddenRelatedSalesOrderClosed);
                    }
                }
            }
        }
Exemplo n.º 20
0
        public void Execute(Document document)
        {
            if (document.IsBeforeSystemStart)
            {
                return;
            }

            if (document.Source != null &&
                (document.Source.Attribute("type").Value == "order" || document.CheckSourceType(SourceType.SalesOrderRealization)))
            {
                DocumentMapper     mapper = DependencyContainerManager.Container.Get <DocumentMapper>();
                CommercialDocument order  = (CommercialDocument)mapper.LoadBusinessObject(BusinessObjectType.CommercialDocument, new Guid(document.Source.Attribute("commercialDocumentId").Value));

                List <WarehouseDocument> warehouses = new List <WarehouseDocument>();
                warehouses.Add((WarehouseDocument)document);

                CommercialWarehouseDocumentFactory.RelateWarehousesLinesToOrderLines(warehouses, order, document.Source, true, false);

                /*if (SalesOrderFactory.TryCloseSalesOrder(order))
                 *  document.AddRelatedObject(order);*/
            }
            else if (document.Source != null && document.Source.Attribute("type").Value == "multipleReservations")
            {
                DocumentMapper            mapper       = DependencyContainerManager.Container.Get <DocumentMapper>();
                List <CommercialDocument> reservations = new List <CommercialDocument>();

                foreach (var orderXml in document.Source.Elements())
                {
                    CommercialDocument order = (CommercialDocument)mapper.LoadBusinessObject(BusinessObjectType.CommercialDocument, new Guid(orderXml.Value));
                    reservations.Add(order);
                }

                List <WarehouseDocument> warehouses = new List <WarehouseDocument>();
                warehouses.Add((WarehouseDocument)document);

                CommercialWarehouseDocumentFactory.RelateWarehousesLinesToMultipleOrdersLines(warehouses, reservations, true, false);
            }
        }
Exemplo n.º 21
0
        public static void CreateCorrectiveDocument(XElement source, WarehouseDocument destination)
        {
            Guid           sourceDocumentId = new Guid(source.Element("correctedDocumentId").Value);
            DocumentMapper mapper           = DependencyContainerManager.Container.Get <DocumentMapper>();

            WarehouseDocument  sourceDocument = (WarehouseDocument)mapper.LoadBusinessObject(BusinessObjectType.WarehouseDocument, sourceDocumentId);
            WarehouseDirection direction      = sourceDocument.WarehouseDirection;

            if (ConfigurationMapper.Instance.PreventDocumentCorrectionBeforeSystemStart &&
                sourceDocument.IsBeforeSystemStart)
            {
                throw new ClientException(ClientExceptionId.DocumentCorrectionBeforeSystemStartError);
            }

            destination.Contractor  = sourceDocument.Contractor;
            destination.WarehouseId = sourceDocument.WarehouseId;

            DuplicableAttributeFactory.DuplicateAttributes(sourceDocument, destination);

            foreach (WarehouseDocumentLine line in sourceDocument.Lines.Children)
            {
                WarehouseDocumentLine correctedLine = mapper.GetWarehouseDocumentLineAfterCorrection(line, direction);

                if (correctedLine != null)
                {
                    destination.Lines.AppendChild(correctedLine);
                }
            }

            if (destination.Lines.Children.Count == 0)
            {
                throw new ClientException(ClientExceptionId.FullyCorrectedCorrectionError);
            }

            destination.InitialCorrectedDocument = sourceDocument;
        }
Exemplo n.º 22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CommercialDocumentLogic"/> class.
 /// </summary>
 /// <param name="coordinator">The parent coordinator.</param>
 public ProductionLogic(DocumentCoordinator coordinator)
 {
     this.mapper      = (DocumentMapper)coordinator.Mapper;
     this.coordinator = coordinator;
 }
Exemplo n.º 23
0
        public static void GenerateInvoiceFromMultipleSalesOrders(XElement source, CommercialDocument destination)
        {
            /*
             *      <source type="multipleSalesOrders">
             *        <salesOrderId>{documentId}</salesOrderId>
             *        <salesOrderId>{documentId}</salesOrderId>
             *        <salesOrderId>{documentId}</salesOrderId>
             *        .........
             *      </source>
             */

            DocumentMapper mapper = DependencyContainerManager.Container.Get <DocumentMapper>();

            List <CommercialDocument> soDocs = new List <CommercialDocument>();

            CalculationType?calcType = null;

            foreach (XElement soId in source.Elements("salesOrderId"))
            {
                Guid docId = new Guid(soId.Value);

                var exists = soDocs.Where(d => d.Id.Value == docId).FirstOrDefault();

                if (exists != null)
                {
                    continue;
                }

                CommercialDocument doc = (CommercialDocument)mapper.LoadBusinessObject(BusinessObjectType.CommercialDocument, docId);
                soDocs.Add(doc);

                if (calcType == null)
                {
                    calcType = doc.CalculationType;
                }
                else if (calcType.Value != doc.CalculationType)
                {
                    throw new ClientException(ClientExceptionId.DifferentCalculationTypes);
                }
            }

            if (calcType.Value != destination.CalculationType && destination.DocumentType.CommercialDocumentOptions.AllowCalculationTypeChange)
            {
                destination.CalculationType = calcType.Value;
            }

            //sprawdzamy czy dok. zrodlowe maja wspolnego kontrahenta. jezeli tak to kopiujemy go na fakture
            bool copyContractor = true;

            //jezeli gdzies nie ma kontrahenta to nie kopiujemy
            var emptyContractor = soDocs.Where(w => w.Contractor == null).FirstOrDefault();

            if (emptyContractor != null)
            {
                copyContractor = false;
            }

            if (copyContractor)
            {
                var differentContractor = soDocs.Where(ww => ww.Contractor.Id.Value != soDocs[0].Contractor.Id.Value).FirstOrDefault();

                if (differentContractor != null)
                {
                    copyContractor = false;
                }
            }

            if (copyContractor)
            {
                destination.Contractor = soDocs[0].Contractor;

                if (destination.Contractor != null)
                {
                    var address = destination.Contractor.Addresses.GetBillingAddress();

                    if (address != null)
                    {
                        destination.ContractorAddressId = address.Id.Value;
                    }
                }
            }

            //kopiujemy atrybuty jezeli sa jakies takie
            DuplicableAttributeFactory.DuplicateAttributes(soDocs, destination);

            XElement tagXml = new XElement("salesOrders");

            foreach (CommercialDocument salesOrder in soDocs)
            {
                if (salesOrder.Relations.Where(rr => rr.RelationType == DocumentRelationType.SalesOrderToInvoice).FirstOrDefault() != null)
                {
                    throw new ClientException(ClientExceptionId.UnableToCreateInvoiceToSalesOrder, null, "orderNumber:" + salesOrder.Number.FullNumber);
                }

                SalesOrderFactory.CopyLinesFromSalesOrder(salesOrder, destination, true, false, true, true);
                tagXml.Add(new XElement("salesOrder", new XAttribute("id", salesOrder.Id.ToUpperString()), new XAttribute("version", salesOrder.Version.ToUpperString())));
            }

            destination.Calculate();
            destination.Tag = tagXml.ToString(SaveOptions.DisableFormatting);
        }
Exemplo n.º 24
0
        public static void GeneratePrepaymentDocument(XElement source, CommercialDocument destination)
        {
            /*
             *      <source type="salesOrder">
             *        <salesOrderId>{documentId}</salesOrderId>
             *        <processObject>prepaidInvoice</processObject>
             *        <closeOrder>false</closeOrder>
             *      </source>
             */
            DocumentMapper mapper = DependencyContainerManager.Container.Get <DocumentMapper>();

            bool closeOrder = false;

            if (source.Element("closeOrder") != null && source.Element("closeOrder").Value.ToUpperInvariant() == "TRUE")
            {
                closeOrder = true;
            }

            CommercialDocument salesOrder = (CommercialDocument)mapper.LoadBusinessObject(BusinessObjectType.CommercialDocument, new Guid(source.Element("salesOrderId").Value));


            SalesOrderFactory.CheckIfSalesOrderHasWarehouseDocumentsWithInvoices(salesOrder, closeOrder);

            SalesOrderSettlements salesOrderSettlements = new SalesOrderSettlements();

            salesOrderSettlements.LoadSalesOrder(salesOrder);
            XElement settledAmount = mapper.GetSalesOrderSettledAmount(salesOrder.Id.Value);

            salesOrderSettlements.LoadPrepaids(settledAmount);
            destination.SalesOrderSettlements = salesOrderSettlements;

            string processType   = salesOrder.Attributes[DocumentFieldName.Attribute_ProcessType].Value.Value;
            string processObject = source.Element("processObject").Value;
            bool   isSimulated   = processObject == "simulatedInvoice";
            bool   hasProtocole  = source.Element("protocole") != null && source.Element("protocole").Value == "true";

            ProcessManager.Instance.AppendProcessAttributes(destination, processType, processObject, null, null);
            DuplicableAttributeFactory.DuplicateAttributes(salesOrder, destination);

            if (isSimulated && hasProtocole)
            {
                destination.Attributes.GetOrCreateNew(DocumentFieldName.Attribute_IsSimulateSettlementInvoiceWithProtocole).Value.Value = "1";
            }

            //sprawdzamy czy dokumenty zrodlowe maja zgodne sposoby liczenia

            if (salesOrder.CalculationType != destination.CalculationType && destination.DocumentType.CommercialDocumentOptions.AllowCalculationTypeChange)
            {
                destination.CalculationType = salesOrder.CalculationType;
            }

            if (salesOrder.Contractor != null)
            {
                destination.Contractor = (Contractor)salesOrder.Contractor;
            }

            if (salesOrder.ContractorAddressId != null)
            {
                destination.ContractorAddressId = salesOrder.ContractorAddressId;
            }

            int prepaidDocuments = 0;

            prepaidDocuments = salesOrder.Relations.Where(r => r.RelationType == DocumentRelationType.SalesOrderToInvoice).Count();

            destination.Tag = prepaidDocuments.ToString(CultureInfo.InvariantCulture);

            /* teraz wybieramy odpowiednia sciezke algorytmu. mamy takie mozliwosc:
             * 1) wystawiamy zaliczke
             *    - w takiej sytuacji wybieramy id towaru zaliczkowego dla kazdej ze stawek vat i wpisujemy tam wartosci nierozliczone
             * 2) wystawiamy fakture rozliczajaca (closeOrder == true) podczas gdy mamy zaliczki (prepaidDocuments > 0)
             *    - kopiujemy wszystkie pozycje z ZS 1:1, a tabele vat pomniejszamy o sume zaliczek
             * 3) wystawiamy fakture rozliczajaca (closeOrder == true) i nie mamy dokumentow zaliczkowych (prepaidDocuments == 0)
             *    - w takim przypadku zamowienie sprzedazowe traktujemy jako proforme, kopiujemy wszystkie pozycje i tabele vat bez zmian i tyle
             */


            //wstawiamy odpowiedni towar na zaliczke + ustawiamy odpowiednai wartosc
            int stage = 0;

            if (closeOrder)
            {
                stage = 0;
            }
            else if (prepaidDocuments == 0)
            {
                stage = 1;
            }
            else if (prepaidDocuments == 1)
            {
                stage = 2;
            }
            else if (prepaidDocuments == 2)
            {
                stage = 3;
            }
            else if (prepaidDocuments >= 3)
            {
                stage = 4;
            }

            List <Guid> items = new List <Guid>(2);

            ICollection <SalesOrderSettlement> unsettledValues = salesOrderSettlements.GetUnsettledValues();

            foreach (var v in salesOrder.VatTableEntries.GetVatRates())
            {
                items.Add(ProcessManager.Instance.GetPrepaidItemId(salesOrder, stage, v));
            }

            XDocument xml = DependencyContainerManager.Container.Get <ItemMapper>().GetItemsDetailsForDocument(false, null, null, items);

            if (closeOrder)
            {
                SalesOrderFactory.CopyLinesFromSalesOrder(salesOrder, destination, false, true, false, true);
                destination.Calculate();

                //Ostatnia rata pchamy do atrybutu zeby wydruk fiskalny wiedzial co ma wydrukowac
                if (destination.CalculationType == CalculationType.Gross && !isSimulated)
                {
                    XElement fiscalLines = new XElement("fiscalLines");

                    foreach (var v in unsettledValues)
                    {
                        XElement itemXml    = xml.Root.Elements().Where(i => i.Attribute("id").Value == ProcessManager.Instance.GetPrepaidItemId(salesOrder, stage, v.VatRateId).ToUpperString()).First();
                        XElement fiscalLine = new XElement("fiscalLine");
                        fiscalLine.Add(new XElement("itemName", itemXml.Attribute("name").Value));
                        fiscalLine.Add(new XElement("quantity", "1"));
                        fiscalLine.Add(new XElement("vatRateId", itemXml.Attribute("vatRateId").Value));
                        fiscalLine.Add(new XElement("grossPrice", v.GrossValue.ToString(CultureInfo.InvariantCulture)));
                        fiscalLine.Add(new XElement("grossValue", v.GrossValue.ToString(CultureInfo.InvariantCulture)));
                        fiscalLine.Add(new XElement("unitId", itemXml.Attribute("unitId").Value));
                        fiscalLines.Add(fiscalLine);
                    }

                    var attribute = destination.Attributes.CreateNew(DocumentFieldName.Attribute_FiscalPrepayment);
                    attribute.Value = fiscalLines;
                }

                if (prepaidDocuments > 0)                 // *2)
                {
                    decimal maxDifference = ProcessManager.Instance.GetMaxSettlementDifference(salesOrder);

                    foreach (var v in salesOrderSettlements.Prepaids)
                    {
                        if (v.NetValue > 0 || v.GrossValue > 0 || v.VatValue > 0)
                        {
                            var vt        = destination.VatTableEntries.Where(t => t.VatRateId == v.VatRateId).FirstOrDefault();
                            var prepaidVt = destination.VatTableEntries.CreateNewAfter(vt, v.VatRateId);
                            prepaidVt.VatRateId  = v.VatRateId;
                            prepaidVt.NetValue   = -v.NetValue;
                            prepaidVt.GrossValue = -v.GrossValue;
                            prepaidVt.VatValue   = -v.VatValue;

                            decimal vtNetValue   = 0;
                            decimal vtGrossValue = 0;
                            decimal vtVatValue   = 0;
                            if (vt != null)
                            {
                                vtNetValue   = vt.NetValue;
                                vtGrossValue = vt.GrossValue;
                                vtVatValue   = vt.VatValue;
                            }

                            decimal grossBalance = vtGrossValue + prepaidVt.GrossValue;
                            decimal netBalance   = vtNetValue + prepaidVt.NetValue;
                            decimal vatBalance   = vtVatValue + prepaidVt.VatValue;

                            SalesOrderBalanceValidator validator =
                                new SalesOrderBalanceValidator(maxDifference, grossBalance, netBalance, vatBalance);

                            if (validator.IsIllegalOverPayment)
                            {
                                throw new ClientException(ClientExceptionId.SalesOrderSettlementOverpaidError, null, "value:" + (-grossBalance).ToString(CultureInfo.InvariantCulture).Replace('.', ',')); //nadpłata powyżej granicy błędu
                            }
                            else if (validator.IsAcceptableOverPayment)                                                                                                                                    //czyli mamy nadplate w granicy bledu
                            {
                                prepaidVt.NetValue   = -vtNetValue;
                                prepaidVt.GrossValue = -vtGrossValue;
                                prepaidVt.VatValue   = -vtVatValue;
                            }
                        }
                    }
                }
                else
                {
                    throw new ClientException(ClientExceptionId.UnableToCreateSettlementDocument3);
                }

                decimal netValue   = 0;
                decimal grossValue = 0;
                decimal vatValue   = 0;

                foreach (var vt in destination.VatTableEntries)
                {
                    netValue   += vt.NetValue;
                    grossValue += vt.GrossValue;
                    vatValue   += vt.VatValue;
                }

                destination.NetValue   = netValue;
                destination.GrossValue = grossValue;
                destination.VatValue   = vatValue;

                destination.DisableLinesChange = DisableDocumentChangeReason.LINES_SETTLEMENT_INVOICE;

                if (!isSimulated)
                {
                    var attr = destination.Attributes.CreateNew(DocumentFieldName.Attribute_IsSettlementDocument);
                    attr.Value.Value = "1";
                }
            }
            else             //1) wystawiamy zaliczke
            {
                foreach (XElement itemXml in xml.Root.Elements("item"))
                {
                    CommercialDocumentLine line = destination.Lines.CreateNew();
                    line.ItemId = new Guid(itemXml.Attribute("id").Value);
                    Guid vatRateId = new Guid(itemXml.Attribute("vatRateId").Value);

                    if (itemXml.Attribute("code") != null)
                    {
                        line.ItemCode = itemXml.Attribute("code").Value;
                    }

                    line.UnitId      = new Guid(itemXml.Attribute("unitId").Value);
                    line.VatRateId   = vatRateId;
                    line.ItemVersion = new Guid(itemXml.Attribute("version").Value);
                    line.Quantity    = 1;
                    line.ItemName    = itemXml.Attribute("name").Value;
                }

                destination.Calculate();
            }
        }
Exemplo n.º 25
0
        private static void GenerateFinancialDocumentToPayment(Payment payment, CommercialDocument document)
        {
            DocumentMapper mapper = DependencyContainerManager.Container.Get <DocumentMapper>();

            using (DocumentCoordinator coordinator = new DocumentCoordinator(false, false))
            {
                PaymentMethod paymentMethod = DictionaryMapper.Instance.GetPaymentMethod(payment.PaymentMethodId.Value);

                Guid branchId = SessionManager.User.BranchId;

                if (DictionaryMapper.Instance.IsPaymentMethodSupportedByRegister(paymentMethod.Id.Value, branchId))
                {
                    FinancialRegister register = DictionaryMapper.Instance.GetFinancialRegisterForSpecifiedPaymentMethod(paymentMethod.Id.Value, branchId, payment.PaymentCurrencyId);

                    if (register == null)
                    {
                        throw new ClientException(ClientExceptionId.UnableToIssueFinancialDocument3);
                    }

                    FinancialDirection direction = FinancialDocumentFactory.GetFinancialDirectionForPayment(document, payment);

                    Guid?reportId = mapper.GetOpenedFinancialReportId(register.Id.Value);

                    if (reportId == null)
                    {
                        throw new ClientException(ClientExceptionId.UnableToIssueDocumentToClosedFinancialReport);
                    }

                    FinancialDocument financialDoc = new FinancialDocument();
                    financialDoc.RelatedCommercialDocument = document;
                    coordinator.TrySaveProfileIdAttribute(financialDoc);

                    if (direction == FinancialDirection.Income)
                    {
                        financialDoc.DocumentTypeId         = register.IncomeDocumentTypeId;
                        financialDoc.Number.NumberSettingId = register.IncomeNumberSettingId;
                    }
                    else
                    {
                        financialDoc.DocumentTypeId         = register.OutcomeDocumentTypeId;
                        financialDoc.Number.NumberSettingId = register.OutcomeNumberSettingId;
                    }

                    financialDoc.Contractor          = payment.Contractor;
                    financialDoc.ContractorAddressId = payment.ContractorAddressId;
                    FinancialReport report = new FinancialReport();
                    report.Id = reportId;
                    report.FinancialRegisterId   = register.Id.Value;
                    financialDoc.FinancialReport = report;
                    financialDoc.DocumentStatus  = DocumentStatus.Committed;
                    DuplicableAttributeFactory.DuplicateAttributes(document, financialDoc);

                    Payment pt = financialDoc.Payments.CreateNew();
                    pt.Amount                       = Math.Abs(payment.Amount);
                    pt.ExchangeRate                 = financialDoc.ExchangeRate = document.ExchangeRate;
                    pt.ExchangeScale                = financialDoc.ExchangeScale = document.ExchangeScale;
                    pt.ExchangeDate                 = financialDoc.ExchangeDate = document.ExchangeDate;
                    financialDoc.Amount             = pt.Amount;
                    financialDoc.DocumentCurrencyId = payment.PaymentCurrencyId;
                    PaymentSettlement settlement = pt.Settlements.CreateNew();
                    settlement.IsAutoGenerated = true;
                    settlement.RelatedPayment  = payment;
                    settlement.Amount          = pt.Amount;

                    document.AddRelatedObject(financialDoc);
                }
            }
        }
Exemplo n.º 26
0
 public ComplaintDocumentLogic(DocumentCoordinator coordinator)
 {
     this.mapper      = (DocumentMapper)coordinator.Mapper;
     this.coordinator = coordinator;
 }
Exemplo n.º 27
0
        public static void UpdateFinancialDocumentsInCommercialDocument(CommercialDocument document)
        {
            if (document == null)
            {
                return;
            }

            DocumentMapper mapper = DependencyContainerManager.Container.Get <DocumentMapper>();

            ICollection <Guid> financialIdCol = mapper.GetRelatedFinancialDocumentsId(document.Id.Value);

            //wczytujemy i laczymy dokumenty po paymentach
            foreach (Guid id in financialIdCol)
            {
                FinancialDocument fDoc = null;

                try
                {
                    fDoc = (FinancialDocument)mapper.LoadBusinessObject(BusinessObjectType.FinancialDocument, id);
                }
                catch (ClientException ex)
                {
                    RoboFramework.Tools.RandomLogHelper.GetLog().Debug("FractusRefactorTraceCatch:126");
                    if (ex.Id == ClientExceptionId.ObjectNotFound)
                    {
                        continue;
                    }
                }

                document.AddRelatedObject(fDoc);

                //aktualizujemy dane kursu na dokumencie finansowym i na jego platnosciach
                fDoc.ExchangeDate  = document.ExchangeDate;
                fDoc.ExchangeRate  = document.ExchangeRate;
                fDoc.ExchangeScale = document.ExchangeScale;

                foreach (Payment payment in fDoc.Payments)
                {
                    payment.ExchangeDate  = document.ExchangeDate;
                    payment.ExchangeRate  = document.ExchangeRate;
                    payment.ExchangeScale = document.ExchangeScale;
                }

                var settlements = from p in document.Payments.Children
                                  from s in p.Settlements.Children
                                  select s;

                foreach (PaymentSettlement settlement in settlements)
                {
                    Payment pt = fDoc.Payments.Children.Where(x => x.Id.Value == settlement.RelatedPayment.Id.Value).FirstOrDefault();

                    if (pt != null)
                    {
                        settlement.RelatedPayment = pt;

                        if (settlement.AlternateVersion != null)
                        {
                            ((PaymentSettlement)settlement.AlternateVersion).RelatedPayment = pt;
                        }
                    }
                }

                //replace deleted payments/settlements
                if (document.AlternateVersion != null)
                {
                    CommercialDocument alternateDocument = (CommercialDocument)document.AlternateVersion;
                    var deletedSettlements = from p in alternateDocument.Payments.Children
                                             from s in p.Settlements.Children
                                             where p.AlternateVersion == null
                                             select s;

                    foreach (PaymentSettlement settlement in deletedSettlements)
                    {
                        Payment pt = fDoc.Payments.Children.Where(x => x.Id.Value == settlement.RelatedPayment.Id.Value).FirstOrDefault();

                        if (pt != null)
                        {
                            settlement.RelatedPayment = pt;
                        }
                    }
                }
            }

            if (!FinancialDocumentFactory.IsFinancialToCommercialRelationOneToOne(document))
            {
                throw new ClientException(ClientExceptionId.AutomaticFinancialDocumentUpdateException);
            }

            //aktualizujemy
            foreach (Payment payment in document.Payments.Children.Where(p => p.Status == BusinessObjectStatus.Modified))
            {
                Payment alternatePayment = (Payment)payment.AlternateVersion;
                string  cntId, altercntId;
                cntId = payment.Contractor != null?payment.Contractor.Id.ToString() : "brak";

                altercntId = alternatePayment.Contractor != null?alternatePayment.Contractor.Id.ToString() : "brak";

                //Jeśli zmienia się kontrhent to należy zmienić dowiązany dokument handlowy
                if (payment.PaymentMethodId.Value == alternatePayment.PaymentMethodId.Value &&
                    !(cntId != altercntId))        //zmienila sie wartosc
                {
                    PaymentSettlement settlement = payment.Settlements.Children.FirstOrDefault();

                    if (settlement != null)
                    {
                        settlement.Amount = Math.Abs(payment.Amount);

                        decimal difference = Math.Abs(Math.Abs(payment.Amount) - Math.Abs(settlement.RelatedPayment.Amount));

                        if ((settlement.RelatedPayment.Amount + difference) * settlement.RelatedPayment.Direction == -payment.Amount * payment.Direction)
                        {
                            settlement.RelatedPayment.Amount += difference;
                        }
                        else
                        {
                            settlement.RelatedPayment.Amount -= difference;
                        }

                        ((FinancialDocument)settlement.RelatedPayment.Parent).Amount = settlement.RelatedPayment.Amount;
                        settlement.RelatedPayment.Amount = settlement.RelatedPayment.Amount;
                        settlement.RelatedPayment.Settlements.Where(s => s.Id.Value == settlement.Id.Value).First().Amount = settlement.RelatedPayment.Amount;
                    }
                }
                else //zmienila sie forma platnosci
                {
                    //anulujemy powiazany dokument finansowy jezeli:
                    //1) powiazanie jest na pelna sume
                    //2) dokument istnieje (nie rozliczamy nic z innego oddzialu
                    //3) powiazany dokument ma taki sam typ jaki jaki generowala stara forma platnosci
                    if (payment.Settlements.Children.Count > 0)
                    {
                        //1
                        if (payment.Settlements.Children.Count != 1)
                        {
                            throw new ClientException(ClientExceptionId.AutomaticFinancialDocumentUpdateException);
                        }

                        if (alternatePayment.Amount != payment.Settlements.Children.First().Amount)
                        {
                            throw new ClientException(ClientExceptionId.AutomaticFinancialDocumentUpdateException);
                        }

                        //2
                        FinancialDocument fDoc = (FinancialDocument)payment.Settlements.Children.First().RelatedPayment.Parent;

                        if (fDoc == null)
                        {
                            throw new ClientException(ClientExceptionId.AutomaticFinancialDocumentUpdateException);
                        }

                        //3
                        FinancialRegister reg = DictionaryMapper.Instance.GetFinancialRegisterForSpecifiedPaymentMethod(alternatePayment.PaymentMethodId.Value, SessionManager.User.BranchId, alternatePayment.PaymentCurrencyId);

                        if (reg == null || (reg.IncomeDocumentTypeId != fDoc.DocumentTypeId && reg.OutcomeDocumentTypeId != fDoc.DocumentTypeId))
                        {
                            throw new ClientException(ClientExceptionId.AutomaticFinancialDocumentUpdateException);
                        }

                        //warunki spelnione, mozna anulowac
                        DocumentStatusChangeLogic.CancelFinancialDocument(fDoc);
                        payment.Settlements.RemoveAll();
                    }

                    FinancialDocumentFactory.GenerateFinancialDocumentToPayment(payment, document);
                }
            }
        }
Exemplo n.º 28
0
 public InventorySheetLogic(DocumentCoordinator coordinator)
 {
     this.mapper      = (DocumentMapper)coordinator.Mapper;
     this.coordinator = coordinator;
 }
Exemplo n.º 29
0
 public SalesOrderLogic(DocumentCoordinator coordinator)
 {
     this.mapper      = (DocumentMapper)coordinator.Mapper;
     this.coordinator = coordinator;
 }
Exemplo n.º 30
0
 public async Task <IActionResult> GetDocuments(string dbname, string index)
 {
     return(Ok(DocumentMapper.MapToDtos(await DatabaseService.GetAll(new IndexModel(dbname, index)))));
 }
Exemplo n.º 31
0
 public FinancialDocumentLogic(DocumentCoordinator coordinator)
 {
     this.mapper      = (DocumentMapper)coordinator.Mapper;
     this.coordinator = coordinator;
 }