public CustomerEntityValidator SaveMinorProfile(MinorProfile minorProfile, string minorId, string parsedName)
        {
            var saveTrackOrder = new CustomerEntityValidator();

            var minorApplicant = new customer()
            {
                ctype           = "IL",
                fbobkind        = "IL",
                fbonumbr        = minorId,
                appldate        = DateTime.Now,
                firstname       = minorProfile.CustomersFirstname,
                middlename      = minorProfile.CustomersMiddlename,
                lastname        = minorProfile.CustomersLastname,
                fbobname        = ($"{minorProfile.CustomersFirstname} {minorProfile.CustomersMiddlename} {minorProfile.CustomersLastname}"),
                sex             = Convert.ToDecimal(minorProfile.CustomersSex),//is a string in the system
                typeofid        = minorProfile.CustomersIdtype,
                idnumber        = minorProfile.CustomersIdnumber,
                mailingcountry  = minorProfile.CustomersCountry,
                town            = minorProfile.CustomersCity,
                fbobadr1        = minorProfile.CustomersArea,
                nationality     = minorProfile.CustomersCountry,
                relationshipkin = minorProfile.CustomersRelationborrower,
                emailname       = minorProfile.CustomersEmail,
                homephone       = minorProfile.CustomersHomephone,

                birthdate = DateTime.Parse(minorProfile.CustomersBirthdate),
            };

            //Database insert operations
            using (var dpac = new DPACEntities())
            {
                try
                {
                    dpac.customers.Add(minorApplicant);
                    if (dpac.SaveChanges() > 0)
                    {
                        saveTrackOrder.Customer   = true;
                        saveTrackOrder.CustomerId = minorId;
                        dpac.updateCustCode(parsedName);
                        //dpac.FMS_InsertIntoFxrefbor(minorId, "S", DateTime.Now, "AN2019-00120");
                    }
                }
                catch (DbEntityValidationException e)
                {
                    saveTrackOrder.Customer           = false;
                    saveTrackOrder.CustomerErrMessage = e.Message;
                }
            }

            return(saveTrackOrder);
        }
        public CustomerEntityValidator SaveGuarantor(Guarantor guarantor, string guarantorId, string parsedName)
        {
            //declarations ----------

            List <individual_financials> assetList     = new List <individual_financials>();
            List <individual_financials> liabilityList = new List <individual_financials>();
            var grossFamilyIncome = new customers_financial();

            var saveOrderTrack = new CustomerEntityValidator();

            //------------ Definitions
            var guarantorRec = new customer()
            {
                ctype            = "IL",
                fbobkind         = "IL",
                fbonumbr         = guarantorId,
                appldate         = DateTime.Now,
                firstname        = guarantor.GuarantorPersonal.CustomersFirstname,
                middlename       = guarantor.GuarantorPersonal.CustomersMiddlename,
                lastname         = guarantor.GuarantorPersonal.CustomersLastname,
                fbobname         = $"{guarantor.GuarantorPersonal.CustomersFirstname} {guarantor.GuarantorPersonal.CustomersMiddlename} {guarantor.GuarantorPersonal.CustomersLastname}",
                sex              = Convert.ToDecimal(guarantor.GuarantorPersonal.CustomersSex),//is a string in the system
                mailing_address1 = guarantor.GuarantorPersonal.CustomersMailingAddress1,
                typeofid         = guarantor.GuarantorPersonal.CustomersTypeofid,
                mailing_address2 = guarantor.GuarantorPersonal.CustomersMailingAddress2,
                mailingcountry   = guarantor.GuarantorPersonal.CustomersMailingcountry,
                idnumber         = guarantor.GuarantorPersonal.CustomersIdnumber,
                nationality      = guarantor.GuarantorPersonal.CustomersMailingcountry,
                birthdate        = DateTime.Parse(guarantor.GuarantorPersonal.CustomersBirthdate),
                next_kin         = guarantor.GuarantorPersonal.CustomersNextKin,
                relationshipkin  = guarantor.GuarantorPersonal.CustomersRelationshipkin,
                emailname        = guarantor.GuarantorPersonal.CustomersEmailname,
                homephone        = guarantor.GuarantorPersonal.CustomersHomephone,
                otherphone       = guarantor.GuarantorPersonal.CustomersOtherphone,
                workphone        = guarantor.GuarantorPersonal.CustomersWorkphone,
                mobilphone       = guarantor.GuarantorPersonal.CustomersMobilphone,
                spousename       = "",
                //Customer Financial
                indusgrp    = "",
                depends     = Convert.ToDecimal(guarantor.GuarantorFinancial.CustomersDepends),
                empstatus   = Convert.ToDecimal(guarantor.GuarantorFinancial.CustomersEmpstatus),
                home_status = guarantor.GuarantorFinancial.CustomersHomeStatus,//Live Rent free
                num_inhouse = Convert.ToDecimal(guarantor.GuarantorFinancial.CustomersNumInhouse),
                yearsaddr   = Convert.ToDecimal(guarantor.GuarantorFinancial.CustomersYearsaddr)
            };

            if (guarantor.GuarantorFinancial.Asset != null)
            {
                foreach (var asset in guarantor.GuarantorFinancial.Asset)
                {
                    assetList.Add(new individual_financials()
                    {
                        fbonumbr    = guarantorId,
                        code        = asset.IndividualFinancialsCode,
                        amount      = Convert.ToDecimal(asset.IndividualFinancialsAmount),
                        description = asset.IndividualFinancialsDescription
                    });
                }
            }

            if (guarantor.GuarantorFinancial.Liabilities != null)
            {
                foreach (var liability in guarantor.GuarantorFinancial.Liabilities)
                {
                    liabilityList.Add(new individual_financials()
                    {
                        fbonumbr    = guarantorId,
                        code        = liability.IndividualFinancialsCode,
                        amount      = Convert.ToDecimal(liability.IndividualFinancialsAmount),
                        description = liability.IndividualFinancialsDescription
                    });
                }
            }

            if (guarantor.GuarantorFinancial.GrossAnnualFamilyIncome != null)
            {
                var g = guarantor.GuarantorFinancial.GrossAnnualFamilyIncome.FirstOrDefault();
                grossFamilyIncome = new customers_financial()
                {
                    fbonumbr = guarantorId,
                    income2  = Convert.ToDecimal(g.CustomersFinancialIncome2),
                    income4  = Convert.ToDecimal(g.CustomersFinancialIncome4)
                };
            }

            //Database insert operations
            using (var dpac = new DPACEntities())
            {
                try
                {
                    dpac.customers.Add(guarantorRec);
                    if (dpac.SaveChanges() > 0)
                    {
                        saveOrderTrack.Customer   = true;
                        saveOrderTrack.CustomerId = guarantorId;
                        dpac.updateCustCode(parsedName);
                    }
                }
                catch (DbEntityValidationException e)
                {
                    saveOrderTrack.Customer           = false;
                    saveOrderTrack.CustomerErrMessage = e.Message;
                }

                //---- asset
                try
                {
                    if (guarantor.GuarantorFinancial.Asset != null && saveOrderTrack.Customer)
                    {
                        foreach (var g in assetList)
                        {
                            dpac.individual_financials.Add(g);
                        }
                    }

                    if (dpac.SaveChanges() > 0)
                    {
                        saveOrderTrack.Asset = true;
                    }
                }
                catch (DbEntityValidationException e)
                {
                    saveOrderTrack.Asset           = false;
                    saveOrderTrack.AssetErrMessage = e.Message;
                }

                //--- liabilites
                try
                {
                    if (guarantor.GuarantorFinancial.Liabilities != null && saveOrderTrack.Customer)
                    {
                        foreach (var l in liabilityList)
                        {
                            dpac.individual_financials.Add(l);
                        }
                    }
                    if (dpac.SaveChanges() > 0)
                    {
                        saveOrderTrack.Liability = true;
                    }
                }
                catch (DbEntityValidationException e)
                {
                    saveOrderTrack.Liability           = false;
                    saveOrderTrack.LiabilityErrMessage = e.Message;
                }

                // ----- gross family income

                try
                {
                    if (guarantor.GuarantorFinancial.GrossAnnualFamilyIncome != null && saveOrderTrack.Customer)
                    {
                        dpac.customers_financial.Add(grossFamilyIncome);
                    }
                    if (dpac.SaveChanges() > 0)
                    {
                        saveOrderTrack.GrossFamilyIncome = true;
                    }
                }
                catch (DbEntityValidationException e)
                {
                    saveOrderTrack.GrossFamilyIncome     = false;
                    saveOrderTrack.GrossFamilyErrMessage = e.Message;
                }
            }

            return(saveOrderTrack);
        }
        public CustomerEntityValidator SaveLoanApplicant(LoanApplicantProfile applicant, string applicantId, string parsedName)
        {
            //declarations
            List <individual_financials> assetList         = new List <individual_financials>();
            List <individual_financials> liabilityList     = new List <individual_financials>();
            customers_financial          grossFamilyIncome = new customers_financial();

            var saveOrderTrack = new CustomerEntityValidator();


            //definitions
            var loanApplicant = new customer()
            {
                ctype            = "IL", //default val
                fbobkind         = "IL", //default val
                prefix           = (Convert.ToDecimal(applicant.CustomersSex) == 1) ? "Mr" : "Ms",
                fbonumbr         = applicantId,
                appldate         = DateTime.Now,
                firstname        = applicant.CustomersFirstname,
                middlename       = applicant.CustomersMiddlename,
                lastname         = applicant.CustomersLastname,
                fbobname         = ($"{applicant.CustomersFirstname} {applicant.CustomersMiddlename} {applicant.CustomersLastname}"),
                sex              = Convert.ToDecimal(applicant.CustomersSex),
                mailing_address1 = applicant.CustomersMailingAddress1,
                fbobadr1         = applicant.CustomersMailingAddress1,
                fbobadr2         = applicant.CustomersMailingAddress2,
                mailing_address2 = applicant.CustomersMailingAddress2,
                mailingcountry   = applicant.CustomersMailingcountry,
                typeofid         = applicant.CustomersTypeofid,
                idnumber         = applicant.CustomersIdnumber,
                nationality      = applicant.CustomersNationality,
                businessplace    = applicant.CustomersBusinessplace,
                employfrom       = (DateTime.TryParse(applicant.CustomersEmployfrom, out DateTime date)) ? date: (DateTime?)null,
                //Format: 1/07/2019 ---(string.IsNullOrWhiteSpace(applicant.CustomersEmployfrom))? null: applicant.CustomersEmployfrom
                occupation = applicant.CustomersOccupation,
                //customer_financial.income1
                depends         = Convert.ToDecimal(applicant.CustomersDepends),
                empstatus       = Convert.ToDecimal(applicant.CustomersEmpstatus),
                home_status     = applicant.CustomersHomeStatus,//mortgage
                num_inhouse     = Convert.ToDecimal(applicant.CustomersNumInhouse),
                yearsaddr       = Convert.ToDecimal(applicant.CustomersYearsaddr),
                next_kin        = applicant.CustomersNextKin,
                relationshipkin = applicant.CustomersRelationshipkin,
                emailname       = applicant.CustomersEmailname,
                homephone       = applicant.CustomersHomephone,
                otherphone      = applicant.CustomersOtherphone,
                workphone       = applicant.CustomersWorkphone,
                mobilphone      = applicant.CustomersMobilphone,
                spousename      = "",
            };

            //prepping assets in a list
            if (applicant.Asset != null)
            {
                foreach (var asset in applicant.Asset)
                {
                    assetList.Add(new individual_financials()
                    {
                        fbonumbr    = applicantId,
                        code        = asset.IndividualFinancialsCode,
                        amount      = Convert.ToDecimal(asset.IndividualFinancialsAmount),
                        description = asset.IndividualFinancialsDescription
                    });
                }
            }

            //prepping liabilities
            if (applicant.Liabilities != null)
            {
                foreach (var liability in applicant.Liabilities)
                {
                    liabilityList.Add(new individual_financials()
                    {
                        fbonumbr    = applicantId,
                        code        = liability.IndividualFinancialsCode,
                        amount      = Convert.ToDecimal(liability.IndividualFinancialsAmount),
                        description = liability.IndividualFinancialsDescription
                    });
                }
            }

            //gross family income
            if (applicant.GrossAnnualFamilyIncome != null)
            {
                var g = applicant.GrossAnnualFamilyIncome.FirstOrDefault();
                grossFamilyIncome = new customers_financial()
                {
                    fbonumbr = applicantId,
                    income2  = Convert.ToDecimal(g.CustomersFinancialIncome2),
                    income4  = Convert.ToDecimal(g.CustomersFinancialIncome4)
                };
            }

            //database operations  which will save the above entities into, you guessed it, the database
            using (var ctx = new DPACEntities())
            {
                try
                {
                    ctx.customers.Add(loanApplicant);
                    if (ctx.SaveChanges() > 0)
                    {
                        ctx.SaveChanges();
                        ctx.updateCustCode(parsedName);
                        saveOrderTrack.Customer   = true;
                        saveOrderTrack.CustomerId = applicantId;
                    }
                }
                catch (DbEntityValidationException e)
                {
                    saveOrderTrack.Customer           = false;
                    saveOrderTrack.CustomerErrMessage = e.Message;
                }
                //saving assets
                try
                {
                    if (assetList.Any() && saveOrderTrack.Customer)
                    {
                        foreach (var asset in assetList)
                        {
                            ctx.individual_financials.Add(asset);
                        }

                        if (ctx.SaveChanges() > 0)
                        {
                            saveOrderTrack.Asset = true;
                        }
                    }
                }
                catch (DbEntityValidationException e)
                {
                    saveOrderTrack.Asset           = false;
                    saveOrderTrack.AssetErrMessage = e.Message;
                }
                //saving liabilities
                try
                {
                    if (liabilityList.Any() && saveOrderTrack.Customer)
                    {
                        foreach (var liabilities in liabilityList)
                        {
                            ctx.individual_financials.Add(liabilities);
                        }
                    }
                    if (ctx.SaveChanges() > 0)
                    {
                        saveOrderTrack.Liability = true;
                    }
                }
                catch (DbEntityValidationException e)
                {
                    saveOrderTrack.Liability           = false;
                    saveOrderTrack.LiabilityErrMessage = e.Message;
                }
                //saving gross family income
                try
                {
                    if (!grossFamilyIncome.fbonumbr.IsNullOrWhiteSpace() && saveOrderTrack.Customer)
                    {
                        ctx.customers_financial.Add(grossFamilyIncome);
                    }

                    if (ctx.SaveChanges() > 0)
                    {
                        saveOrderTrack.GrossFamilyIncome = true;
                    }
                }
                catch (DbEntityValidationException e)
                {
                    saveOrderTrack.GrossFamilyIncome     = false;
                    saveOrderTrack.GrossFamilyErrMessage = e.Message;
                }
            }

            return(saveOrderTrack);
        }
        public LoanInsertionResult ProcessStudentLoanForDbEntry(StudentLoan loan)
        {
            string        minorId = null;
            string        applicantId;
            List <string> guarantorIds = new List <string>();

            string LoanApplicationId;

            //result container
            CustomerEntityValidator        loanApplicantResult = new CustomerEntityValidator();
            CustomerEntityValidator        minorProfileResult  = new CustomerEntityValidator();
            List <CustomerEntityValidator> guarantorResults    = new List <CustomerEntityValidator>();


            var  loanConfigResult          = new Application();
            var  studentDataResult         = new Application();
            bool crossReferenceMinorResult = false;

            IList <bool> crossReferenceGuarantorResults = new List <bool>();

            //Loan applicant Operations
            if (loan.LoanApplicantProfile.ApplicantId == null)
            {
                var appId = new CustomerDbHandler(loan.LoanApplicantProfile.CustomersFirstname, loan.LoanApplicantProfile.CustomersLastname, loan.LoanApplicantProfile.CustomersMiddlename);
                appId.CreateCustomerId();
                // string id = appId.CustomerId;
                loanApplicantResult = SaveLoanApplicant(loan.LoanApplicantProfile, appId.CustomerId, appId.ParsedName);

                applicantId = null;
            }
            else
            {
                applicantId = (ValidateCustomerPostId(loan.LoanApplicantProfile.ApplicantId))? loan.LoanApplicantProfile.ApplicantId.ToUpper() : null;
                loanApplicantResult.CustomerId = (applicantId != null) ? applicantId : null;
                loanApplicantResult.Customer   = (applicantId != null) ? true : false;
                //simply discards the posted info and retains the given ID, also run further validation on Id
            }

            //Minor profile operations
            if (loan.MinorProfile != null)
            {
                if (loan.MinorProfile.MinorId == null)
                {
                    var minorCustomer = new CustomerDbHandler(loan.MinorProfile.CustomersFirstname, loan.MinorProfile.CustomersLastname, loan.MinorProfile.CustomersMiddlename);
                    minorCustomer.CreateCustomerId();

                    minorProfileResult = SaveMinorProfile(loan.MinorProfile, minorCustomer.CustomerId, minorCustomer.ParsedName);
                }
                else
                {
                    minorId = (ValidateCustomerPostId(loan.MinorProfile.MinorId)) ? loan.MinorProfile.MinorId.ToUpper() : null;
                    minorProfileResult.CustomerId = (minorId != null)? minorId : null;
                    minorProfileResult.Customer   = (minorId != null) ? true : false;
                }
            }


            //Guarantor Operations
            if (loan.Guarantors != null)
            {
                foreach (var guarantor in loan.Guarantors)
                {
                    if (guarantor.ApplicantId == null)
                    {
                        var g = new CustomerDbHandler(guarantor.GuarantorPersonal.CustomersFirstname, guarantor.GuarantorPersonal.CustomersLastname, guarantor.GuarantorPersonal.CustomersMiddlename);
                        g.CreateCustomerId();

                        guarantorResults.Add(SaveGuarantor(guarantor, g.CustomerId, g.ParsedName));
                    }
                    else
                    {
                        if (ValidateCustomerPostId(guarantor.ApplicantId.ToUpper()))
                        {
                            guarantorIds.Add(guarantor.ApplicantId.ToUpper());
                            guarantorResults.Add(new CustomerEntityValidator()
                            {
                                CustomerId          = guarantor.ApplicantId.ToUpper(),
                                Customer            = true,
                                IsExistingGuarantor = true,
                            });
                        }
                    }
                }
            }

            //Loan configuration operations
            if (loan.LoanConfig != null)
            {
                string globAppId;
                var    application = new Application();
                if (application.CreateApplicationId())
                {
                    if (string.IsNullOrEmpty(applicantId))
                    {
                        LoanApplicationId = application.ApplicationId;

                        loanConfigResult = SaveLoanConfiguration(loan.LoanConfig, LoanApplicationId, loanApplicantResult.CustomerId, loan.LoanConfig.OfficerId);
                    }
                    else
                    {
                        loanConfigResult = SaveLoanConfiguration(loan.LoanConfig, application.ApplicationId, applicantId, loan.LoanConfig.OfficerId);
                        //  globAppId = loanConfigResult.ApplicationId;
                    }
                }



                //Education Program Data operations
                if (loan.EducationProgramData != null && loanConfigResult.ApplicationSuccess)
                {
                    studentDataResult = SaveEducationProgramData(loan.EducationProgramData, loanConfigResult.ApplicationId, applicantId);
                }
            }

            //Finally, linking the entities into a relational model
            if (minorId == null && loanConfigResult.ApplicationSuccess)
            {
                if (minorProfileResult.Customer && loanConfigResult.ApplicationSuccess)
                {
                    crossReferenceMinorResult = CrossReferenceEntity(minorProfileResult.CustomerId, "S", loanConfigResult.ApplicationId);
                }
            }
            else
            {
                crossReferenceMinorResult = CrossReferenceEntity(minorId, "S", loanConfigResult.ApplicationId);
            }

            if (loanConfigResult.ApplicationSuccess)
            {
                foreach (var guarantorRes in guarantorResults)
                {
                    if (guarantorRes.Customer && !(guarantorRes.IsExistingGuarantor))
                    {
                        crossReferenceGuarantorResults.Add(CrossReferenceEntity(guarantorRes.CustomerId, "G", loanConfigResult.ApplicationId));
                    }
                }

                if (guarantorIds.Any())
                {
                    foreach (var g in guarantorIds)
                    {
                        crossReferenceGuarantorResults.Add(CrossReferenceEntity(g, "G", loanConfigResult.ApplicationId));
                    }
                }
            }

            return(new LoanInsertionResult()
            {
                Applicant = loanApplicantResult,
                Minor = minorProfileResult,
                Guarantors = guarantorResults,

                LoanApplication = loanConfigResult,
                StudentInformation = studentDataResult,

                CrossReferenceOperation = crossReferenceMinorResult,
                CrossRefGuarantorOperation = crossReferenceGuarantorResults
            });
        }