public IHttpActionResult PutCreditTransaction(int id, CreditTransaction creditTransaction) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != creditTransaction.CreditTransactionID) { return(BadRequest()); } db.Entry(creditTransaction).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CreditTransactionExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public ActionResult DeleteConfirmed(int id) { CreditTransaction creditTransaction = db.CreditTransactions.Find(id); db.CreditTransactions.Remove(creditTransaction); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult Edit([Bind(Include = "CreditTransactionID,Company,CreditIssued,Amount,DueDate,Paid")] CreditTransaction creditTransaction) { if (ModelState.IsValid) { db.Entry(creditTransaction).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(creditTransaction)); }
public ActionResult Create([Bind(Include = "CreditTransactionID,Company,CreditIssued,Amount,DueDate,Paid")] CreditTransaction creditTransaction) { if (ModelState.IsValid) { db.CreditTransactions.Add(creditTransaction); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(creditTransaction)); }
private async Task CreateCreditTransfer(TransferCommand request, Account sourceAccount, Account destinationAccount) { CreditTransaction creditTransaction = new CreditTransaction(TransactionType.Transfer) { AccountId = destinationAccount.Id, OriginAccountId = sourceAccount.Id, Amount = request.Amount }; destinationAccount.Balance += request.Amount; destinationAccount.AddTransaction(creditTransaction); await _accountRepository.Update(destinationAccount); }
public IHttpActionResult GetCreditTransaction(int id) { CreditTransaction creditTransaction = db.CreditTransactions.Find(id); if (creditTransaction == null) { return(NotFound()); } return(Ok(creditTransaction)); }
public IHttpActionResult PostCreditTransaction(CreditTransaction creditTransaction) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.CreditTransactions.Add(creditTransaction); db.SaveChanges(); return(CreatedAtRoute("DefaultApi", new { id = creditTransaction.CreditTransactionID }, creditTransaction)); }
public void UpdateCreditTransactions() { foreach (var transaction in _creditTransactions) { transaction.Do(); CreditTransaction aux = (CreditTransaction)transaction; if (aux.CreditPayed) { _creditTransactions.Remove(transaction); } ContextWindow.UpdateDatabaseFile(); } }
// GET: CreditTransactions1/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } CreditTransaction creditTransaction = db.CreditTransactions.Find(id); if (creditTransaction == null) { return(HttpNotFound()); } return(View(creditTransaction)); }
/// <summary> /// Credits (Refunds) the specified transaction. /// </summary> /// <param name="origTransaction">The original transaction.</param> /// <param name="amount">The amount.</param> /// <param name="comment">The comment.</param> /// <param name="errorMessage">The error message.</param> /// <returns></returns> public override FinancialTransaction Credit(FinancialTransaction origTransaction, decimal amount, string comment, out string errorMessage) { errorMessage = string.Empty; Response ppResponse = null; if (origTransaction != null && !string.IsNullOrWhiteSpace(origTransaction.TransactionCode) && origTransaction.FinancialGateway != null) { var ppInvoice = new Invoice(); ppInvoice.Amt = new Currency(amount); ppInvoice.Comment1 = comment; var ppTransaction = new CreditTransaction(origTransaction.TransactionCode, GetUserInfo(origTransaction.FinancialGateway), GetConnection(origTransaction.FinancialGateway), ppInvoice, PayflowUtility.RequestId); ppResponse = ppTransaction.SubmitTransaction(); if (ppResponse != null) { TransactionResponse txnResponse = ppResponse.TransactionResponse; if (txnResponse != null) { if (txnResponse.Result == 0) // Success { var transaction = new FinancialTransaction(); transaction.TransactionCode = txnResponse.Pnref; return(transaction); } else { errorMessage = string.Format("[{0}] {1}", txnResponse.Result, txnResponse.RespMsg); } } else { errorMessage = "Invalid transaction response from the financial gateway"; } } else { errorMessage = "Invalid response from the financial gateway."; } } else { errorMessage = "Invalid original transaction, transaction code, or gateway."; } return(null); }
public IHttpActionResult DeleteCreditTransaction(int id) { CreditTransaction creditTransaction = db.CreditTransactions.Find(id); if (creditTransaction == null) { return(NotFound()); } db.CreditTransactions.Remove(creditTransaction); db.SaveChanges(); return(Ok(creditTransaction)); }
/// <summary> /// Create a CreditTransaction from a StripCharge and Order. /// </summary> /// <param name="stripeCharge"></param> /// <param name="order"></param> public void CreateCreditTransactionFromStripeCharge(StripeCharge stripeCharge, Order order) { var creditTransaction = new CreditTransaction() { StripeChargeId = stripeCharge.Id, Created = stripeCharge.Created, AmountInCents = stripeCharge.Amount, Paid = stripeCharge.Paid, Order = order, OrderId = order.OrderId }; _appDbContext.CreditTransactions.Add(creditTransaction); _appDbContext.SaveChanges(); order.CreditTransactionId = creditTransaction.CreditTransactionId; _appDbContext.Update <Order>(order); _appDbContext.SaveChanges(); }
public bool AddMoCreditsTransaction(long to, long fromid, double amount, TransferType type, long?linkedId) { var matchingPaymentType = _paymentTypesService.GetPaymentType(type); if (matchingPaymentType != null) { var creditTransaction = new CreditTransaction() { AdminNotes = string.Empty, Amount = amount, FromUserId = fromid, LinkedId = linkedId, Notes = string.Empty, Timestamp = DateTime.Now, ToUserId = to, PaymentTypeId = matchingPaymentType.Id }; _creditTransactionRepository.Add(creditTransaction); return(Convert.ToBoolean(_creditTransactionRepository.Save())); } return(false); }
public void SaveDocument(CreditTransactionDocument document) { try { CheckAddRight(); var creditTransaction = TinyMapper.Map <CreditTransaction>(document); if (creditTransaction.Id == 0) { creditTransaction.UserId = User.Id; } else { CreditTransaction dbTransaction = null; if (creditTransaction.Id != 0) { dbTransaction = Context.CreditTransactions.Get(creditTransaction.Id, x => x.DkpDocument, x => x.AgentDocument); } UserFileCheck.AddOrUpdate(Context, creditTransaction, creditTransaction.DkpDocument, dbTransaction?.DkpDocument); UserFileCheck.AddOrUpdate(Context, creditTransaction, creditTransaction.AgentDocument, dbTransaction?.AgentDocument); } Context.CreditTransactions.AddOrUpdate(creditTransaction); Context.SaveChanges(); document.Id = creditTransaction.Id; //document.Number = Context.CreditTransactions.Get(creditTransaction.Id).Number; } catch (AccessDeniedException) { throw; } catch (Exception ex) { Logger.Instance.Log(ex); throw new Exception("Неудалось сохранить документ"); } }
private static ISubledgerTransaction BuildSubledgerTransaction(TransactionType type, TransactionStatus status, decimal amount) { ISubledgerTransaction subledgerTransaction = null; if (type == TransactionType.Invoice) { subledgerTransaction = new InvoiceTransaction(status, amount); } else if (type == TransactionType.Credit) { subledgerTransaction = new CreditTransaction(amount); } else if (type == TransactionType.JournalAr || type == TransactionType.JournalNar) { subledgerTransaction = new JournalTransaction(amount); } else if (type == TransactionType.Receipt) { subledgerTransaction = new ReceiptTransaction(amount); } else if (type == TransactionType.Overpayment) { subledgerTransaction = new OverpaymentTransaction(amount); } else if (type == TransactionType.CreditBalanceTransferCredit || type == TransactionType.CreditBalanceTransferDebit || type == TransactionType.Allocation) { subledgerTransaction = new CreditBalanceTransferTransaction(amount); } else if (type == TransactionType.Discount) { subledgerTransaction = new DiscountTransaction(amount); } else if (type == TransactionType.Repurchase) { subledgerTransaction = new RepurchaseTransaction(amount); } return(subledgerTransaction); }
public async Task AddTransaction(Guid walletId, ETransactionType transactionType, Amount amount, string description) { var wallet = await walletReadOnlyRepository.GetWallet(walletId); if (wallet == null) { return; } Transaction transaction = null; if (transactionType == ETransactionType.Credit) { transaction = new CreditTransaction(amount, description, DateTime.Now); } else if (transactionType == ETransactionType.Debit) { transaction = new DebitTransaction(amount, description, DateTime.Now); } wallet.AddTransaction(transaction); await Save(wallet); }
public override void ProcessTransaction(Transaction t) { bool result = false; //'Get Configuration Settings string MerchantPartner = Settings.MerchantPartner; string MerchantLogin = Settings.MerchantLogin; string MerchantUser = Settings.MerchantUser; string MerchantPassword = Settings.MerchantPassword; string CurrencyCode = Settings.CurrencyCode; bool TestMode = Settings.TestMode; bool DebugMode = Settings.DeveloperMode; UserInfo User = new UserInfo(MerchantUser, MerchantLogin, MerchantPartner, MerchantPassword); //Set HostAddress URL string HostAddress = LiveUrl; if (TestMode) { HostAddress = TestUrl; } //Connection Info PayflowConnectionData Connection = new PayflowConnectionData(HostAddress, 443, 45); //', CertLocation) // *** Create a new Invoice data object *** // Set Invoice object with the Amount, Billing & Shipping Address, etc. *** Invoice Inv = new Invoice(); // Set the amount object. A valid amount is a two decimal value. An invalid amount will generate a result code Currency Amt = new Currency(Decimal.Round(t.Amount, 2), CurrencyCode); //' 840 is US ISO currency code. If no code passed, 840 is default. Inv.Amt = Amt; // Generate a unique transaction ID string strRequestID = PayflowUtility.RequestId + t.MerchantInvoiceNumber; //InvNum and CustRef are sent to the processors and could show up on a customers // or your bank statement. These fields are reportable but not searchable in PayPal Manager. Inv.InvNum = t.MerchantInvoiceNumber; Inv.CustRef = t.Customer.Email; //' Comment1 and Comment2 fields are searchable within PayPal Manager . Inv.Comment1 = "Order Number: " + Inv.InvNum; Inv.Comment2 = "Customer Email: " + t.Customer.Email; // Create the BillTo object. BillTo Bill = new BillTo(); Bill.FirstName = t.Customer.FirstName; Bill.LastName = t.Customer.LastName; Bill.Street = t.Customer.Street; Bill.City = t.Customer.City; Bill.Zip = t.Customer.PostalCode; Bill.PhoneNum = t.Customer.Phone; Bill.Email = t.Customer.Email; Bill.State = t.Customer.Region; //' BillToCountry code is based on numeric ISO country codes. (e.g. 840 = USA) //Get Country Code string CountryCode = MerchantTribe.Web.Geography.Country.FindByName(t.Customer.Country).IsoNumeric; Bill.BillToCountry = CountryCode; // Set the BillTo object into invoice. Inv.BillTo = Bill; CustomerInfo CustInfo = new CustomerInfo(); CustInfo.CustId = t.Customer.Email; CustInfo.CustIP = t.Customer.IpAddress; // *** Create a new Payment Device - Credit Card data object. *** // Note: Expiration date is in the format MMYY string CCExpDate = t.Card.ExpirationMonthPadded + t.Card.ExpirationYearTwoDigits; CreditCard CC = new CreditCard(t.Card.CardNumber, CCExpDate); //' *** Card Security Code *** //' This is the 3 or 4 digit code on either side of the Credit Card. if (t.Card.SecurityCode.Length > 0) { CC.Cvv2 = t.Card.SecurityCode; } // Name on Credit Card is optional. CC.Name = t.Card.CardHolderName; // *** Create a new Tender - Card Tender data object. *** CardTender Card = new CardTender(CC); // *** Create a new Transaction. *** // The Request Id is the unique id necessary for each transaction. // If you pass a non-unique request id, you will receive the transaction details from the original request. //'DO TRANSACTION try { BaseTransaction Trans = null; switch (t.Action) { case ActionType.CreditCardHold: Trans = new AuthorizationTransaction(User, Connection, Inv, Card, strRequestID); break; case ActionType.CreditCardCharge: Trans = new SaleTransaction(User, Connection, Inv, Card, strRequestID); break; case ActionType.CreditCardCapture: Trans = new CaptureTransaction(t.PreviousTransactionNumber, User, Connection, Inv, strRequestID); break; case ActionType.CreditCardRefund: Trans = new CreditTransaction(t.PreviousTransactionNumber, User, Connection, Inv, strRequestID); break; case ActionType.CreditCardVoid: Trans = new VoidTransaction(t.PreviousTransactionNumber, User, Connection, strRequestID); break; } int Result = 0; System.Globalization.CultureInfo currCulture = System.Threading.Thread.CurrentThread.CurrentCulture; Response Resp = null; try { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; //' Submit the Transaction Resp = Trans.SubmitTransaction(); } finally { System.Threading.Thread.CurrentThread.CurrentCulture = currCulture; } if (Resp != null) { // Get the Transaction Response parameters. TransactionResponse TrxnResponse = Resp.TransactionResponse; // RESULT codes returns. if (TrxnResponse != null) { //Check for Approval (0 = approved, all else = Decline or Error) Result = TrxnResponse.Result; string RespMsg = TrxnResponse.RespMsg; //if success then save our reference number if (Result == 0) { t.Result.ReferenceNumber = TrxnResponse.Pnref; } t.Result.ResponseCode = TrxnResponse.AuthCode; //Custom Properties t.Result.AvsCode = AvsResponseType.Unavailable; t.Result.AvsCodeDescription = "AVSADDR: " + TrxnResponse.AVSAddr + " AVSZIP: " + TrxnResponse.AVSZip + " IAVS: " + TrxnResponse.IAVS; t.Result.ResponseCode = TrxnResponse.Result.ToString(); t.Result.CvvCode = CvnResponseType.Unavailable; t.Result.CvvCodeDescription = TrxnResponse.CVV2Match; t.Result.ResponseCodeDescription = TrxnResponse.RespMsg; } else { t.Result.Messages.Add(new Message("Payment Error: Transaction Response is Null", "BVP_PFP_1003", MessageType.Error)); } //Show Complete Response if Debug Mode if (DebugMode) { t.Result.Messages.Add(new Message("PayflowPro Request:" + Trans.Request, "REQ", MessageType.Information)); t.Result.Messages.Add(new Message("PayflowPro Request:" + Trans.Response.ResponseString, "RES", MessageType.Information)); // Get the Transaction Context Context TransCtx = Resp.TransactionContext; if ((TransCtx != null) && (TransCtx.getErrorCount() > 0)) { t.Result.Messages.Add(new Message("PayflowPro Context:" + TransCtx.ToString(), "CTX", MessageType.Information)); } } if (Result == 0) { result = true; } else { result = false; } } else { t.Result.Messages.Add(new Message("Payment Error: Response is Null", "BVP_PFP_1002", MessageType.Error)); } } catch (Exception ex) { result = false; t.Result.Messages.Add(new Message("Payment Error: " + ex.Message, "BVP_PFP_1001", MessageType.Error)); t.Result.Messages.Add(new Message("Stack Trace " + ex.StackTrace, "STACKTRACE", MessageType.Error)); } t.Result.Succeeded = result; }
public static void Main(string[] Args) { Console.WriteLine("------------------------------------------------------"); Console.WriteLine("Executing Sample from File: DOCredit.cs"); Console.WriteLine("------------------------------------------------------"); // Create the Data Objects. // Create the User data object with the required user details. UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>"); // Create the Payflow Connection data object with the required connection details. // The PAYFLOW_HOST property is defined in the App config file. PayflowConnectionData Connection = new PayflowConnectionData(); // Create a new Invoice data object with the Amount, Billing Address etc. details. Invoice Inv = new Invoice(); // Set Amount. Currency Amt = new Currency(new decimal(25.12)); Inv.Amt = Amt; Inv.PoNum = "PO12345"; Inv.InvNum = "INV12345"; // Set the Billing Address details. BillTo Bill = new BillTo(); Bill.BillToStreet = "123 Main St."; Bill.BillToZip = "12345"; Inv.BillTo = Bill; // Create a new Payment Device - Credit Card data object. // The input parameters are Credit Card Number and Expiration Date of the Credit Card. CreditCard CC = new CreditCard("5105105105105100", "0115"); // Create a new Tender - Card Tender data object. CardTender Card = new CardTender(CC); /////////////////////////////////////////////////////////////////// // Create a new Credit Transaction. // Following is an example of a independent credit type of transaction. CreditTransaction Trans = new CreditTransaction(User, Connection, Inv, Card, PayflowUtility.RequestId); // Submit the Transaction Response Resp = Trans.SubmitTransaction(); // Display the transaction response parameters. if (Resp != null) { // Get the Transaction Response parameters. TransactionResponse TrxnResponse = Resp.TransactionResponse; if (TrxnResponse != null) { Console.WriteLine("RESULT = " + TrxnResponse.Result); Console.WriteLine("PNREF = " + TrxnResponse.Pnref); Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg); Console.WriteLine("AUTHCODE = " + TrxnResponse.AuthCode); Console.WriteLine("AVSADDR = " + TrxnResponse.AVSAddr); Console.WriteLine("AVSZIP = " + TrxnResponse.AVSZip); Console.WriteLine("IAVS = " + TrxnResponse.IAVS); Console.WriteLine("CVV2MATCH = " + TrxnResponse.CVV2Match); // If value is true, then the Request ID has not been changed and the original response // of the original transction is returned. Console.WriteLine("DUPLICATE = " + TrxnResponse.Duplicate); } // Get the Fraud Response parameters. FraudResponse FraudResp = Resp.FraudResponse; // Display Fraud Response parameter if (FraudResp != null) { Console.WriteLine("PREFPSMSG = " + FraudResp.PreFpsMsg); Console.WriteLine("POSTFPSMSG = " + FraudResp.PostFpsMsg); } // Display the response. Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp)); // Get the Transaction Context and check for any contained SDK specific errors (optional code). Context TransCtx = Resp.TransactionContext; if (TransCtx != null && TransCtx.getErrorCount() > 0) { Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString()); } } Console.WriteLine("Press Enter to Exit ..."); Console.ReadLine(); }
public void GetTransactionValueCredit() { var transaction = new CreditTransaction(); transaction.TransDate = DateTime.Now; transaction.Description = "Admin Expenses"; transaction.Value = 55.26m; transaction.Balance = 543.12m; Assert.That(transaction.Description, Is.EqualTo("Admin expenses")); }
public void GetDummyTransactionCredit() { var transaction = new CreditTransaction(); var MyTransactionCredit = new TransactionDomainService(); transaction = MyTransactionCredit.GetDummyCreditTransaction(); Assert.That(transaction.Description, Is.Not.Null); }
public CreditTransaction GetCreditTransaction(byte[] result) { return(CreditTransaction.ParseFrom(result)); }
/// <summary> /// Credits (Refunds) the specified transaction. /// </summary> /// <param name="origTransaction">The original transaction.</param> /// <param name="amount">The amount.</param> /// <param name="comment">The comment.</param> /// <param name="errorMessage">The error message.</param> /// <returns></returns> public override FinancialTransaction Credit( FinancialTransaction origTransaction, decimal amount, string comment, out string errorMessage ) { errorMessage = string.Empty; Response ppResponse = null; if ( origTransaction != null && !string.IsNullOrWhiteSpace( origTransaction.TransactionCode ) && origTransaction.FinancialGateway != null ) { var ppInvoice = new Invoice(); ppInvoice.Amt = new Currency( amount ); ppInvoice.Comment1 = comment; var ppTransaction = new CreditTransaction( origTransaction.TransactionCode, GetUserInfo( origTransaction.FinancialGateway ), GetConnection( origTransaction.FinancialGateway ), ppInvoice, PayflowUtility.RequestId ); ppResponse = ppTransaction.SubmitTransaction(); if ( ppResponse != null ) { TransactionResponse txnResponse = ppResponse.TransactionResponse; if ( txnResponse != null ) { if ( txnResponse.Result == 0 ) // Success { var transaction = new FinancialTransaction(); transaction.TransactionCode = txnResponse.Pnref; return transaction; } else { errorMessage = string.Format( "[{0}] {1}", txnResponse.Result, txnResponse.RespMsg ); } } else { errorMessage = "Invalid transaction response from the financial gateway"; } } else { errorMessage = "Invalid response from the financial gateway."; } } else { errorMessage = "Invalid original transaction, transaction code, or gateway."; } return null; }
public SpecFlowFeature1Steps() { auditorMock = new Mock <ITransactionAuditor>(); creditTransaction = new CreditTransaction(); account = new BankAccount(auditorMock.Object); }
public void Setup() { // Arrange creditTransaction = new CreditTransaction(); }
public void Visit(CreditTransaction visitable) { throw new NotImplementedException(); }
public AktTransactionPrintedDocumentTemplate(CreditTransaction transaction, byte[] templateFile) { TemplateFile = templateFile; _labelValues = new Dictionary <string, string>(); _labelValues.Add("банк_кредитор", transaction.Creditor.Name); _labelValues.Add("пропись_итого_комиссия", MoneyToText.Convert(((transaction.CreditSumm - (transaction.RealPrice - transaction.DownPaymentCashbox)) - transaction.ReportInsurance - transaction.Rollback + transaction.CommissionCashbox))); _labelValues.Add("итого_комиссия", ((transaction.CreditSumm - (transaction.RealPrice - transaction.DownPaymentCashbox)) - transaction.ReportInsurance - transaction.Rollback + transaction.CommissionCashbox).ToString()); _labelValues.Add("остаток_в_сумме", (transaction.CreditSumm - (transaction.RealPrice - transaction.DownPaymentCashbox)).ToString()); _labelValues.Add("пропись_остаток_в_сумме", MoneyToText.Convert(transaction.CreditSumm - (transaction.RealPrice - transaction.DownPaymentCashbox))); _labelValues.Add("к_выдаче_продавцу", (transaction.RealPrice - transaction.DownPaymentCashbox).ToString()); _labelValues.Add("пропись_к_выдаче_продавцу", MoneyToText.Convert(transaction.RealPrice - transaction.DownPaymentCashbox)); _labelValues.Add("пропись_комиссия_касса", MoneyToText.Convert(transaction.CommissionCashbox)); _labelValues.Add("пропись_сумма_кредит", MoneyToText.Convert(transaction.CreditSumm)); _labelValues.Add("пропись_первый_взнос", MoneyToText.Convert(transaction.DownPayment)); _labelValues.Add("пропись_стоимость_банк", MoneyToText.Convert(transaction.PriceBank)); _labelValues.Add("реквизит", transaction.Requisit.Name); _labelValues.Add("бик_реквизит", transaction.Requisit.Bik); _labelValues.Add("рс_реквизит", transaction.Requisit.Ros_schet); _labelValues.Add("кс_реквизит", transaction.Requisit.Kor_schet); _labelValues.Add("в_банке_реквизит", transaction.Requisit.InBank); _labelValues.Add("месяц_доверенность", transaction.DateProxy?.Month.ToString()); _labelValues.Add("месяц_ад", transaction.DateAgent?.Month.ToString()); _labelValues.Add("месяц", transaction.Date.Month.ToString()); _labelValues.Add("имя_мен", transaction.User.FirstName); _labelValues.Add("фамилия_мен", transaction.User.LastName); _labelValues.Add("отчество_мен", transaction.User.MiddleName); _labelValues.Add("имя_р__мен", transaction.User.FirstNameGenitive); _labelValues.Add("фамилия_р_мен", transaction.User.LastNameGenitive); _labelValues.Add("отчество_р__мен", transaction.User.MiddleNameGenitive); _labelValues.Add("номер_мен", transaction.User.Number); _labelValues.Add("дата_мен", transaction.User.Date.ToString("dd.MM.yyyy")); _labelValues.Add("номер", transaction.Number.ToString()); _labelValues.Add("дата_да", transaction.DateAgent?.ToString("dd.MM.yyyy")); _labelValues.Add("дата", transaction.Date.ToString("dd.MM.yyyy")); _labelValues.Add("дата_доверенность", transaction.DateProxy?.ToString("dd.MM.yyyy")); _labelValues.Add("номер_доверенность", transaction.NumberProxy); _labelValues.Add("номер_реестр", transaction.NumberRegistry); _labelValues.Add("стоимость", transaction.Price.ToString()); _labelValues.Add("пропись", MoneyToText.Convert(transaction.Price)); _labelValues.Add("стоимость_банк", transaction.PriceBank.ToString()); _labelValues.Add("первый_взнос", transaction.DownPayment.ToString()); _labelValues.Add("сумма_кредит", transaction.CreditSumm.ToString()); _labelValues.Add("стоимость_реальная", transaction.RealPrice.ToString()); _labelValues.Add("первый_взнос_касса", transaction.DownPaymentCashbox.ToString()); _labelValues.Add("отчёт_по_страховым", transaction.ReportInsurance.ToString()); _labelValues.Add("откат", transaction.Rollback.ToString()); _labelValues.Add("источник", transaction.Source); _labelValues.Add("комиссия_Касса", transaction.CommissionCashbox.ToString()); if (transaction.Seller != null) { _labelValues.Add("п_фио", ReportHelper.GetFullName(transaction.Seller)); _labelValues.Add("п_фио_сокр", ReportHelper.GetShortName(transaction.Seller)); _labelValues.Add("п_контрагент_и", ReportHelper.GetContractorName(transaction.Seller)); _labelValues.Add("п_контрагент_р", ReportHelper.GetContractorNameGenitive(transaction.Seller)); _labelValues.Add("п_подпись", ReportHelper.GetContractorSignature(transaction.Seller)); } else { _labelValues.Add("п_фио", null); _labelValues.Add("п_фио_сокр", null); _labelValues.Add("п_контрагент_и", null); _labelValues.Add("п_контрагент_р", null); _labelValues.Add("п_подпись", null); } if (transaction.Buyer != null) { _labelValues.Add("по_фио", ReportHelper.GetFullName(transaction.Buyer)); _labelValues.Add("по_фио_сокр", ReportHelper.GetShortName(transaction.Buyer)); _labelValues.Add("по_контрагент_и", ReportHelper.GetContractorName(transaction.Buyer)); _labelValues.Add("по_контрагент_р", ReportHelper.GetContractorNameGenitive(transaction.Buyer)); _labelValues.Add("по_подпись", ReportHelper.GetContractorSignature(transaction.Buyer)); } else { _labelValues.Add("по_фио", null); _labelValues.Add("по_фио_сокр", null); _labelValues.Add("по_контрагент_и", null); _labelValues.Add("по_контрагент_р", null); _labelValues.Add("по_подпись", null); } if (transaction.Owner != null) { _labelValues.Add("соб_фио", ReportHelper.GetFullName(transaction.Owner)); _labelValues.Add("соб_фио_сокр", ReportHelper.GetShortName(transaction.Owner)); _labelValues.Add("соб_контрагент_и", ReportHelper.GetContractorName(transaction.Owner)); _labelValues.Add("соб_контрагент_р", ReportHelper.GetContractorNameGenitive(transaction.Owner)); _labelValues.Add("соб_подпись", ReportHelper.GetContractorSignature(transaction.Owner)); } else { _labelValues.Add("соб_фио", null); _labelValues.Add("соб_фио_сокр", null); _labelValues.Add("соб_контрагент_и", null); _labelValues.Add("соб_контрагент_р", null); _labelValues.Add("соб_подпись", null); } _labelValues.Add("вид_тс", transaction.Trancport.Type.Name); _labelValues.Add("год_тс", transaction.Trancport.Year.ToString()); _labelValues.Add("вин", transaction.Trancport.Vin); _labelValues.Add("гос_номер_тс", transaction.Trancport.Number); _labelValues.Add("дата_птс", transaction.Trancport.DatePts?.ToString("dd.MM.yyyy")); _labelValues.Add("дата_cтс", transaction.Trancport.DateSts?.ToString("dd.MM.yyyy")); _labelValues.Add("изготовитель_тс", transaction.Trancport.Maker); _labelValues.Add("категория_тc", transaction.Trancport.Category.Name); _labelValues.Add("кем_птс", transaction.Trancport.ByPts); _labelValues.Add("кем_стс", transaction.Trancport.BySts); _labelValues.Add("кузов", transaction.Trancport.BodyNumber); _labelValues.Add("макс_масса", transaction.Trancport.MaxMass); _labelValues.Add("марка_двиг", transaction.Trancport.EngineMake); _labelValues.Add("марка_тс", transaction.Trancport.Make.Name); _labelValues.Add("модель_тс", transaction.Trancport.Model.Name); _labelValues.Add("масса", transaction.Trancport.Mass); _labelValues.Add("мощность", transaction.Trancport.Strong); _labelValues.Add("номер_птс", transaction.Trancport.NumberPts); _labelValues.Add("номер_стс", transaction.Trancport.NumberSts); _labelValues.Add("объем", transaction.Trancport.Volume); _labelValues.Add("па", transaction.Trancport.Pa); _labelValues.Add("серия_птс", transaction.Trancport.SerialPts); _labelValues.Add("серия_стс", transaction.Trancport.SerialSts); _labelValues.Add("типы_двигателей_тс", transaction.Trancport.EngineType.Name); _labelValues.Add("цвет", transaction.Trancport.Color); _labelValues.Add("шасси", transaction.Trancport.ChassisNumber); }
static void Main(string[] args) { #warning ПРИ ИЗМЕНЕНИИ БД НЕ ЗАБУДЬ СОЗДАТЬ ТРИГЕРЫ using (var aimp = new aimpEntities()) { using (var newDb = new SqlContext()) { newDb.StatusesCardTrancport.Add(new StatusCardTrancport() { Name = "В наличии" }); newDb.StatusesCardTrancport.Add(new StatusCardTrancport() { Name = "Продана" }); newDb.StatusesCardTrancport.Add(new StatusCardTrancport() { Name = "Зобрали с комиссии" }); foreach (ШАБЛОНЫ шаблоны in aimp.ШАБЛОНЫ) { string type = string.Empty; switch (шаблоны.типы_шаблонов) { case 1: type = PrintedDocumentTemplateType.Сделка.ToString(); break; case 2: type = PrintedDocumentTemplateType.Кредит.ToString(); break; case 3: type = PrintedDocumentTemplateType.Дкп.ToString(); break; case 4: type = PrintedDocumentTemplateType.Акт.ToString(); break; case 5: type = PrintedDocumentTemplateType.Комиссия.ToString(); break; } PrintedDocumentTemplate reportTemplate = new PrintedDocumentTemplate() { Name = шаблоны.наименование, File = шаблоны.файл, FileName = шаблоны.файл_наим, Type = type }; newDb.PrintedDocumentTemplates.Add(reportTemplate); } foreach (ОТЧЁТЫ_КЛИЕНТОВ отчётыКлиентов in aimp.ОТЧЁТЫ_КЛИЕНТОВ) { спр_СТАТУСЫ_КЛИЕНТОВ спрСтатусыКлиентов = aimp.спр_СТАТУСЫ_КЛИЕНТОВ.First( x => x.код == отчётыКлиентов.спр_статусы_клиентов); спр_ПРОГРАММЫ_КРЕДИТОВАНИЯ программыКредитования = aimp.спр_ПРОГРАММЫ_КРЕДИТОВАНИЯ.First( x => x.код == отчётыКлиентов.спр_программы_кредитования); ClientReport clientReport = new ClientReport() { Date = отчётыКлиентов.дата ?? DateTime.Now, Source = отчётыКлиентов.источник, FullName = отчётыКлиентов.фио, Price = Convert.ToDecimal(отчётыКлиентов.стоимость), TotalContribution = Convert.ToDecimal(отчётыКлиентов.общий_взнос), ClientStatus = newDb.ClientStatuses.Local.FirstOrDefault( x => x.Name == спрСтатусыКлиентов.наименование) ?? new ClientStatus() { Name = спрСтатусыКлиентов.наименование, UsedFilter = nullBye(спрСтатусыКлиентов.фильтр) }, Telefon = отчётыКлиентов.телефон, CreditProgramm = newDb.CreditProgramms.Local.FirstOrDefault( x => x.Name == программыКредитования.наименование) ?? new CreditProgramm() { Name = программыКредитования.наименование }, CreditSum = Convert.ToDecimal(отчётыКлиентов.сумма_кредита), CommissionKnow = nullBye(отчётыКлиентов.комиссии_знает), CommissionRemoval = Convert.ToDecimal(отчётыКлиентов.комиссия_за_снятие), CommissionCredit = nullBye(отчётыКлиентов.комиссии_в_кредите), ActAssessment = Convert.ToDecimal(отчётыКлиентов.акт_оценки), DKP_DK = отчётыКлиентов.дкп_дк, Comment = отчётыКлиентов.комментарий, CommissionSalon = отчётыКлиентов.комиссия_салона, User = NewUser(отчётыКлиентов.ПОЛЬЗОВАТЕЛИ1, newDb), Trancport = отчётыКлиентов.тс }; foreach (БАНКИ_ДЛЯ_ОТЧЁТЫ_КЛИЕНТОВ банкиДляОтчётыКлиентов in отчётыКлиентов.БАНКИ_ДЛЯ_ОТЧЁТЫ_КЛИЕНТОВ) { BankReportClient bankReportClient = new BankReportClient(); bankReportClient.ClientReport = clientReport; bankReportClient.Bank = newDb.Banks.Local.FirstOrDefault( x => x.Name == банкиДляОтчётыКлиентов.спр_БАНКИ_ОТЧЁТЫ_КЛИЕНТОВ1.наименование) ?? new Bank() { Name = банкиДляОтчётыКлиентов.спр_БАНКИ_ОТЧЁТЫ_КЛИЕНТОВ1.наименование }; bankReportClient.BankStatus = newDb.BankStatuses.Local.FirstOrDefault( x => x.Name == банкиДляОтчётыКлиентов.спр_СТАТУСЫ_БАНКА1.наименование) ?? new BankStatus() { Name = банкиДляОтчётыКлиентов.спр_СТАТУСЫ_БАНКА1.наименование, MiddleName = банкиДляОтчётыКлиентов.спр_СТАТУСЫ_БАНКА1.наименование2 }; bankReportClient.Used = банкиДляОтчётыКлиентов.используется == null ? false : банкиДляОтчётыКлиентов.используется == 1 ? true : false; newDb.BankReportClients.Add(bankReportClient); } } foreach (var сделка in aimp.СДЕЛКИ) { CashTransaction cash = new CashTransaction(); cash.Date = сделка.дата ?? DateTime.Now; cash.Number = Convert.ToInt32(сделка.номер); if (сделка.КОНТРАГЕНТЫ1 != null) { cash.Buyer = NewContractor(сделка.КОНТРАГЕНТЫ1, newDb); } if (сделка.КОНТРАГЕНТЫ2 != null) { cash.Owner = NewContractor(сделка.КОНТРАГЕНТЫ2, newDb); } cash.Trancport = NewTrancport(сделка.ТРАНСПОРТ1, newDb); cash.Price = Convert.ToDecimal(сделка.стоимость); cash.User = NewUser(сделка.ПОЛЬЗОВАТЕЛИ1, newDb); cash.DateProxy = сделка.дата_доверенность; cash.NumberProxy = сделка.номер_доверенность; cash.NumberRegistry = сделка.номер_реестр; if (сделка.КОНТРАГЕНТЫ != null) { cash.Seller = NewContractor(сделка.КОНТРАГЕНТЫ, newDb); } switch (сделка.тип) { case 1: newDb.CashTransactions.Add(cash); break; case 2: CreditTransaction credit = new CreditTransaction() { Date = cash.Date, Number = cash.Number, Seller = cash.Seller, Buyer = cash.Buyer, Owner = cash.Owner, Trancport = cash.Trancport, Price = cash.Price, User = cash.User, DateProxy = cash.DateProxy, NumberProxy = cash.NumberProxy, NumberRegistry = cash.NumberRegistry }; credit.AgentDocument = new UserFile() { Name = сделка.агенский_наим, File = сделка.агенский }; credit.DkpDocument = new UserFile() { Name = сделка.дкп_наим, File = сделка.дкп }; credit.DateAgent = сделка.дата_ад ?? DateTime.Now; credit.DateDkp = сделка.дата ?? DateTime.Now; credit.PriceBank = Convert.ToDecimal(сделка.стоимость_банк); credit.DownPayment = Convert.ToDecimal(сделка.первый_взнос); credit.CreditSumm = Convert.ToDecimal(сделка.сумма_кредит); credit.RealPrice = Convert.ToDecimal(сделка.стоимость_реальная); credit.DownPaymentCashbox = Convert.ToDecimal(сделка.первый_взнос_касса); string creditor = aimp.КРЕДИТОРЫ.FirstOrDefault(x => x.код == сделка.кредиторы)?.наименование; if (!string.IsNullOrWhiteSpace(creditor)) { credit.Creditor = newDb.Creditors.Local.FirstOrDefault(x => x.Name == creditor) ?? new Creditor() { Name = creditor }; } ЕКВИЗИТЫ реквизит = aimp.ЕКВИЗИТЫ.First(x => x.код == сделка.реквизиты); credit.Requisit = newDb.Requisits.Local.FirstOrDefault( x => x.Name == реквизит.наименование && x.Bik == реквизит.бик) ?? new Requisit() { Name = реквизит.наименование, Bik = реквизит.бик, InBank = реквизит.в_банке, Kor_schet = реквизит.кор_счет, Ros_schet = реквизит.рос_счет }; credit.ReportInsurance = Convert.ToDecimal(сделка.отчёт_по_страховым); credit.Rollback = Convert.ToDecimal(сделка.откат); credit.Source = сделка.источник; credit.IsCredit = сделка.кредит == 1 ? true : false; credit.CommissionCashbox = Convert.ToDecimal(сделка.комиссия_Касса); newDb.CreditTransactions.Add(credit); break; case 3: case 5: CommissionTransaction commission = new CommissionTransaction() { Date = cash.Date, Number = cash.Number, Seller = cash.Seller, Buyer = cash.Buyer, Owner = cash.Owner, Trancport = cash.Trancport, Price = cash.Price, User = cash.User, DateProxy = cash.DateProxy, NumberProxy = cash.NumberProxy, NumberRegistry = cash.NumberRegistry }; commission.Commission = Convert.ToDecimal(сделка.комиссия); commission.Parking = Convert.ToDecimal(сделка.стоянка); commission.IsTwoMounth = сделка.второй_месяц == null ? false : сделка.второй_месяц == 1 ? true : false; newDb.CommissionTransactions.Add(commission); break; } } newDb.SaveChanges(); } } }
public static void Main(string[] Args) { Console.WriteLine("------------------------------------------------------"); Console.WriteLine("Executing Sample from File: DOReferenceCredit.cs"); Console.WriteLine("------------------------------------------------------"); // Create the Data Objects. // Create the User data object with the required user details. UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>"); // Create the Payflow Connection data object with the required connection details. // The PAYFLOW_HOST property is defined in the App config file. PayflowConnectionData Connection = new PayflowConnectionData(); /////////////////////////////////////////////////////////////////// // If you want to change the amount being credited, you'll need to set the Amount object. //Invoice Inv = new Invoice(); // Set the amount object if you want to change the amount from the original transaction. // Currency Code USD is US ISO currency code. If no code passed, USD is default. // See the Developer's Guide for the list of three-character currency codes available. //Currency Amt = new Currency(new decimal(10.00)); //Inv.Amt = Amt; //CreditTransaction trans = new CreditTransaction("<ORIGINAL_PNREF>", User, Connection, Inv, PayflowUtility.getRequestId()); // Create a new Invoice data object with the Amount, Billing Address etc. details. Invoice Inv = new Invoice(); // Set Amount. Currency Amt = new Currency(new decimal(25.12)); Inv.Amt = Amt; Inv.PoNum = "PO12345"; Inv.InvNum = "INV12345"; // Create a new Credit Transaction from the original transaction. See above if you // need to change the amount. CreditTransaction Trans = new CreditTransaction("<ORIGINAL_PNREF>", User, Connection, Inv, PayflowUtility.RequestId); // Submit the Transaction Response Resp = Trans.SubmitTransaction(); // Display the transaction response parameters. if (Resp != null) { // Get the Transaction Response parameters. TransactionResponse TrxnResponse = Resp.TransactionResponse; if (TrxnResponse != null) { Console.WriteLine("RESULT = " + TrxnResponse.Result); Console.WriteLine("PNREF = " + TrxnResponse.Pnref); Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg); Console.WriteLine("AUTHCODE = " + TrxnResponse.AuthCode); Console.WriteLine("AVSADDR = " + TrxnResponse.AVSAddr); Console.WriteLine("AVSZIP = " + TrxnResponse.AVSZip); Console.WriteLine("IAVS = " + TrxnResponse.IAVS); } // Get the Fraud Response parameters. FraudResponse FraudResp = Resp.FraudResponse; // Display Fraud Response parameter if (FraudResp != null) { Console.WriteLine("PREFPSMSG = " + FraudResp.PreFpsMsg); Console.WriteLine("POSTFPSMSG = " + FraudResp.PostFpsMsg); } // Display the response. Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp)); // Get the Transaction Context and check for any contained SDK specific errors (optional code). Context TransCtx = Resp.TransactionContext; if (TransCtx != null && TransCtx.getErrorCount() > 0) { Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString()); } } Console.WriteLine("Press Enter to Exit ..."); Console.ReadLine(); }
public override void ProcessTransaction(Transaction t) { bool result = false; //'Get Configuration Settings string MerchantPartner = Settings.MerchantPartner; string MerchantLogin = Settings.MerchantLogin; string MerchantUser = Settings.MerchantUser; string MerchantPassword = Settings.MerchantPassword; string CurrencyCode = Settings.CurrencyCode; bool TestMode = Settings.TestMode; bool DebugMode = Settings.DeveloperMode; UserInfo User = new UserInfo(MerchantUser, MerchantLogin, MerchantPartner, MerchantPassword); //Set HostAddress URL string HostAddress = LiveUrl; if (TestMode) HostAddress = TestUrl; //Connection Info PayflowConnectionData Connection = new PayflowConnectionData(HostAddress, 443, 45); //', CertLocation) // *** Create a new Invoice data object *** // Set Invoice object with the Amount, Billing & Shipping Address, etc. *** Invoice Inv = new Invoice(); // Set the amount object. A valid amount is a two decimal value. An invalid amount will generate a result code Currency Amt = new Currency(Decimal.Round(t.Amount, 2), CurrencyCode); //' 840 is US ISO currency code. If no code passed, 840 is default. Inv.Amt = Amt; // Generate a unique transaction ID string strRequestID = PayflowUtility.RequestId + t.MerchantInvoiceNumber; //InvNum and CustRef are sent to the processors and could show up on a customers // or your bank statement. These fields are reportable but not searchable in PayPal Manager. Inv.InvNum = t.MerchantInvoiceNumber; Inv.CustRef = t.Customer.Email; //' Comment1 and Comment2 fields are searchable within PayPal Manager . Inv.Comment1 = "Order Number: " + Inv.InvNum; Inv.Comment2 = "Customer Email: " + t.Customer.Email; // Create the BillTo object. BillTo Bill = new BillTo(); Bill.FirstName = t.Customer.FirstName; Bill.LastName = t.Customer.LastName; Bill.Street = t.Customer.Street; Bill.City = t.Customer.City; Bill.Zip = t.Customer.PostalCode; Bill.PhoneNum = t.Customer.Phone; Bill.Email = t.Customer.Email; Bill.State = t.Customer.Region; //' BillToCountry code is based on numeric ISO country codes. (e.g. 840 = USA) //Get Country Code string CountryCode = MerchantTribe.Web.Geography.Country.FindByName(t.Customer.Country).IsoNumeric; Bill.BillToCountry = CountryCode; // Set the BillTo object into invoice. Inv.BillTo = Bill; CustomerInfo CustInfo = new CustomerInfo(); CustInfo.CustId = t.Customer.Email; CustInfo.CustIP = t.Customer.IpAddress; // *** Create a new Payment Device - Credit Card data object. *** // Note: Expiration date is in the format MMYY string CCExpDate = t.Card.ExpirationMonthPadded + t.Card.ExpirationYearTwoDigits; CreditCard CC = new CreditCard(t.Card.CardNumber, CCExpDate); //' *** Card Security Code *** //' This is the 3 or 4 digit code on either side of the Credit Card. if (t.Card.SecurityCode.Length > 0) { CC.Cvv2 = t.Card.SecurityCode; } // Name on Credit Card is optional. CC.Name = t.Card.CardHolderName; // *** Create a new Tender - Card Tender data object. *** CardTender Card = new CardTender(CC); // *** Create a new Transaction. *** // The Request Id is the unique id necessary for each transaction. // If you pass a non-unique request id, you will receive the transaction details from the original request. //'DO TRANSACTION try { BaseTransaction Trans = null; switch(t.Action) { case ActionType.CreditCardHold: Trans = new AuthorizationTransaction(User,Connection, Inv, Card, strRequestID); break; case ActionType.CreditCardCharge: Trans = new SaleTransaction(User,Connection, Inv, Card, strRequestID); break; case ActionType.CreditCardCapture: Trans = new CaptureTransaction(t.PreviousTransactionNumber, User, Connection, Inv, strRequestID); break; case ActionType.CreditCardRefund: Trans = new CreditTransaction(t.PreviousTransactionNumber, User, Connection, Inv, strRequestID); break; case ActionType.CreditCardVoid: Trans = new VoidTransaction(t.PreviousTransactionNumber, User, Connection, strRequestID); break; } int Result = 0; System.Globalization.CultureInfo currCulture = System.Threading.Thread.CurrentThread.CurrentCulture; Response Resp = null; try { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; //' Submit the Transaction Resp = Trans.SubmitTransaction(); } finally { System.Threading.Thread.CurrentThread.CurrentCulture = currCulture; } if (Resp != null) { // Get the Transaction Response parameters. TransactionResponse TrxnResponse = Resp.TransactionResponse; // RESULT codes returns. if (TrxnResponse != null) { //Check for Approval (0 = approved, all else = Decline or Error) Result = TrxnResponse.Result; string RespMsg = TrxnResponse.RespMsg; //if success then save our reference number if (Result == 0) { t.Result.ReferenceNumber = TrxnResponse.Pnref; } t.Result.ResponseCode = TrxnResponse.AuthCode; //Custom Properties t.Result.AvsCode = AvsResponseType.Unavailable; t.Result.AvsCodeDescription = "AVSADDR: " + TrxnResponse.AVSAddr + " AVSZIP: " + TrxnResponse.AVSZip + " IAVS: " + TrxnResponse.IAVS; t.Result.ResponseCode = TrxnResponse.Result.ToString(); t.Result.CvvCode = CvnResponseType.Unavailable; t.Result.CvvCodeDescription = TrxnResponse.CVV2Match; t.Result.ResponseCodeDescription = TrxnResponse.RespMsg; } else { t.Result.Messages.Add(new Message("Payment Error: Transaction Response is Null", "BVP_PFP_1003", MessageType.Error)); } //Show Complete Response if Debug Mode if (DebugMode) { t.Result.Messages.Add(new Message("PayflowPro Request:" + Trans.Request, "REQ", MessageType.Information)); t.Result.Messages.Add(new Message("PayflowPro Request:" + Trans.Response.ResponseString, "RES", MessageType.Information)); // Get the Transaction Context Context TransCtx = Resp.TransactionContext; if ((TransCtx != null) && (TransCtx.getErrorCount() > 0)) { t.Result.Messages.Add(new Message("PayflowPro Context:" + TransCtx.ToString(), "CTX", MessageType.Information)); } } if (Result == 0) { result = true; } else { result = false; } } else { t.Result.Messages.Add(new Message("Payment Error: Response is Null", "BVP_PFP_1002", MessageType.Error)); } } catch(Exception ex) { result = false; t.Result.Messages.Add(new Message("Payment Error: " + ex.Message, "BVP_PFP_1001", MessageType.Error)); t.Result.Messages.Add(new Message("Stack Trace " + ex.StackTrace, "STACKTRACE", MessageType.Error)); } t.Result.Succeeded = result; }
public IActionResult PaymentTerm([FromBody] IPayment payment) { using (var transaction = ctx.Database.BeginTransaction()) { try { var contract = ctx.CreditContract.FirstOrDefault(p => p.ContractId == payment.ContractId); var calculate = ctx.CreditCalculate.FirstOrDefault(p => p.CalculateId == contract.CalculateId); var PayNetPrice = payment.PayNetPrice; var InstalmentNo = payment.CreditContractItem.Min(x => x.InstalmentNo); var _ContractItem = ctx.CreditContractItem .Where(x => x.ContractId == payment.ContractId && x.InstalmentNo >= InstalmentNo) .OrderBy(x => x.InstalmentNo) .ToList(); var TaxInvoiceNo = iSysParamService.GenerateInstalmentTaxInvoiceNo(payment.BranchId); var ReceiptNo = iSysParamService.GenerateReceiptNo(payment.BranchId); _ContractItem.ForEach(Item => { //var Item = ctx.CreditContractItem.SingleOrDefault(o => o.ContractItemId == x.ContractItemId); if (PayNetPrice <= 0) { return; } var vat = 1 + (Item.VatRate / 100); var CreditTransList = new List <CreditTransaction>(); var CreditTransItem = new CreditTransaction(); // ในกรณีที่ชำระน้อยกว่าที่ระบบกำหนด เมื่อถึงงวดสุดท้ายที่เลือกชำระ ยอดคงเหลือจะถูกหักออกบางส่วน // true = ให้เอายอดคงเหลือไปลบ ยอดชำระ // false = ใช้ยอดคงเหลือไปตัดออกจาก ยอดคงเหลือในรายการ var _PayNetPrice = PayNetPrice < Item.RemainNetPrice ? Item.RemainNetPrice - PayNetPrice : Item.RemainNetPrice; // เปรียบเทียบ _PayNetPrice == Item.RemainNetPrice เพื่อนำยอดคงเหลือไปบันทึก // true = ลบยอดคงเหลือด้วย ยอดรับชำระ // false = ยอดชำระ _PayNetPrice = _PayNetPrice == Item.RemainNetPrice ? Item.RemainNetPrice - _PayNetPrice : _PayNetPrice; var payPriceExvat = _PayNetPrice / vat; var remainNetPriceExVat = _PayNetPrice / vat; // กรณีที่มีค่าปรับ ระบบจะหักให้อัตโนมัติ // โดยจะต้องชำระค่าปรับก่อนค่างวดเสมอ if (Item.FineSum > 0) { Item.FineSumRemain = 0; Item.FineSumStatus = 11; } if (payment.FineSumOther > 0) { Item.FineSumOther = payment.FineSumOther; } // ถ้า ยอดรับชำระ น้อยกว่า ยอดคงเหลือ // true = ชำระบางส่วน // false = ชำระครบ CreditTransItem = new CreditTransaction { ContractItemId = Item.ContractItemId }; if (PayNetPrice < Item.RemainNetPrice) { CreditTransItem.Description = $"ชำระค่างวดท่ี {Item.InstalmentNo} บางส่วน"; Item.Status = 12; } else { CreditTransItem.Description = Item.Status == 12 ? $"ชำระยอดยกมาจากงวดที่ {Item.InstalmentNo - 1}" : "ชำระครบ"; Item.Status = 11; } // ลบยอดคงเหลือออกจาก ยอดชำระ ลงเรื่อยๆ PayNetPrice -= Item.RemainNetPrice; var PayPrice = Item.Balance - remainNetPriceExVat; var PayVatPrice = Item.BalanceVatPrice - (_PayNetPrice - remainNetPriceExVat); var __PayNetPrice = Item.BalanceNetPrice - _PayNetPrice; Item.RevenueStamp = payment.RevenueStamp; Item.PayPrice = PayPrice; Item.PayVatPrice = PayVatPrice; Item.PayNetPrice = __PayNetPrice; CreditTransItem.PayPrice = PayPrice; CreditTransItem.PayVatPrice = PayVatPrice; CreditTransItem.PayNetPrice = __PayNetPrice; CreditTransList.Add(CreditTransItem); Item.Remain = remainNetPriceExVat; Item.RemainVatPrice = _PayNetPrice - remainNetPriceExVat; Item.RemainNetPrice = _PayNetPrice; Item.Payeer = payment.UpdateBy; Item.PayDate = payment.PayDate; Item.PaymentType = payment.PaymentType; Item.BankCode = payment.BankCode; Item.TaxInvoiceBranchId = payment.BranchId; if (Item.TaxInvoiceNo == null) { Item.TaxInvoiceNo = TaxInvoiceNo; } if (Item.ReceiptNo == null) { Item.ReceiptNo = ReceiptNo; } Item.Remark = payment.Remark; Item.DocumentRef = payment.DocumentRef; Item.UpdateBy = payment.UpdateBy; Item.UpdateDate = DateTime.Now; ctx.CreditContractItem.Update(Item); ctx.SaveChanges(); ctx.CreditTransactions.AddRange(CreditTransList); ctx.SaveChanges(); }); // นำจะนวนรายการชำระครบ var isPay = ctx.CreditContractItem .Where(p => p.Status == 11 && p.ContractId == contract.ContractId && p.RefNo == contract.RefNo) .Count(); // นับจำนวนทั้งหมด var totalRec = ctx.CreditContractItem .Where(p => p.ContractId == contract.ContractId && p.RefNo == contract.RefNo) .Count(); if (isPay == totalRec) { // ถ้าชำระครบ จะเปลี่ยนสถานะเป็น ชำระครบรอโอนทะเบียน contract.ContractStatus = 30; contract.EndContractDate = DateTime.Now.Date; ctx.CreditContract.Update(contract); ctx.SaveChanges(); } transaction.Commit(); return(Get(payment.ContractId)); } catch (Exception ex) { Console.Write(ex.Message); transaction.Rollback(); return(StatusCode(500, ex.Message)); } } }
/// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResult(); // Check license bool isLicensed = this._licenseService.IsLicensed(HttpContext.Current.Request.Url.Host); if (!isLicensed && refundPaymentRequest.Order.OrderTotal > 5.00M) { result.AddError("The trial license can be used to submit order of $5.00 or less. Please purchase a full license at our website."); return result; } string transactionId = refundPaymentRequest.Order.CaptureTransactionId; // Create the Payflow Data Objects. // Create the User data object with the required user details. UserInfo payflowUser = _payPalHelper.GetUserInfo(); // Create the Payflow Connection data object with the required connection details. PayflowConnectionData payflowConn = new PayflowConnectionData(_payPalHelper.GetPayflowProHost()); // Create a new Invoice data object with the Amount, Billing Address etc. details. Invoice invoice = new Invoice(); // Set Amount. PayPal.Payments.DataObjects.Currency refundAmount = new PayPal.Payments.DataObjects.Currency(refundPaymentRequest.AmountToRefund); invoice.Amt = refundAmount; invoice.PoNum = refundPaymentRequest.Order.Id.ToString(); invoice.InvNum = refundPaymentRequest.Order.Id.ToString(); CreditTransaction trans = new CreditTransaction(transactionId, payflowUser, payflowConn, invoice, PayflowUtility.RequestId); Response resp = trans.SubmitTransaction(); // Process the Payflow response. if (resp != null) { // Get the Transaction Response parameters. TransactionResponse trxResp = resp.TransactionResponse; if (trxResp != null) { if (trxResp.Result == 0) { if (refundPaymentRequest.IsPartialRefund) result.NewPaymentStatus = PaymentStatus.PartiallyRefunded; else result.NewPaymentStatus = PaymentStatus.Refunded; } else { result.AddError(string.Format("Refund RESULT: {0}-{1}", trxResp.Result, trxResp.RespMsg)); } } } return result; }