private void LogCustomer(CustomerDocument customerDocument)
        {
            var url      = $"{Properties.Settings.Default.ServerAddress}/api/resource/Sage 50 Export Log";
            var resource = new Resource(url);

            resource.LogCustomer(customerDocument);
        }
Esempio n. 2
0
        public void AddCustomerDocument(CustomerDocument cd)
        {
            var cus = _customerRepository.GetById(cd.CustomerId);

            cus.Documents.Add(cd);
            _customerRepository.Update(cus);
        }
Esempio n. 3
0
 public void Update(CustomerDocument model)
 {
     _context.Entry(model).State = System.Data.Entity.EntityState.Modified;
     _context.SaveChanges();
     //_context.CustomerDocuments.Attach(model);
     //_context.SaveChanges();
 }
 private void AddContacts(Customer customer, CustomerDocument customerDocument)
 {
     foreach (var c in customerDocument.Contacts)
     {
         if (!string.IsNullOrEmpty(customer.BillToContact.CompanyName) && !string.IsNullOrEmpty(customer.ShipToContact.CompanyName))
         {
             break;
         }
         else if (customer.BillToContact.Address.Address1 != null && (string.IsNullOrEmpty(customer.BillToContact.CompanyName) &&
                                                                      (customer.BillToContact.Address.Address1 != null || customer.BillToContact.Address.Address1.Length != 0)))
         {
             customer.BillToContact.CompanyName = customerDocument.CustomerName;
             customer.BillToContact.Email       = c.EmailId;
             customer.BillToContact.FirstName   = c.FirstName;
             customer.BillToContact.Gender      = c.Gender == "Male" ? Gender.Male : c.Gender == "Female" ? Gender.Female : Gender.NotSpecified;
             customer.BillToContact.LastName    = c.LastName;
             customer.BillToContact.Title       = c.Salutation;
         }
         else if (customer.ShipToContact.Address.Address1 != null && (string.IsNullOrEmpty(customer.ShipToContact.CompanyName) &&
                                                                      (customer.ShipToContact.Address.Address1 != null || customer.ShipToContact.Address.Address1.Length != 0)))
         {
             customer.ShipToContact.CompanyName = customerDocument.CustomerName;
             customer.ShipToContact.Email       = c.EmailId;
             customer.ShipToContact.FirstName   = c.FirstName;
             customer.ShipToContact.Gender      = c.Gender == "Male" ? Gender.Male : c.Gender == "Female" ? Gender.Female : Gender.NotSpecified;
             customer.ShipToContact.LastName    = c.LastName;
             customer.ShipToContact.Title       = c.Salutation;
         }
     }
 }
        private static void AddAddresses(Customer customer, CustomerDocument customerDocument)
        {
            var billingAddress  = customerDocument.Addresses.Find(x => x.AddressType == "Billing");
            var shippingAddress = customerDocument.Addresses.Find(x => x.AddressType == "Shipping");

            if (billingAddress != null)
            {
                var state = TransformState(billingAddress.State);
                customer.BillToContact.Address.Address1 = billingAddress.AddressLine1;
                customer.BillToContact.Address.Address2 = billingAddress.AddressLine2;
                customer.BillToContact.Address.City     = billingAddress.City;
                customer.BillToContact.Address.State    = GetStateFromPredefinedStates(state);
                customer.BillToContact.Address.Zip      = billingAddress.Pincode;
                customer.BillToContact.Address.Country  = billingAddress.Country;
            }
            if (shippingAddress != null)
            {
                var state = TransformState(shippingAddress.State);
                customer.ShipToContact.Address.Address1 = shippingAddress.AddressLine1;
                customer.BillToContact.Address.Address2 = shippingAddress.AddressLine2;
                customer.BillToContact.Address.City     = shippingAddress.City;
                customer.BillToContact.Address.State    = GetStateFromPredefinedStates(state);
                customer.BillToContact.Address.Zip      = shippingAddress.Pincode;
                customer.BillToContact.Address.Country  = shippingAddress.Country;
            }
        }
Esempio n. 6
0
        public void ShouldSetBestNewAge()
        {
            var service     = new MergeService(_dataAccess.Object, _repository.Object);
            var newCustomer = new MappedCustomerMessage
            {
                CustomerId = 1,
                SourceId   = 2,
                Data       = new Dictionary <string, Dictionary <string, object> > {
                    { "edad", new Dictionary <string, object> {
                          { "2", 36 }
                      } }
                }
            };
            var customerDocument = new CustomerDocument("1")
            {
                Data = new Dictionary <string, object> {
                    { "nombre", "cliente prueba" },
                    { "edad", 35 }
                },
                Full = JObject.Parse(elasticCustomer)
            };

            _dataAccess.Setup(x => x.Get <CustomerDocument>(It.IsAny <string>())).Returns(customerDocument);
            _dataAccess.Setup(x => x.Put(It.IsAny <CustomerDocument>()));
            service.Save("1", newCustomer);
            _dataAccess.Verify(x => x.Put(It.Is <CustomerDocument>(y => y.Data.Any(z => z.Key == "edad" && ((int)z.Value) == 36))));
        }
        public ActionResult _AddDocument(int id)
        {
            var cd = new CustomerDocument {
                CustomerId = id
            };

            return(PartialView("_EditCustomerDocument", Mapper.Map <CustomerDocument, CustomerDocumentVM>(cd)));
        }
Esempio n. 8
0
        public void AddsDocument()
        {
            var newCustomer = new CustomerDocument {
                Email = "*****@*****.**", First = "Rob", Last = "Conery"
            };

            docs.Add(newCustomer);
            Assert.Equal(1, docs.Count);
        }
Esempio n. 9
0
 public int Insert(CustomerDocument obj)
 {
     return(QueryExecutor.Execute(StoreProcedures.sp_CustomerDocument_Insert.ToString(), new {
         obj.DocumentTypeId,
         obj.CustomerId,
         obj.DocumentNumber,
         obj.DocumentIssueBy,
         obj.DocumentIssueDate,
         obj.DocumentExpiryDate,
     }));
 }
Esempio n. 10
0
        public void DeletesDocument()
        {
            var newCustomer = new CustomerDocument {
                Email = "*****@*****.**", First = "Rob", Last = "Conery"
            };

            docs.Add(newCustomer);
            var removed = docs.Remove(newCustomer);

            Assert.True(removed);
        }
Esempio n. 11
0
        public void UpdatesDocument()
        {
            var newCustomer = new CustomerDocument {
                Email = "*****@*****.**", First = "Rob", Last = "Conery"
            };

            docs.Add(newCustomer);
            newCustomer.First = "Bill";
            var updated = docs.Update(newCustomer);

            Assert.Equal(1, updated);
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            try
            {
                PmsEteckContext db = new PmsEteckContext();
                Console.WriteLine("We starten nu met het downloaden van de documenten per entiteit");

                CustomerDocument        _customerDocument    = new CustomerDocument();
                List <CustomerDocument> documentsForDownload = db.CustomerDocuments.Where(w => !w.bDownloaded && w.sUrl.StartsWith("http://dms.eteck.nl/ufc")).ToList();
                Console.WriteLine(string.Format("De lijst met documenten is opgehaald en bevat {0} items", documentsForDownload.Count));

                foreach (var item in documentsForDownload)
                {
                    Console.WriteLine(string.Format("Gestart met het downloaden van document:  {0}", item.sDocumentName));
                    bool result = _customerDocument.SaveFile(item.iCustomerDocumentKey);
                    if (!result)
                    {
                        Console.WriteLine(string.Format("Er heeft zich een fout voorgedaan bij het downloaden van document {0}", item.sDocumentName));
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Het downloaden van het bestand is voltooid: {0}", item.sDocumentName));
                    }
                }

                Console.WriteLine("We starten met het downloaden van alle documenten.");

                Hyperlink        _hyperlink            = new Hyperlink();
                List <Hyperlink> hyperlinksForDownload = db.Hyperlinks.Where(w => !w.bDownloaded && w.sUrl.StartsWith("http://dms.eteck.nl/ufc")).ToList();
                Console.WriteLine(string.Format("De lijst met hyperlinks is opgehaald. Dit zijn er {0}", hyperlinksForDownload.Count));

                foreach (Hyperlink hyperlink in hyperlinksForDownload)
                {
                    Console.WriteLine(string.Format("Gestart met het downloaden van document:  {0}", hyperlink.sLinkName));
                    bool result = _hyperlink.SaveFile(hyperlink.iHyperlinkKey);
                    if (!result)
                    {
                        Console.WriteLine(string.Format("Er heeft zich een fout voorgedaan bij het downloaden van document {0}", hyperlink.sLinkName));
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Het downloaden van het bestand is voltooid: {0}", hyperlink.sLinkName));
                    }
                }
                Console.WriteLine("Alle bestanden zijn gedownload.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }
        private void AddSalesRep(Customer customer, CustomerDocument customerDocument)
        {
            EmployeeList employees = Company.Factories.EmployeeFactory.List();

            employees.Load();
            foreach (var item in employees)
            {
                if (item.Name != customerDocument.SalesRep)
                {
                    continue;
                }
                customer.SalesRepresentativeReference = item.Key;
                break;
            }
        }
Esempio n. 14
0
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            string Editor_contentHeader      = HeaderEditor.Content;
            string Editor_contentFooter      = FooterEditor.Content;
            string Editor_contentBody        = BodyEditor.Content;
            List <CustomerDocument> custDocs = new List <CustomerDocument>();
            int intFileSize = flVendCat.PostedFile.ContentLength;

            if (flVendCat.HasFile)
            {
                if (flVendCat.PostedFile.FileName != "")
                {
                    if (Request.Files.Count > 0)
                    {
                        HttpFileCollection attachments = Request.Files;
                        for (int i = 0; i < attachments.Count; i++)
                        {
                            HttpPostedFile attachment = attachments[i];
                            if (attachment.ContentLength > 0 && !String.IsNullOrEmpty(attachment.FileName))
                            {
                                CustomerDocument cbc = new CustomerDocument();
                                if (File.Exists(Server.MapPath("../CustomerDocs/VendorEmailDocument/") + attachment.FileName) == true)
                                {
                                    File.Delete(Server.MapPath("../CustomerDocs/VendorEmailDocument/") + attachment.FileName);
                                    flVendCat.PostedFile.SaveAs(Server.MapPath("../CustomerDocs/VendorEmailDocument/") + attachment.FileName);
                                }
                                else
                                {
                                    flVendCat.PostedFile.SaveAs(Server.MapPath("../CustomerDocs/VendorEmailDocument/") + attachment.FileName);
                                }
                                string fPath;
                                fPath            = ("../CustomerDocs/VendorEmailDocument/") + attachment.FileName;
                                cbc.DocumentName = attachment.FileName;
                                cbc.DocumentPath = fPath;
                                custDocs.Add(cbc);
                            }
                        }
                    }
                }
            }
            bool result = AdminBLL.Instance.UpdateHTMLTemplate(Editor_contentHeader, Editor_contentBody, Editor_contentFooter, txtSubject.Text, SubHTMLTemplateID, custDocs);

            if (result)
            {
                InitialDataBind(SubHTMLTemplateID);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "AlertBox", "alert('Auto Email Template Updated Successfully');", true);
            }
        }
Esempio n. 15
0
        public IRestResponse LogCustomer(CustomerDocument document)
        {
            var log = new Log
            {
                document_name = document.Name,
                export_date   = DateTime.Now.ToString("yyyy-MM-dd"),
                document_date = DateTime.Now.ToString("yyyy-MM-dd"),
                document_type = "Customer"
            };
            var request = new RestRequest(Method.POST);

            request.AddJsonBody(log);
            var response = _restClient.Execute(request);

            return(response);
        }
Esempio n. 16
0
        public ValidationMessage Insert(CustomerDocument obj)
        {
            var URL     = string.Format(AppSettings.BaseApiUrl + ApiUrls.CustomerDocument.Insert);
            var Content = Post <string>(URL, obj);

            if (Content.IsSuccessful)
            {
                return(new ValidationMessage());
            }
            else
            {
                return(new ValidationMessage()
                {
                    Message = Content.Message
                });
            }
        }
Esempio n. 17
0
        public void RecordsPopulated()
        {
            docs.Clear();
            var newCustomer = new CustomerDocument {
                Email = "*****@*****.**", First = "Buddy", Last = "Conery"
            };

            docs.Add(newCustomer);

            //load a new, separate list
            var customers = new PGDocumentList <CustomerDocument>("dvds");

            //there should be some records here based on the above
            Assert.Equal("*****@*****.**", customers.First().Email);
            Assert.Equal("Buddy", customers.First().First);
            Assert.Equal("Conery", customers.First().Last);
        }
Esempio n. 18
0
        public async Task <IActionResult> GetCustomerDocumentById(Int64 CustomerDocumentId)
        {
            CustomerDocument Items = new CustomerDocument();

            try
            {
                Items = await _context.CustomerDocument.Where(q => q.CustomerDocumentId == CustomerDocumentId).FirstOrDefaultAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(BadRequest($"Ocurrio un error:{ex.Message}"));
            }


            return(await Task.Run(() => Ok(Items)));
        }
        private Customer CreateNewCustomer(CustomerDocument customerDocument)
        {
            var customer = Company.Factories.CustomerFactory.Create();

            if (customer == null)
            {
                Logger.Information("Customer data was null when trying to create Sage customer");
                return(null);
            }

            if (customerDocument == null || customerDocument.Addresses.Count == 0)
            {
                Logger.Information("Customer has no address so the customer cannot be created");
                return(customer);
            }
            try
            {
                customer.ID   = customerDocument.OldCustomerId;  // add a field - ID to Customer doctype
                customer.Name = customerDocument.CustomerName;
                AddContact(customer, customerDocument);
                AddSalesRep(customer, customerDocument);

                customer.Save();
                Logger.Information("Customer - {Customer} saved successfully", customerDocument.CustomerName);
            }
            catch (ValidationException e)
            {
                Logger.Debug("Validation failed.");
                Logger.Debug(e.Message);
                Logger.Debug("{@Name} will be sent back to the queue", customerDocument.Name);
                customer = null;
            }
            catch (RecordInUseException)
            {
                customer = null;
                Logger.Debug("Record is in use. {@Name} will be sent back to the queue", customerDocument.Name);
            }
            catch (Exception e)
            {
                customer = null;
                Logger.Debug(e, e.Message);
                Logger.Debug("{@E}", e);
            }

            return(customer);
        }
Esempio n. 20
0
        public async Task <ActionResult <CustomerDocument> > Insert([FromBody] CustomerDocument _CustomerDocument)
        {
            CustomerDocument _CustomerDocumentq = new CustomerDocument();

            try
            {
                _CustomerDocumentq = _CustomerDocument;
                _context.CustomerDocument.Add(_CustomerDocumentq);
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(BadRequest($"Ocurrio un error:{ex.Message}"));
            }

            return(await Task.Run(() => Ok(_CustomerDocumentq)));
        }
Esempio n. 21
0
        public ActionResult _AddDocument(CustomerDocumentVM mCustomerDocument)
        {
            var cd = new CustomerDocument();

            if (TryUpdateModel(cd))
            {
                cd.LoadFile(mCustomerDocument.FilePath);
                DocumentController.RemoveFile(mCustomerDocument.FilePath);
                if (ExecuteRepositoryAction(() =>
                {
                    _customerService.AddCustomerDocument(cd); _customerService.CommitChanges();
                }))
                {
                    return(ReturnJsonFormSuccess());
                }
            }

            return(PartialView("_EditCustomerDocument", mCustomerDocument));
        }
 private void AddContact(Customer customer, CustomerDocument customerDocument)
 {
     if (customerDocument.Addresses.Count > 0)
     {
         customer.Email         = customerDocument.CustomerEmail;
         customer.ShipVia       = customerDocument.ShipVia;
         customer.WebSiteURL    = customerDocument.CompanyWebsite;
         customer.CustomerSince = DateTime.Now;
         customer.IsInactive    = customerDocument.Disabled == 1;
         AddAddresses(customer, customerDocument);
         AddContacts(customer, customerDocument);
     }
     else
     {
         Logger.Information("Customer {@Name} did not have addresses so will not create a contact", customer.Name);
         ContactList contactsList = customer.Contacts;
         contactsList.Clear();
     }
 }
Esempio n. 23
0
        public void Save(string customerId, MappedCustomerMessage message)
        {
            var currentDocument = _customersDataAccess.Get <CustomerDocument>(customerId);
            var upsertCustomer  = new CustomerDocument(customerId);
            var dataToMerge     = JObject.FromObject(message.Data);

            if (currentDocument == null)
            {
                upsertCustomer.Data = message.Data.ToDictionary(x => x.Key, x => x.Value.First().Value);
                upsertCustomer.Full = dataToMerge;
            }
            else
            {
                var currentCustomerFull = new JObject(currentDocument.Full);

                currentCustomerFull.Merge(dataToMerge, new JsonMergeSettings
                {
                    MergeArrayHandling = MergeArrayHandling.Union
                });

                upsertCustomer.Full = currentCustomerFull;
                upsertCustomer.Data = currentDocument.Data;

                foreach (var customerFieldName in message.Data.Select(x => x.Key))
                {
                    var filters = _fieldMaps.Where(x => x.CustomerField.FieldName.Equals(customerFieldName, StringComparison.InvariantCultureIgnoreCase));
                    var token   = currentCustomerFull.GetValue(customerFieldName, StringComparison.InvariantCultureIgnoreCase);

                    foreach (var fieldMap in filters.Where(x => x.SourceField != null).OrderBy(x => x.Order))
                    {
                        var customerValue = token[fieldMap.SourceField.SourceId.ToString()];
                        if (customerValue != null)
                        {
                            upsertCustomer.Data[customerFieldName] = ((JValue)customerValue).Value;
                            break;
                        }
                    }
                }
            }

            _customersDataAccess.Put(upsertCustomer);
        }
Esempio n. 24
0
        public async Task <IActionResult> Delete([FromBody] CustomerDocument _CustomerDocument)
        {
            CustomerDocument _CustomerDocumentq = new CustomerDocument();

            try
            {
                _CustomerDocumentq = _context.CustomerDocument
                                     .Where(x => x.CustomerDocumentId == (Int64)_CustomerDocument.CustomerDocumentId)
                                     .FirstOrDefault();

                _context.CustomerDocument.Remove(_CustomerDocumentq);
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(await Task.Run(() => BadRequest($"Ocurrio un error:{ex.Message}")));
            }

            return(await Task.Run(() => Ok(_CustomerDocumentq)));
        }
Esempio n. 25
0
        public async Task <ActionResult <CustomerDocument> > Update([FromBody] CustomerDocument _CustomerDocument)
        {
            CustomerDocument _CustomerDocumentq = _CustomerDocument;

            try
            {
                _CustomerDocumentq = await(from c in _context.CustomerDocument
                                           .Where(q => q.CustomerDocumentId == _CustomerDocument.CustomerDocumentId)
                                           select c
                                           ).FirstOrDefaultAsync();

                _context.Entry(_CustomerDocumentq).CurrentValues.SetValues((_CustomerDocument));

                //_context.CustomerDocument.Update(_CustomerDocumentq);
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(await Task.Run(() => BadRequest($"Ocurrio un error:{ex.Message}")));
            }

            return(await Task.Run(() => Ok(_CustomerDocumentq)));
        }
Esempio n. 26
0
 public void Update(CustomerDocument model)
 {
     _repository.Update(model);
 }
Esempio n. 27
0
 public int Create(CustomerDocument model)
 {
     return(_repository.Save(model));
 }
        public HttpResponseMessage UploadImage(string aid, string pass)
        {
            string Image = null;


            string filename = null;

            var httpRequest = HttpContext.Current.Request;

            if (httpRequest.Files.GetKey(0).ToString() == "btnPan")
            {
                Image = "btnPan";
            }
            else if (httpRequest.Files.GetKey(0).ToString() == "btnVoter")
            {
                Image = "btnVoter";
            }
            else if (httpRequest.Files.GetKey(0).ToString() == "btnSalSlip")
            {
                Image = "btnSalSlip";
            }
            else if (httpRequest.Files.GetKey(0).ToString() == "btnLoa")
            {
                Image = "btnLoa";
            }
            else if (httpRequest.Files.GetKey(0).ToString() == "btnNoc")
            {
                Image = "btnNoc";
            }

            else if (httpRequest.Files.GetKey(0).ToString() == "btnAgrSale")
            {
                Image = "btnAgrSale";
            }



            //filename = new string(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
            //filename = filename + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);

            var postedFile = httpRequest.Files[Image];

            filename = new String(Path.GetFileName(postedFile.FileName).Take(10).ToArray());

            var filepath = HttpContext.Current.Server.MapPath("~/Image/" + filename); //sets file path to Image folder in VS Project

            postedFile.SaveAs(filepath);
            //CustomerDocument file = new CustomerDocument();

            if (httpRequest.Files.GetKey(0).ToString() == "btnPan")
            {
                //file.PanCard = filename;

                //db.CustomerDocuments.Add(file);
                //db.SaveChanges();

                CustomerDocument cd = new CustomerDocument();
                //file.PanCard = filename;
                cd.ApplicationID = aid;
                cd.PanCard       = filename;
                db.CustomerDocuments.Add(cd);
                db.SaveChanges();
            }
            else if (httpRequest.Files.GetKey(0).ToString() == "btnVoter")
            {
                //file.VoterID = filename;

                //db.CustomerDocuments.Add(file);
                //db.SaveChanges();

                CustomerDocument cd = db.CustomerDocuments.ToList().Find(x => x.ApplicationID == aid);
                cd.VoterID = filename;
                db.SaveChanges();
            }
            else if (httpRequest.Files.GetKey(0).ToString() == "btnSalSlip")
            {
                CustomerDocument cd = db.CustomerDocuments.ToList().Find(x => x.ApplicationID == aid);
                cd.SalarySlip = filename;
                db.SaveChanges();
            }
            else if (httpRequest.Files.GetKey(0).ToString() == "btnLoa")
            {
                CustomerDocument cd = db.CustomerDocuments.ToList().Find(x => x.ApplicationID == aid);
                cd.LOA = filename;
                db.SaveChanges();
            }
            else if (httpRequest.Files.GetKey(0).ToString() == "btnNoc")
            {
                CustomerDocument cd = db.CustomerDocuments.ToList().Find(x => x.ApplicationID == aid);
                cd.BuilderNOC = filename;
                db.SaveChanges();
            }

            else if (httpRequest.Files.GetKey(0).ToString() == "btnAgrSale")
            {
                CustomerDocument cd = db.CustomerDocuments.ToList().Find(x => x.ApplicationID == aid);
                cd.SaleAgreement = filename;
                db.SaveChanges();
            }



            return(Request.CreateResponse(HttpStatusCode.Created));
        }
Esempio n. 29
0
 private void PersistCustomer()
 {
     Record.Customer = CustomerDocument.ToString(SaveOptions.None);
 }
Esempio n. 30
0
        public long CreateDocument(DocumentViewModel documentViewModel)
        {
            Data.Entities.Context.Document document = null;
            document = repository.GetContext().Documents.Where(e => e.Id == documentViewModel.Id).FirstOrDefault();

            if (document == null)
            {   //Directory with same name already exists
                var documentType = repository.GetContext().DocumentTypes.Where(x => x.Name.ToLower() == documentViewModel.DocumentTypeViewModel.Name.ToLower()).FirstOrDefault();
                if (documentType == null)
                {
                    documentType = repository.GetContext().DocumentTypes.FirstOrDefault(x => x.Name.ToLower() == "file");
                }
                if (documentType != null)
                {
                    document = new Data.Entities.Context.Document()
                    {
                        DocumentType = documentType,
                        Name         = documentViewModel.Name,
                        Title        = documentViewModel.Title
                    };
                    document = repository.SaveNew(document);

                    if (document?.Id > 0)
                    {
                        if (documentViewModel.CustomerId > 0)
                        {
                            ///Customer related documents

                            CustomerDocument customerDocument = new CustomerDocument()
                            {
                                CustomerId = documentViewModel.CustomerId,
                                DocumentId = document.Id
                            };

                            try
                            {
                                customerDocument = repository.SaveNew(customerDocument);
                            }
                            catch (Exception ex)
                            {
                                throw;
                            }
                        }
                        else if (documentViewModel.LoanId > 0)
                        {
                            ///Loan related documents
                            LoanDocument loanDocument = new LoanDocument()
                            {
                                DocumentId = document.Id,
                                LoanId     = documentViewModel.LoanId
                            };
                            try
                            {
                                loanDocument = repository.SaveNew(loanDocument);
                            }
                            catch (Exception ex)
                            {
                                throw;
                            }
                        }
                    }
                }
            }
            return(document != null ? document.Id : 0);
        }