public Agreement ExtendAgreement(int customerId)
        {
            try
            {
                using (var transaction = new TransactionScope())
                {
                    Customer customer = repository.First<Customer>(customerId);

                    if (customer != null)
                    {
                        foreach (var agreement in customer.Agreements)
                        {
                            repository.Delete(agreement);
                        }
                    }

                    Agreement extendedAgreement = new Agreement();
                    extendedAgreement.Customer = customer;
                    extendedAgreement.Number = GenerateAgreementNumber();
                    extendedAgreement.CreatedOn = DateTime.Now;

                    repository.Save(extendedAgreement);
                    repository.Commit();

                    transaction.Complete();

                    return extendedAgreement;
                }
            }
            catch (Exception ex)
            {
                throw new AgreementManagementException(string.Format("Failed to extend agreement for customer {0}.", customerId), ex);
            }
        }
 protected Agreement CaptureData()
 {
     Agreement obj = new Agreement();
     obj.Agreement_ID = txtID.Text.Trim();
     obj.Agreement_Name = txtName.Text.Trim();
     return obj;
 }
 protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
 {
     AgreementManager mgr = new AgreementManager();
     Agreement obj = new Agreement();
     obj.Agreement_ID = (GridView1.SelectedDataKey).Value.ToString();
     obj = mgr.selectAgreement(obj);
     AddEditAgreementControl1.populateControls(obj);
     MultiView1.ActiveViewIndex = 1;
 }
 public void populateControls(Agreement obj)
 {
     Session.Remove("Flag");
     Session.Add("Flag", "Edit");
     btnOpt.Text = "Modify Agreement";
     btnDelete.Enabled = true;
     txtID.Text = obj.Agreement_ID;
     txtName.Text = obj.Agreement_Name;
 }
 protected void btnDelete_Click(object sender, EventArgs e)
 {
     try
     {
         AgreementManager mgr = new AgreementManager();
         Agreement obj = new Agreement();
         obj.Agreement_ID = txtID.Text.Trim();
         lblError.Text = CustomErrors.CHANGES_ACCEDTED_STATUS + mgr.deleteAgreement(obj);
         ClearControls();
     }
     catch(Exception ex)
     {
         lblError.Text = ex.Message;
     }
 }
        public Agreement ExtendAgreement(int customerId)
        {
            try
            {
                try
                {
                    unitOfWork.BeginTransaction();

                    Customer customer = unitOfWork.Session.Query<Customer>().FetchMany(f => f.Agreements).FirstOrDefault(f => f.Id == customerId && f.DeletedOn == null);
                    if (customer != null)
                    {
                        foreach (var agreement in customer.Agreements)
                        {
                            unitOfWork.Session.Delete(agreement);
                        }
                    }

                    Agreement extendedAgreement = new Agreement();
                    extendedAgreement.Customer = customer;
                    extendedAgreement.Number = GenerateAgreementNumber();
                    extendedAgreement.CreatedOn = DateTime.Now;

                    unitOfWork.Session.SaveOrUpdate(extendedAgreement);
                    unitOfWork.Commit();

                    return extendedAgreement;
                }
                catch (Exception)
                {
                    unitOfWork.Rollback();
                    throw;
                }
            }
            catch (Exception ex)
            {
                throw new AgreementManagementException(string.Format("Failed to extend agreement for customer {0}.", customerId), ex);
            }
        }
Esempio n. 7
0
 private void CreateSignatureBitmap(Agreement agreement, SignatureToImage sigToImage, string signatureUrl)
 {
     var bitmap = sigToImage.SigJsonToImage(agreement.Signature);
     var targetPath = Server.MapPath(signatureUrl);
     bitmap.Save(targetPath, ImageFormat.Gif);
 }
Esempio n. 8
0
 private static void SendByMail(AgentInfo agent, Agreement agreement, string destFile)
 {
     Task.Factory.StartNew(() =>
                               {
                                   try
                                   {
                                       SystemMonitor.Info("Sending Email to: {0}, {1}", agent.Email,
                                                          agreement.CustomerEmail);
                                       SendEmail(agent, agreement, destFile);
                                   }
                                   catch (Exception anyException)
                                   {
                                       SystemMonitor.Error(anyException, "Failed to send agreement by mail.");
                                   }
                               });
 }
Esempio n. 9
0
        public ActionResult PropertyAgreement(AgentInfo agent, Agreement agreement)
        {
            try
            {
                SystemMonitor.Info("Sending property agreement from agent '{0}' to customer '{1}'.", agent.FullName, agreement.CustomerName);
                
                agreement.Signature = CreateSignature(agreement);
                
                SystemMonitor.Debug("Signature created, url: {0}", agreement.Signature);

                var destFile = GenerateReport(agent, agreement);

                SystemMonitor.Debug("Report generated, file name: {0}", System.IO.Path.GetFileName(destFile));

                SendByMail(agent, agreement, destFile);
            }
            catch (Exception anyException)
            {
                SystemMonitor.Error(anyException, "Error Creating agreement report");
                return new HttpStatusCodeResult(500);
            }
            return new HttpStatusCodeResult(200);
        }
Esempio n. 10
0
        public void SendAgreement(Agreement agreement)
        {
            var exchangeConfig = new Tuple <string, string>("agreements", "addAgreement");

            SendEventHandler.SendEvent(agreement, _rabbitMqOptions, exchangeConfig);
        }
Esempio n. 11
0
 public void UpdateAgreement(int id, Agreement agreement)
 {
     _UnitOfWork.AgreementRepository.Update(id, agreement);
 }
Esempio n. 12
0
 public AgreementInfo(Agreement agreement)
 {
     _agreement       = agreement;
     _agreementNumber = agreement.AgreementNumber;
     _companyName     = agreement.Company.Name;
 }
        private FinancialAccount CreateFinancialAccountWithParent(Agreement agreement, DateTime today, FinancialAccount financialAccountParent)
        {
            FinancialAccount financialAccountNew1 = new FinancialAccount();
            financialAccountNew1.Agreement = agreement;
            financialAccountNew1.FinancialAccountType = FinancialAccountType.LoanAccountType;
            financialAccountNew1.ParentFinancialAccountId = financialAccountParent.Id;

            return financialAccountNew1;
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //Post back to either sandbox or live
            m_ManagementService.SQLConnection = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
            var    config      = ConfigManager.Instance.GetProperties();
            var    accessToken = new OAuthTokenCredential(config).GetAccessToken();
            var    apiContext  = new APIContext(accessToken);
            string url         = "";;
            if (config["mode"].ToLower() == "sandbox")
            {
                url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
            }
            else
            {
                url = "https://www.paypal.com/cgi-bin/webscr";
            }

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
            //Set values for the request back
            req.Method      = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] Param      = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
            string strRequest = Encoding.ASCII.GetString(Param);
            strRequest        = strRequest + "&cmd=_notify-validate";
            req.ContentLength = strRequest.Length;

            //Send the request to PayPal and get the response
            StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);
            streamOut.Write(strRequest);
            streamOut.Close();

            StreamReader streamIn    = new StreamReader(req.GetResponse().GetResponseStream());
            string       strResponse = streamIn.ReadToEnd();
            streamIn.Close();

            if (strResponse == "VERIFIED")
            {
                NameValueCollection qscoll = HttpUtility.ParseQueryString(strRequest);
                string   agreementID       = Convert.ToString(qscoll["recurring_payment_id"]);
                DateTime lastPaymentDate   = default(DateTime);
                decimal  lastPaymentAmount = default(decimal);
                DateTime nextBillingDate   = default(DateTime);

                Agreement agreement = PayPal.Api.Agreement.Get(apiContext, agreementID);

                if ((agreement != null))
                {
                    if ((agreement.agreement_details != null) && (agreement.agreement_details.last_payment_date != null) && (agreement.agreement_details.next_billing_date != null) && (agreement.agreement_details.last_payment_amount != null))
                    {
                        lastPaymentDate   = Convert.ToDateTime(agreement.agreement_details.last_payment_date);
                        nextBillingDate   = Convert.ToDateTime(agreement.agreement_details.next_billing_date);
                        lastPaymentAmount = Convert.ToDecimal(agreement.agreement_details.last_payment_amount.value);
                        m_ManagementService.UpdateBillingSubscription(agreementID, lastPaymentDate, lastPaymentAmount, nextBillingDate);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            m_ManagementService.LogError(ex.Message, ex.StackTrace);
        }
    }
Esempio n. 15
0
 public Entities.Agreement MapToEntity(Agreement agreement)
 {
     return(this.Mapper.Map <Entities.Agreement>(agreement));
 }
Esempio n. 16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PSAgreement" /> class.
 /// </summary>
 /// <param name="agreement">The base agreement for this instance.</param>
 public PSAgreement(Agreement agreement)
 {
     this.CopyFrom(agreement);
 }
Esempio n. 17
0
 public IEnumerable <byte> ToBytes()
 {
     return(Era.ToBytes().Concat(Agreement.ToBytes()).Concat(Epoch.ToBytes()));
 }
        public async Task <HttpResponseMessage> UpdateAgreementAsync(string id, Agreement agreement)
        {
            var load = new HttpClient();

            return(await load.PutAsync($"{baseUrl}api/Agreement/UpdateAgreement/{id}", getStringContentFromObject(agreement)));
        }
        public async Task <HttpResponseMessage> InsertAgreementAsync(Agreement agreement)
        {
            var load = new HttpClient();

            return(await load.PostAsync($"{baseUrl}api/Agreement/AddAgreement", getStringContentFromObject(agreement)));
        }
Esempio n. 20
0
        public ActionResult TestRecurring()
        {
            string sPricePlan = Helpers.Tools.PriceFormat(priceItem);
            string sTaxAmt    = Helpers.Tools.PriceFormat(priceItem * tax);
            //string sSubtotal = Helpers.Tools.PriceFormat(decimal.Parse(sPriceItem) - decimal.Parse(sTaxAmt));

            APIContext apiContext = clsPayPal.PayPalConfig.GetAPIContext();

            Session["accesstoken"] = apiContext.AccessToken;

            ChargeModel cModel = new ChargeModel()
            {
                amount = new Currency()
                {
                    currency = currency,
                    value    = sTaxAmt
                },
                type = "TAX"
            };

            //cModel = new ChargeModel()
            //{
            //    amount = new Currency()
            //    {
            //        currency = currency,
            //        value = sTaxAmt
            //    },
            //    type = "SHIPPING"
            //};

            List <ChargeModel> lstModels = new List <ChargeModel>();

            lstModels.Add(cModel);

            PaymentDefinition pDef = new PaymentDefinition()
            {
                amount = new Currency()
                {
                    currency = currency,
                    value    = sPricePlan
                },
                cycles             = "11",
                charge_models      = lstModels,
                frequency          = "MONTH",
                frequency_interval = "1",
                type = "REGULAR",
                name = "pmt recurring",
            };
            List <PaymentDefinition> lstPayDef = new List <PaymentDefinition>();

            lstPayDef.Add(pDef);

            MerchantPreferences merPref = new MerchantPreferences()
            {
                setup_fee = new Currency()
                {
                    currency = currency,
                    value    = "1"
                },
                auto_bill_amount           = "YES",
                max_fail_attempts          = "0",
                initial_fail_amount_action = "CONTINUE",
                return_url = returnURL,
                cancel_url = cancelURL
            };

            Plan createdPlan = Plan.Get(apiContext, "P-4NL72850M8850524J7ZREBTY");

            if (createdPlan == null)
            {
                Plan myPlan = new Plan();
                myPlan.name                 = "Plan One";
                myPlan.description          = "Plan One Description";
                myPlan.type                 = "fixed";
                myPlan.payment_definitions  = lstPayDef;
                myPlan.merchant_preferences = merPref;
                var guid = Convert.ToString((new Random()).Next(100000));
                myPlan.merchant_preferences.return_url = Request.Url.ToString() + "?guid=" + guid;
                createdPlan = myPlan.Create(apiContext);
            }

            // Activate the plan
            var patchRequest = new PatchRequest()
            {
                new Patch()
                {
                    op    = "replace",
                    path  = "/",
                    value = new Plan()
                    {
                        state = "ACTIVE"
                    }
                }
            };

            createdPlan.Update(apiContext, patchRequest);

            ShippingAddress shippAddr = new ShippingAddress()
            {
                line1        = "111 First Street",
                city         = "Toronto",
                state        = "ON",
                postal_code  = "95070",
                country_code = "CA"
            };

            //Agreement newSub =clsPayPal.CreateBillingAgreement(hPlan.id, shippAddr, "some name", "some description", DateTime.Now);

            var agreement = new Agreement()
            {
                name        = "some name",
                description = "some description",
                start_date  = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + "Z",
                payer       = new Payer()
                {
                    payment_method = "paypal",
                },
                plan = new Plan()
                {
                    id = createdPlan.id
                },
                shipping_address = shippAddr,
            };


            var createdAgreement = agreement.Create(apiContext);

            //return createdAgreement;



            /////

            //Details dtl = new Details()
            //{
            //    tax = sTaxAmt,
            //    subtotal = sSubtotal,
            //    shipping = "0",
            //};

            ////contact infor
            //Address addr = new Address()
            //{
            //    city = sCity,
            //    country_code = sCountryCode,
            //    line1 = sAddressLine1,
            //    line2 = sAddressLine2,
            //    phone = sPhone,
            //    postal_code = sPostalCode,
            //    state = sProvince,
            //};

            //PayerInfo payInfo = new PayerInfo()
            //{
            //    //billing_address = addr,
            //    //country_code= sCountryCode,
            //    first_name = sFirstName,
            //    last_name = sLastName,
            //    //middle_name ="",
            //    email = sEmail,
            //    //phone =sPhone,
            //};

            //Amount amnt = new Amount()
            //{
            //    currency = currency,
            //    total = sPricePlan,
            //    details = dtl,
            //};

            //List<Transaction> transactionList = new List<Transaction>();
            //Transaction tran = new Transaction()
            //{
            //    description = sItemName,
            //    custom = sItemName + " some additional information",
            //    amount = amnt
            //};
            //transactionList.Add(tran);

            //Payer payr = new Payer();
            //payr.payment_method = "paypal";
            //payr.payer_info = payInfo;

            //RedirectUrls redirUrls = new RedirectUrls();
            //redirUrls.cancel_url = "https://devtools-paypal.com/guide/pay_paypal/dotnet?cancel=true";
            ////redirUrls.return_url = "https://devtools-paypal.com/guide/pay_paypal/dotnet?success=true";
            //redirUrls.return_url = "https://localhost:44320/PayPal/ReturnTestRecurring";

            //Payment pymnt = new Payment();
            //pymnt.intent = "sale";
            //pymnt.payer = payr;
            //pymnt.transactions = transactionList;
            //pymnt.redirect_urls = redirUrls;

            //Payment createdPayment = pymnt.Create(apiContext);
            //string ApprovalURL = createdPayment.GetApprovalUrl();

            //Response.Redirect(ApprovalURL);

            return(View());
        }
Esempio n. 21
0
        private string RenderReport(AgentInfo agent, Agreement agreement)
        {
            var destFile = Path.GetTempFileName() + ".pdf";
            var designFile = Server.MapPath("~/Static/Reports/" + (agreement.IsExclusive ? "Exclusive":"") +"PropertyAgreement.rdlc");

            var parameters = CreateReportParameters(agent);

            Render(designFile, 
                new ReportDataSource[]
                    {
                        new ReportDataSource("Agreement", new[] {agreement})
                    }, destFile,
                   parameters);
            return destFile;
        }
        private AgreementRole CreateAgreementRole(Agreement agreement, PartyRole role)
        {
            AgreementRole agreementRole = new AgreementRole();
            agreementRole.Agreement = agreement;
            agreementRole.PartyRole = role;

            return agreementRole;
        }
Esempio n. 23
0
 /// <summary>
 /// Saves new agreement.
 /// </summary>
 /// <param name="agreement">Agreement to save.</param>
 /// <permission cref="System.Security.PermissionSet"> Accessible from the outside.</permission>
 public void SaveAgreement(Agreement agreement)
 {
     context.Agreements.Add(agreement);
     context.SaveChanges();
 }
        private Agreement CreateNewAgreement(Application application, DateTime today)
        {
            Agreement agreement = new Agreement();
            agreement.Application = application;
            agreement.AgreementType = AgreementType.LoanAgreementType;
            agreement.EffectiveDate = today;
            agreement.AgreementDate = today;

            return agreement;
        }
Esempio n. 25
0
 private static bool AgreementHasBeenSigned(Agreement agreement)
 {
     return((agreement.Status == EmployerAgreementStatus.Signed || agreement.Status == EmployerAgreementStatus.Expired || agreement.Status == EmployerAgreementStatus.Superseded) && agreement.SignedDate.HasValue);
 }
Esempio n. 26
0
 public void UpdateAgreement(Agreement source, Agreement target)
 {
     _context.Entry(source).CurrentValues.SetValues(target);
 }
Esempio n. 27
0
 public void TestInitialize()
 {
     _agreementManager = new AgreementManager();
     _agreement = null;
 }
Esempio n. 28
0
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            if (customer == null)
            {
                throw new Exception("Customer cannot be loaded");
            }

            try
            {
                var apiContext = PaypalHelper.GetApiContext(_paypalDirectPaymentSettings);
                var currency   = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);

                //check that webhook exists
                if (string.IsNullOrEmpty(_paypalDirectPaymentSettings.WebhookId))
                {
                    result.AddError("Recurring payments are not available until you create a webhook");
                    return(result);
                }

                Webhook.Get(apiContext, _paypalDirectPaymentSettings.WebhookId);

                //create the plan
                var url         = _storeContext.CurrentStore.SslEnabled ? _storeContext.CurrentStore.SecureUrl : _storeContext.CurrentStore.Url;
                var billingPlan = new Plan
                {
                    name                 = processPaymentRequest.OrderGuid.ToString(),
                    description          = string.Format("nopCommerce billing plan for the {0} order", processPaymentRequest.OrderGuid),
                    type                 = "fixed",
                    merchant_preferences = new MerchantPreferences
                    {
                        return_url       = url,
                        cancel_url       = url,
                        auto_bill_amount = "YES",
                        //setting setup fee as the first payment (workaround for the processing first payment immediately)
                        setup_fee = new PayPal.Api.Currency
                        {
                            currency = currency != null ? currency.CurrencyCode : null,
                            value    = processPaymentRequest.OrderTotal.ToString("N", new CultureInfo("en-US"))
                        }
                    },
                    payment_definitions = new List <PaymentDefinition>
                    {
                        new PaymentDefinition
                        {
                            name = "nopCommerce payment for the billing plan",
                            type = "REGULAR",
                            frequency_interval = processPaymentRequest.RecurringCycleLength.ToString(),
                            frequency          = processPaymentRequest.RecurringCyclePeriod.ToString().TrimEnd('s'),
                            cycles             = (processPaymentRequest.RecurringTotalCycles - 1).ToString(),
                            amount             = new PayPal.Api.Currency
                            {
                                currency = currency != null ? currency.CurrencyCode : null,
                                value    = processPaymentRequest.OrderTotal.ToString("N", new CultureInfo("en-US"))
                            }
                        }
                    }
                }.Create(apiContext);

                //activate the plan
                var patchRequest = new PatchRequest()
                {
                    new Patch()
                    {
                        op    = "replace",
                        path  = "/",
                        value = new Plan
                        {
                            state = "ACTIVE"
                        }
                    }
                };
                billingPlan.Update(apiContext, patchRequest);

                //create subscription
                var subscription = new Agreement
                {
                    name = string.Format("nopCommerce subscription for the {0} order", processPaymentRequest.OrderGuid),
                    //we set order guid in the description, then use it in the webhook handler
                    description = processPaymentRequest.OrderGuid.ToString(),
                    //setting start date as the next date of recurring payments as the setup fee was the first payment
                    start_date = GetStartDate(processPaymentRequest.RecurringCyclePeriod, processPaymentRequest.RecurringCycleLength),

                    #region payer

                    payer = new Payer()
                    {
                        payment_method = "credit_card",

                        #region credit card info

                        funding_instruments = new List <FundingInstrument>
                        {
                            new FundingInstrument
                            {
                                credit_card = new CreditCard
                                {
                                    type         = processPaymentRequest.CreditCardType.ToLowerInvariant(),
                                    number       = processPaymentRequest.CreditCardNumber,
                                    cvv2         = processPaymentRequest.CreditCardCvv2,
                                    expire_month = processPaymentRequest.CreditCardExpireMonth,
                                    expire_year  = processPaymentRequest.CreditCardExpireYear
                                }
                            }
                        },

                        #endregion

                        #region payer info

                        payer_info = new PayerInfo
                        {
                            #region billing address

                            billing_address = customer.BillingAddress == null ? null : new Address
                            {
                                country_code = customer.BillingAddress.Country != null ? customer.BillingAddress.Country.TwoLetterIsoCode : null,
                                state        = customer.BillingAddress.StateProvince != null ? customer.BillingAddress.StateProvince.Abbreviation : null,
                                city         = customer.BillingAddress.City,
                                line1        = customer.BillingAddress.Address1,
                                line2        = customer.BillingAddress.Address2,
                                phone        = customer.BillingAddress.PhoneNumber,
                                postal_code  = customer.BillingAddress.ZipPostalCode
                            },

                            #endregion

                            email      = customer.BillingAddress.Email,
                            first_name = customer.BillingAddress.FirstName,
                            last_name  = customer.BillingAddress.LastName
                        }

                        #endregion
                    },

                    #endregion

                    #region shipping address

                    shipping_address = customer.ShippingAddress == null ? null : new ShippingAddress
                    {
                        country_code = customer.ShippingAddress.Country != null ? customer.ShippingAddress.Country.TwoLetterIsoCode : null,
                        state        = customer.ShippingAddress.StateProvince != null ? customer.ShippingAddress.StateProvince.Abbreviation : null,
                        city         = customer.ShippingAddress.City,
                        line1        = customer.ShippingAddress.Address1,
                        line2        = customer.ShippingAddress.Address2,
                        phone        = customer.ShippingAddress.PhoneNumber,
                        postal_code  = customer.ShippingAddress.ZipPostalCode
                    },

                    #endregion

                    plan = new Plan
                    {
                        id = billingPlan.id
                    }
                }.Create(apiContext);

                //if first payment failed, try again
                if (string.IsNullOrEmpty(subscription.agreement_details.last_payment_date))
                {
                    subscription.BillBalance(apiContext, new AgreementStateDescriptor {
                        amount = subscription.agreement_details.outstanding_balance
                    });
                }

                result.SubscriptionTransactionId = subscription.id;
            }
            catch (PayPal.PayPalException exc)
            {
                if (exc is PayPal.ConnectionException)
                {
                    var error = JsonFormatter.ConvertFromJson <Error>((exc as PayPal.ConnectionException).Response);
                    if (error != null)
                    {
                        result.AddError(string.Format("PayPal error: {0} ({1})", error.message, error.name));
                        if (error.details != null)
                        {
                            error.details.ForEach(x => result.AddError(string.Format("{0} {1}", x.field, x.issue)));
                        }
                    }
                }

                //if there are not the specific errors add exception message
                if (result.Success)
                {
                    result.AddError(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                }
            }

            return(result);
        }
Esempio n. 29
0
        public void TestCleanUp()
        {
            _agreementManager = null;
            _agreement = null;

        }
Esempio n. 30
0
        public ActionResult PropertyAgreement(int id)
        {
            var agreement = new Agreement()
            {
                CustomerName = "דוד אזולאי",
                CustomerAddress = "השקמה 10, פתח תקווה",
                CustomerPhone = "052-5233366",
                CustomerIdNumber = "040022534",
                PercentsRate = 1.5
            };
            var destFile = RenderReport(GetAgentInfo(), agreement);

            return File(destFile, "application/pdf");
        }
Esempio n. 31
0
 public void MarkAsModified(Agreement agreement)
 {
 }
Esempio n. 32
0
 private string GenerateReport(AgentInfo agent, Agreement agreement)
 {
     var destFile = RenderReport(agent, agreement);
     var reportFilePath = string.Format((agreement.IsExclusive ? "Exclusive-" : "") + "Agreement.{0}[{1}].pdf",
                                        DateTime.Now.ToString("dd-MM-yyyy HH-mm"), agreement.UniqueId);
     var outputPath = GetPropertyAgreementsOutputPath();
     reportFilePath = Path.Combine(outputPath, reportFilePath);
     System.IO.File.Copy(destFile, reportFilePath, true);
     return destFile;
 }
 public void AddAgreement(Guid customerId, Agreement agreement)
 {
     throw new NotImplementedException();
 }
Esempio n. 34
0
        private string CreateSignature(Agreement agreement)
        {
            var sigToImage = new SignatureToImage()
                                 {
                                     CanvasWidth = 200,
                                     CanvasHeight = 120
                                 };
            var signatureUrl = "~/Output/Signatures/" + agreement.UniqueId + ".gif";

            CreateSignatureBitmap(agreement, sigToImage, signatureUrl);
            signatureUrl = Url.Content(signatureUrl);
            agreement.Signature = signatureUrl;
            return signatureUrl;
        }
 public void UpdateAgreement(Agreement agreement)
 {
     throw new NotImplementedException();
 }
Esempio n. 36
0
        private static void SendEmail(AgentInfo agent, Agreement agreement, string destFile)
        {
            var mailMessage = new MailMessage();
            mailMessage.From = new MailAddress("*****@*****.**", agent.FullName);
            mailMessage.Sender = new MailAddress("*****@*****.**", "Simple. ReDoc");
            mailMessage.To.Add(new MailAddress(agent.Email, agent.FullName, Encoding.UTF8));
            mailMessage.To.Add(new MailAddress("*****@*****.**", "Simple. ReDoc"));
            if (!string.IsNullOrEmpty(agreement.CustomerEmail))
            {
                try
                {
                    mailMessage.To.Add(new MailAddress(agreement.CustomerEmail, agreement.CustomerName, Encoding.UTF8));
                }
                catch (Exception anyException)
                {
                    SystemMonitor.Error(anyException, "Error creating customer mail address");
                }
            }
            mailMessage.Subject = "הסכם לשירותי תיווך מאת - " + agent.FullName;
            mailMessage.Body = "מצורף בזאת הסכם לשירותי תיווך";
            var attachment = new Attachment(destFile, new ContentType("application/pdf"))
                                 {
                                     Name = "הסכם שירותי תיווך - " + DateTime.Now.ToShortDateString() + ".pdf"
                                 };
            mailMessage.Attachments.Add(attachment);

            var smtpClient = new SmtpClient("smtp.gmail.com", 587);
            smtpClient.Credentials = new NetworkCredential("mysmallfish", "Smallfish00");
            smtpClient.EnableSsl = true;

            smtpClient.Send(mailMessage);
        }
Esempio n. 37
0
 public static DateTime?TrueStartDate(this Agreement agreement)
 {
     return(agreement.AgreementMods.FirstOrDefault(p => p.Number == 0).StartDate);
 }
        private AgreementItem CreateAgreementItemFromOldInterest(Agreement agreement, DateTime today, AmortizationItemsModel item, AgreementItem oldItem)
        {
            AgreementItem agreementItemNew1 = new AgreementItem();
            agreementItemNew1.Agreement = agreement;
            agreementItemNew1.InterestComputationMode = oldItem.InterestComputationMode;
            agreementItemNew1.InterestRateDescription = oldItem.InterestRateDescription;
            agreementItemNew1.InterestRate = item.NewInterestRate;
            agreementItemNew1.LoanAmount = oldItem.LoanAmount;
            agreementItemNew1.LoanTermLength = oldItem.LoanTermLength;
            agreementItemNew1.LoanTermUom = oldItem.LoanTermUom;
            agreementItemNew1.MethodOfChargingInterest = oldItem.MethodOfChargingInterest;
            agreementItemNew1.PaymentMode = oldItem.PaymentMode;
            agreementItemNew1.TransitionDateTime = today;
            agreementItemNew1.IsActive = true;

            return agreementItemNew1;
        }
Esempio n. 39
0
        /// <summary>
        /// Holds dictionary of records.
        /// Keys = "recorded", "allocatedSite", "allocatedStudies", "difference"
        /// </summary>
        /// <param name="agreement"></param>
        /// <returns></returns>
        public static Dictionary <string, Dictionary <int, FundingAmounts> > FundingSummary(this Agreement agreement)
        {
            #region Define Dictionaries
            //Holds all the records Dictionaries Key= "recorded", "allocated", "difference"
            var recordsDictionary = new Dictionary <string, Dictionary <int, FundingAmounts> >();
            //Holds the recorded funds from each agreement mod
            var recordedFunds = new Dictionary <int, FundingAmounts>();
            //Holds the allocated funds for each agreement mod
            var allocatedSiteFunds = new Dictionary <int, FundingAmounts>();
            //Holds the allocated Studies funding
            var allocatedStudiesFunds = new Dictionary <int, FundingAmounts>();
            //Holds the Differences for each mod
            var difference = new Dictionary <int, FundingAmounts>();
            #endregion

            #region Add Recorded and Allocated Funding
            //Goes through and adds the mod number and its associated funding amounts
            foreach (var mod in agreement.AgreementMods)
            {
                //Add the recorded funding to the mod
                recordedFunds.Add(mod.Number, new FundingAmounts()
                {
                    USGS = mod.FundingUSGSCMF == null ? 0 : Convert.ToDouble(mod.FundingUSGSCMF), Customer = mod.FundingCustomer == null ? 0 : Convert.ToDouble(mod.FundingCustomer), Other = mod.FundingOther == null ? 0 : Convert.ToDouble(mod.FundingOther)
                });
                //Add a Site Funding for the mod
                allocatedSiteFunds.Add(mod.Number, new FundingAmounts()
                {
                    Customer = 0, Other = 0, USGS = 0
                });
                //Add a Studies Funding for the mod
                allocatedStudiesFunds.Add(mod.Number, new FundingAmounts()
                {
                    Customer = 0, Other = 0, USGS = 0
                });
                //Add a difference for the mod
                difference.Add(mod.Number, new FundingAmounts()
                {
                    Customer = 0, Other = 0, USGS = 0
                });
                //Add all of the site Funding to the allocated site funding list
                foreach (var sf in mod.FundingSites)
                {
                    //Grab a copy of the dictionary FundingAmounts Object
                    var funding = allocatedSiteFunds[mod.Number];
                    //Set values
                    funding.Customer += Convert.ToDouble(sf.FundingCustomer);
                    funding.USGS     += Convert.ToDouble(sf.FundingUSGSCMF);
                    funding.Other    += Convert.ToDouble(sf.FundingOther);
                    //Set the FundingAmounts in the dictionary equal to the one you altered.
                    allocatedSiteFunds[mod.Number] = funding;
                }
                foreach (var sf in mod.FundingStudies)
                {
                    //Grab a copy of the dictionary FundingAmounts Object
                    var funding = allocatedStudiesFunds[mod.Number];
                    //Set values
                    funding.Customer += Convert.ToDouble(sf.FundingCustomer);
                    funding.USGS     += Convert.ToDouble(sf.FundingUSGSCMF);
                    funding.Other    += Convert.ToDouble(sf.FundingOther);
                    //Set the FundingAmounts in the dictionary equal to the one you altered.
                    allocatedStudiesFunds[mod.Number] = funding;
                }
            }
            #endregion

            #region Calculate Difference
            foreach (var recordedFund in recordedFunds)
            {
                var recorded         = recordedFund.Value;
                var siteAllocated    = allocatedSiteFunds[recordedFund.Key];
                var studiesAllocated = allocatedStudiesFunds[recordedFund.Key];
                var diff             = difference[recordedFund.Key];

                diff.USGS     = recorded.USGS - siteAllocated.USGS - studiesAllocated.USGS;
                diff.Customer = recorded.Customer - siteAllocated.Customer - studiesAllocated.Customer;
                diff.Other    = recorded.Other - siteAllocated.Other - studiesAllocated.Other;

                difference[recordedFund.Key] = diff;
            }
            #endregion

            #region Add Dictionaries to the recordsDictionary
            recordsDictionary.Add("recorded", recordedFunds);
            recordsDictionary.Add("allocatedSite", allocatedSiteFunds);
            recordsDictionary.Add("allocatedStudies", allocatedStudiesFunds);
            recordsDictionary.Add("difference", difference);
            #endregion
            return(recordsDictionary);
        }
        private FinancialAccount CreateFinancialAccount(Agreement agreement, DateTime today)
        {
            FinancialAccount financialAccountNew1 = new FinancialAccount();
            financialAccountNew1.Agreement = agreement;
            financialAccountNew1.FinancialAccountType = FinancialAccountType.LoanAccountType;

            return financialAccountNew1;
        }
Esempio n. 41
0
        /// <summary>
        ///
        /// </summary>
        private void CreateBillingAgreement(APIContext apiContext)
        {
            // Before we can setup the billing agreement, we must first create a
            // billing plan that includes a redirect URL back to this test server.
            var plan = BillingPlanCreate.CreatePlanObject(HttpContext.Current);
            var guid = Convert.ToString((new Random()).Next(100000));

            plan.merchant_preferences.return_url = Request.Url.ToString() + "?guid=" + guid;

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Create new billing plan", plan);
            #endregion

            var createdPlan = plan.Create(apiContext);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordResponse(createdPlan);
            #endregion

            // Activate the plan
            var patchRequest = new PatchRequest()
            {
                new Patch()
                {
                    op    = "replace",
                    path  = "/",
                    value = new Plan()
                    {
                        state = "ACTIVE"
                    }
                }
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Update the plan", patchRequest);
            #endregion

            createdPlan.Update(apiContext, patchRequest);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordActionSuccess("Plan updated successfully");
            #endregion

            // With the plan created and activated, we can now create the billing agreement.
            var payer = new Payer()
            {
                payment_method = "paypal"
            };
            var shippingAddress = new ShippingAddress()
            {
                line1        = "111 First Street",
                city         = "Saratoga",
                state        = "CA",
                postal_code  = "95070",
                country_code = "US"
            };

            var agreement = new Agreement()
            {
                name        = "T-Shirt of the Month Club",
                description = "Agreement for T-Shirt of the Month Club",
                start_date  = "2015-02-19T00:37:04Z",
                payer       = payer,
                plan        = new Plan()
                {
                    id = createdPlan.id
                },
                shipping_address = shippingAddress
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Create billing agreement", agreement);
            #endregion

            // Create the billing agreement.
            var createdAgreement = agreement.Create(apiContext);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordResponse(createdAgreement);
            #endregion

            // Get the redirect URL to allow the user to be redirected to PayPal to accept the agreement.
            var links = createdAgreement.links.GetEnumerator();

            while (links.MoveNext())
            {
                var link = links.Current;
                if (link.rel.ToLower().Trim().Equals("approval_url"))
                {
                    this.flow.RecordRedirectUrl("Redirect to PayPal to approve billing agreement...", link.href);
                }
            }
            Session.Add("flow-" + guid, this.flow);
            Session.Add(guid, createdAgreement.token);
        }
        private LoanDisbursementVcr CreateLoanDisbursementVoucher(Agreement agreement, AmortizationItemsModel itemModel, DateTime today, decimal amountBalance)
        {
            LoanDisbursementVcr voucher = new LoanDisbursementVcr();
            voucher.Agreement = agreement;
            voucher.Amount = itemModel.NewLoanAmount;
            voucher.Date = today;
            voucher.Balance = amountBalance;

            Context.LoanDisbursementVcrs.AddObject(voucher);
            return voucher;
        }
        public static AgreementRole CreateAgreementRole(Agreement agreement, PartyRole partyRole)
        {
            AgreementRole agreeRole = new AgreementRole();
            agreeRole.Agreement = agreement;
            agreeRole.PartyRole = partyRole;

            return agreeRole;
        }
        private Agreement CreateNewAgreementWithParent(Application application, DateTime today, FinancialAccount financialAccount)
        {
            Agreement agreement = new Agreement();
            agreement.Application = application;
            agreement.AgreementType = AgreementType.LoanAgreementType;
            agreement.EffectiveDate = today;
            agreement.AgreementDate = today;
            agreement.ParentAgreementId = financialAccount.AgreementId;

            return agreement;
        }
Esempio n. 45
0
 public override void PrintSectionTytul(Agreement agreement)
 {
     Console.WriteLine("UMOWA O PRACĘ");
 }
        protected override void RunSample()
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate
            // the call and to send a unique request id
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly.
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

            // For demonstration purposes, we'll first setup a billing plan in
            // an active state to be used to make an agreement with.
            var plan = BillingPlanCreate.CreatePlanObject(HttpContext.Current);
            var guid = Convert.ToString((new Random()).Next(100000));

            plan.merchant_preferences.return_url = Request.Url.ToString() + "?guid=" + guid;
            plan.merchant_preferences.cancel_url = Request.Url.ToString();

            // > Note: Both `return_url` and `cancel_url` are being set in
            // `plan.merchant_preferences` since many plans may be setup well
            // in advance of anyone setting up an agreement for it.  These URLs
            // are only used for agreements setup with `payer.payment_method`
            // set to `paypal` to establish where the customer should be redirected
            // once they approve or cancel the agreement using their PayPal account.

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Create new billing plan", plan);
            #endregion

            var createdPlan = plan.Create(apiContext);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordResponse(createdPlan);
            #endregion

            // Activate the plan
            var patchRequest = new PatchRequest()
            {
                new Patch()
                {
                    op    = "replace",
                    path  = "/",
                    value = new Plan()
                    {
                        state = "ACTIVE"
                    }
                }
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Update the plan", patchRequest);
            #endregion

            createdPlan.Update(apiContext, patchRequest);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordActionSuccess("Plan updated successfully");
            #endregion

            // With the plan created and activated, we can now create the billing agreement.
            // A resource representing a Payer that funds a payment.
            var payer = new Payer
            {
                payment_method      = "credit_card",
                funding_instruments = new List <FundingInstrument>
                {
                    new FundingInstrument
                    {
                        credit_card = new CreditCard
                        {
                            billing_address = new Address
                            {
                                city         = "Johnstown",
                                country_code = "US",
                                line1        = "52 N Main ST",
                                postal_code  = "43210",
                                state        = "OH"
                            },
                            cvv2         = "874",
                            expire_month = 11,
                            expire_year  = 2018,
                            first_name   = "Joe",
                            last_name    = "Shopper",
                            number       = "4877274905927862",
                            type         = "visa"
                        }
                    }
                }
            };

            var shippingAddress = new ShippingAddress()
            {
                line1        = "111 First Street",
                city         = "Saratoga",
                state        = "CA",
                postal_code  = "95070",
                country_code = "US"
            };

            var agreement = new Agreement()
            {
                name        = "T-Shirt of the Month Club",
                description = "Agreement for T-Shirt of the Month Club",
                start_date  = "2015-02-19T00:37:04Z",
                payer       = payer,
                plan        = new Plan()
                {
                    id = createdPlan.id
                },
                shipping_address = shippingAddress
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Create billing agreement", agreement);
            #endregion

            // Create the billing agreement.
            var createdAgreement = agreement.Create(apiContext);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordResponse(createdAgreement);
            #endregion

            // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
        }
        public IActionResult WebhookEventsHandler()
        {
            var storeScope = GetActiveStoreScopeConfiguration(_storeService, _workContext);
            var payPalDirectPaymentSettings = _settingService.LoadSetting <PayPalDirectPaymentSettings>(storeScope);

            try
            {
                var requestBody = string.Empty;
                using (var stream = new StreamReader(this.Request.Body, Encoding.UTF8))
                {
                    requestBody = stream.ReadToEnd();
                }
                var apiContext = PaypalHelper.GetApiContext(payPalDirectPaymentSettings);

                //validate request
                var headers = new NameValueCollection();
                this.Request.Headers.ToList().ForEach(header => headers.Add(header.Key, header.Value));
                if (!WebhookEvent.ValidateReceivedEvent(apiContext, headers, requestBody, payPalDirectPaymentSettings.WebhookId))
                {
                    _logger.Error("PayPal error: webhook event was not validated");
                    return(Ok());
                }

                var webhook = JsonFormatter.ConvertFromJson <WebhookEvent>(requestBody);

                if (webhook.resource_type.ToLowerInvariant().Equals("sale"))
                {
                    var sale = JsonFormatter.ConvertFromJson <Sale>(webhook.resource.ToString());

                    //recurring payment
                    if (!string.IsNullOrEmpty(sale.billing_agreement_id))
                    {
                        //get agreement
                        var agreement    = Agreement.Get(apiContext, sale.billing_agreement_id);
                        var initialOrder = _orderService.GetOrderByGuid(new Guid(agreement.description));
                        if (initialOrder != null)
                        {
                            var recurringPayment = _orderService.SearchRecurringPayments(initialOrderId: initialOrder.Id).FirstOrDefault();
                            if (recurringPayment != null)
                            {
                                if (sale.state.ToLowerInvariant().Equals("completed"))
                                {
                                    if (recurringPayment.RecurringPaymentHistory.Count == 0)
                                    {
                                        //first payment
                                        initialOrder.PaymentStatus        = PaymentStatus.Paid;
                                        initialOrder.CaptureTransactionId = sale.id;
                                        _orderService.UpdateOrder(initialOrder);

                                        recurringPayment.RecurringPaymentHistory.Add(new RecurringPaymentHistory
                                        {
                                            RecurringPaymentId = recurringPayment.Id,
                                            OrderId            = initialOrder.Id,
                                            CreatedOnUtc       = DateTime.UtcNow
                                        });
                                        _orderService.UpdateRecurringPayment(recurringPayment);
                                    }
                                    else
                                    {
                                        //next payments
                                        var orders = _orderService.GetOrdersByIds(recurringPayment.RecurringPaymentHistory.Select(order => order.OrderId).ToArray());
                                        if (!orders.Any(order => !string.IsNullOrEmpty(order.CaptureTransactionId) &&
                                                        order.CaptureTransactionId.Equals(sale.id, StringComparison.InvariantCultureIgnoreCase)))
                                        {
                                            var processPaymentResult = new ProcessPaymentResult
                                            {
                                                NewPaymentStatus     = PaymentStatus.Paid,
                                                CaptureTransactionId = sale.id,
                                                AvsResult            = sale.processor_response?.avs_code ?? string.Empty,
                                                Cvv2Result           = sale.processor_response?.cvv_code ?? string.Empty
                                            };
                                            _orderProcessingService.ProcessNextRecurringPayment(recurringPayment, processPaymentResult);
                                        }
                                    }
                                }
                                else if (sale.state.ToLowerInvariant().Equals("denied"))
                                {
                                    //payment denied
                                    _orderProcessingService.ProcessNextRecurringPayment(recurringPayment,
                                                                                        new ProcessPaymentResult {
                                        Errors = new[] { webhook.summary }, RecurringPaymentFailed = true
                                    });
                                }
                                else
                                {
                                    _logger.Error(
                                        $"PayPal error: Sale is {sale.state} for the order #{initialOrder.Id}");
                                }
                            }
                        }
                    }
                    else
                    //standard payment
                    {
                        var order = _orderService.GetOrderByGuid(new Guid(sale.invoice_number));
                        if (order != null)
                        {
                            if (sale.state.ToLowerInvariant().Equals("completed"))
                            {
                                if (_orderProcessingService.CanMarkOrderAsPaid(order))
                                {
                                    order.CaptureTransactionId     = sale.id;
                                    order.CaptureTransactionResult = sale.state;
                                    _orderService.UpdateOrder(order);
                                    _orderProcessingService.MarkOrderAsPaid(order);
                                }
                            }
                            if (sale.state.ToLowerInvariant().Equals("denied"))
                            {
                                var reason =
                                    $"Payment is denied. {(sale.fmf_details != null ? $"Based on fraud filter: {sale.fmf_details.name}. {sale.fmf_details.description}" : string.Empty)}";
                                order.OrderNotes.Add(new OrderNote
                                {
                                    Note = reason,
                                    DisplayToCustomer = false,
                                    CreatedOnUtc      = DateTime.UtcNow
                                });
                                _logger.Error($"PayPal error: {reason}");
                            }
                        }
                        else
                        {
                            _logger.Error($"PayPal error: Order with GUID {sale.invoice_number} was not found");
                        }
                    }
                }

                return(Ok());
            }
            catch (PayPal.PayPalException exc)
            {
                if (exc is PayPal.ConnectionException)
                {
                    var error = JsonFormatter.ConvertFromJson <Error>((exc as PayPal.ConnectionException).Response);
                    if (error != null)
                    {
                        _logger.Error($"PayPal error: {error.message} ({error.name})");
                        if (error.details != null)
                        {
                            error.details.ForEach(x => _logger.Error($"{x.field} {x.issue}"));
                        }
                    }
                    else
                    {
                        _logger.Error(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                    }
                }
                else
                {
                    _logger.Error(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                }

                return(Ok());
            }
        }
        public static AgreementItem Create(LoanApplication loanApplication, Agreement agreement)
        {
            AgreementItem agreementItem = new AgreementItem();
            agreementItem.Agreement = agreement;
            agreementItem.LoanAmount = loanApplication.LoanAmount;

            if (loanApplication.IsInterestProductFeatureInd)
            {
                agreementItem.InterestRate = loanApplication.InterestRate ?? 0;
                agreementItem.InterestRateDescription = loanApplication.InterestRateDescription;
            }

            if (loanApplication.IsPastDueProductFeatureInd)
            {
                agreementItem.PastDueInterestRateDescript = loanApplication.PastDueInterestDescription;
                agreementItem.PastDueInterestRate = loanApplication.PastDueInterestRate;
            }

            //descriptive values
            var uom = Context.UnitOfMeasures.SingleOrDefault(entity =>
                entity.Id == loanApplication.LoanTermUomId);
            var payment = Context.LoanApplications.FirstOrDefault(entity =>
                entity.UnitOfMeasure.Id == loanApplication.PaymentModeUomId);
            var featureAppMode = ProductFeatureApplicability.RetrieveFeature(ProductFeatureCategory.InterestComputationModeType, loanApplication);
            var fetaureAppMethod = ProductFeatureApplicability.RetrieveFeature(ProductFeatureCategory.MethodofChargingInterestType, loanApplication);

            agreementItem.LoanTermLength = loanApplication.LoanTermLength;
            agreementItem.LoanTermUom = uom.Name;
            agreementItem.PaymentMode = payment.UnitOfMeasure.Name;
            agreementItem.InterestComputationMode = featureAppMode.ProductFeature.Name;
            agreementItem.MethodOfChargingInterest = fetaureAppMethod.ProductFeature.Name;

            return agreementItem;
        }
Esempio n. 49
0
 public async Task AddAgreement(Agreement agreement)
 {
     await _UnitOfWork.AgreementRepository.Insert(agreement);
 }
        private static void CreateAgreementForGuarantor(LoanApplication loanApplication, Agreement agreement, DateTime today)
        {
            var applicationGuarantor = RoleType.GuarantorApplicationType;
            var roles = Context.LoanApplicationRoles.Where(entity => entity.ApplicationId == loanApplication.ApplicationId && entity.PartyRole.RoleTypeId == applicationGuarantor.Id
                 && entity.PartyRole.EndDate == null);

            var agreementGuarantor = RoleType.GuarantorAgreementType;
            foreach (var role in roles)
            {
                PartyRole partyRole = role.PartyRole;
                var newpartyRole = PartyRole.Create(agreementGuarantor, partyRole.Party, today);
                Context.PartyRoles.AddObject(newpartyRole);

                var agreementRole = CreateAgreementRole(agreement, newpartyRole);
                Context.AgreementRoles.AddObject(agreementRole);
            }
        }
Esempio n. 51
0
        public SupplyResponse Post([FromBody] AgreementWrapper agreement)
        {
            var currentUser = HttpContext.User;
            var dbUser      =
                _dbContext.User.Include(p => p.RestaurantManager).ThenInclude(p => p.Restaurant)
                .SingleOrDefault(p => currentUser.FindFirst(ClaimTypes.Name).Value.Equals(p.UserName));

            if (dbUser == null)
            {
                return(SupplyResponse.Fail("Unauthorize", "Your are not the user in the system."));
            }

            if (agreement.Details == null ||
                agreement.Items == null || agreement.SupplierId == 0)
            {
                return(SupplyResponse.RequiredFieldEmpty());
            }

            if (agreement.StartDate > agreement.ExpiryDate)
            {
                return(SupplyResponse.BadRequest("Start date cannot be later than Expiry Date"));
            }


            //BPA
            if (agreement.AgreementType == AgreementType.Blanket)
            {
                //Get data from request
                ICollection <QuantityItems>     items = new List <QuantityItems>();
                BlanketPurchaseAgreementDetails details;
                try
                {
                    foreach (var item in agreement.Items)
                    {
                        items.Add(item.ToObject <QuantityItems>());
                    }

                    if (!items.Any())
                    {
                        return(SupplyResponse.BadRequest("Agreement Line is Empty"));
                    }

                    details = agreement.Details.ToObject <BlanketPurchaseAgreementDetails>();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    return(SupplyResponse.BadRequest("Request Format Fail"));
                }


                //Verfiy&Process request object
                var dbLine = new Dictionary <string, BlanketPurchaseAgreementLine>();

                foreach (var item in items)
                {
                    if (item.MinimumQuantity <= 0 && item.PromisedQuantity <= 0)
                    {
                        return(SupplyResponse.BadRequest($"Item {item.SupplierItemId} has a zero or negative quantity"));
                    }

                    var dbItem = _dbContext.Item.SingleOrDefault(p => item.SupplierItemId == p.SupplierItemId);
                    if (dbItem == null)
                    {
                        return(SupplyResponse.NotFound("supplier item", item.SupplierItemId));
                    }

                    if (dbLine.ContainsKey(item.SupplierItemId))
                    {
                        return(SupplyResponse.DuplicateEntry("Request Item", item.SupplierItemId));
                    }

                    dbLine[item.SupplierItemId] = new BlanketPurchaseAgreementLine
                    {
                        ItemId           = dbItem.Id,
                        MinimumQuantity  = item.MinimumQuantity,
                        PromisedQuantity = item.PromisedQuantity,
                        Price            = item.Price,
                        Unit             = item.Unit,
                    };
                }

                //Create Agreement Object

                var dbAgreement = new Agreement
                {
                    AgreementType     = AgreementType.Blanket,
                    Currency          = agreement.Currency,
                    StartDate         = agreement.StartDate,
                    ExpiryDate        = agreement.ExpiryDate,
                    SupplierId        = agreement.SupplierId,
                    CreateBy          = dbUser.UserId,
                    TermsAndCondition = agreement.TermsAndCondition
                };
                _dbContext.Agreement.Add(dbAgreement);
                _dbContext.SaveChanges();
                var agreementId = dbAgreement.AgreementId;
                _dbContext.Entry(dbAgreement).State = EntityState.Detached;

                details.AgreementId = agreementId;
                _dbContext.BlanketPurchaseAgreementDetails.Add(details);
                _dbContext.SaveChanges();

                foreach (var line in dbLine.Values)
                {
                    line.AgreementId = agreementId;
                    var entry = _dbContext.BlanketPurchaseAgreementLine.Add(line);
                    _dbContext.SaveChanges();
                    entry.State = EntityState.Detached;
                }

                return(Get(agreementId));
            }


            //CPA
            if (agreement.AgreementType == AgreementType.Contract)
            {
                ICollection <QuantityItems>      items = new List <QuantityItems>();
                ContractPurchaseAgreementDetails details;
                try
                {
                    foreach (var item in agreement.Items)
                    {
                        items.Add(item.ToObject <QuantityItems>());
                    }

                    if (!items.Any())
                    {
                        return(SupplyResponse.BadRequest("Agreement Line is Empty"));
                    }

                    details = agreement.Details.ToObject <ContractPurchaseAgreementDetails>();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    return(SupplyResponse.BadRequest("Request Format Fail"));
                }

                var dbLine = new List <ContractPurchaseAgreementLine>();

                foreach (var item in items)
                {
                    var dbItem = _dbContext.Item.SingleOrDefault(p => item.SupplierItemId == p.SupplierItemId);
                    if (dbItem == null)
                    {
                        return(SupplyResponse.NotFound("supplier item", item.SupplierItemId));
                    }

                    dbLine.Add(new ContractPurchaseAgreementLine()
                    {
                        ItemId = dbItem.Id,
                    });
                }

                var dbAgreement = new Agreement
                {
                    AgreementType     = AgreementType.Contract,
                    Currency          = agreement.Currency,
                    StartDate         = agreement.StartDate,
                    ExpiryDate        = agreement.ExpiryDate,
                    SupplierId        = agreement.SupplierId,
                    CreateBy          = dbUser.UserId,
                    TermsAndCondition = agreement.TermsAndCondition
                };

                _dbContext.Agreement.Add(dbAgreement);
                _dbContext.SaveChanges();
                var agreementId = dbAgreement.AgreementId;
                _dbContext.Entry(dbAgreement).State = EntityState.Detached;

                details.AgreementId = agreementId;
                _dbContext.ContractPurchaseAgreementDetails.Add(details);
                _dbContext.SaveChanges();

                foreach (var line in dbLine)
                {
                    line.AgreementId = agreementId;
                    var entry = _dbContext.ContractPurchaseAgreementLine.Add(line);
                    _dbContext.SaveChanges();
                    entry.State = EntityState.Detached;
                }

                return(Get(agreementId));
            }



            //PPA
            if (agreement.AgreementType == AgreementType.Planned)
            {
                ICollection <QuantityItems>     items = new List <QuantityItems>();
                PlannedPurchaseAgreementDetails details;
                try
                {
                    foreach (var item in agreement.Items)
                    {
                        items.Add(item.ToObject <QuantityItems>());
                    }

                    if (!items.Any())
                    {
                        return(SupplyResponse.BadRequest("Agreement Line is Empty"));
                    }

                    details = agreement.Details.ToObject <PlannedPurchaseAgreementDetails>();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    return(SupplyResponse.BadRequest("Request Format Fail"));
                }

                var dbLine = new Dictionary <string, PlannedPurchaseAgreementLine>();

                foreach (var item in items)
                {
                    if (item.Quantity <= 0)
                    {
                        return(SupplyResponse.BadRequest($"Item {item.SupplierItemId} has a zero or negative quantity"));
                    }

                    var dbItem = _dbContext.Item.SingleOrDefault(p => item.SupplierItemId == p.SupplierItemId);
                    if (dbItem == null)
                    {
                        return(SupplyResponse.NotFound("supplier item", item.SupplierItemId));
                    }

                    if (dbLine.ContainsKey(item.SupplierItemId))
                    {
                        return(SupplyResponse.DuplicateEntry("Request Item", item.SupplierItemId));
                    }

                    dbLine[item.SupplierItemId] = new PlannedPurchaseAgreementLine
                    {
                        ItemId   = dbItem.Id,
                        Quantity = item.Quantity,
                        Price    = item.Price,
                        Unit     = item.Unit
                    };
                }

                var dbAgreement = new Agreement
                {
                    AgreementType     = AgreementType.Planned,
                    Currency          = agreement.Currency,
                    StartDate         = agreement.StartDate,
                    ExpiryDate        = agreement.ExpiryDate,
                    SupplierId        = agreement.SupplierId,
                    CreateBy          = dbUser.UserId,
                    TermsAndCondition = agreement.TermsAndCondition
                };
                _dbContext.Agreement.Add(dbAgreement);
                _dbContext.SaveChanges();
                var agreementId = dbAgreement.AgreementId;
                _dbContext.Entry(dbAgreement).State = EntityState.Detached;

                details.AgreementId = agreementId;
                _dbContext.PlannedPurchaseAgreementDetails.Add(details);
                _dbContext.SaveChanges();

                foreach (var line in dbLine.Values)
                {
                    line.AgreementId = agreementId;
                    var entry = _dbContext.PlannedPurchaseAgreementLine.Add(line);
                    _dbContext.SaveChanges();
                    entry.State = EntityState.Detached;
                }

                return(Get(agreementId));
            }

            return(SupplyResponse.NotFound("Agreement Type", agreement.AgreementType + ""));
        }