public HttpResponseMessage add(GiftCard post)
        {
            // Check for errors
            if (post == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null");
            }
            else if (Language.MasterPostExists(post.language_id) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The language does not exist");
            }
            else if (Currency.MasterPostExists(post.currency_code) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The currency does not exist");
            }

            // Make sure that the data is valid
            post.id = AnnytabDataValidation.TruncateString(post.id, 50);
            post.amount = AnnytabDataValidation.TruncateDecimal(post.amount, 0, 999999999999M);
            post.end_date = AnnytabDataValidation.TruncateDateTime(post.end_date);

            // Check if the gift card exists
            if (GiftCard.MasterPostExists(post.id) == true)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The id already exists");
            }

            // Add the post
            GiftCard.Add(post);

            // Return the success response
            return Request.CreateResponse<string>(HttpStatusCode.OK, "The post has been added");

        } // End of the add method
Esempio n. 2
0
 public static void Payment_Fail_Case(GiftCard GCqry)
 {
     String merchantExt = "";
     if (GCqry.CompanyID.ToString() != "00000000-0000-0000-0000-000000000000")
     {
         try
         {
             merchantExt = "Company=" + GCqry.CompanyID;
         }
         catch { }
     }
     string body = GoDineEmails.PrepareMailBodyWith("newgiftcard_failed.htm", "%NAMEFROM%", GCqry.NameFrom, "%NAMETO%", GCqry.NameTo,
     "%EMAILFROM%", GCqry.EmailFrom, "%EMAILTO%", GCqry.EmailTo, "%amount%", GCqry.GCValue.ToString("0.00"), "%code%", UTILITIES.appendChecksum(GCqry.BarCode) + merchantExt);
     GoDineEmails.SendMail(GCqry.EmailFrom, "Forgot to send a gift card to " + GCqry.NameTo + "?", body, "[email protected]; [email protected]");
 }
Esempio n. 3
0
    ///////////////////////////////////////////////////////////// PAYMENT SUCCESS
    public static void Payment_Success_Case_Global_MoneyAndSend(GiftCard giftCard, decimal fee)
    {
        log.Debug("Processing successful payment for GiftCard " + giftCard.GiftCardID);
        log.Debug("Value=" + giftCard.GCValue + ", fee=" + fee + ", barcode=" + giftCard.BarCode);
        DataClassesAlbertDataContext db = new DataClassesAlbertDataContext();

        string companyName = "";
        if (giftCard.CompanyID != "00000000-0000-0000-0000-000000000000" && giftCard.CompanyID != "")
        {
            try
            {
                companyName = (from c in db.Companies where c.UserID == new Guid(giftCard.CompanyID) select c).Single().Name;
            }
            catch { }
        }

        GoDine a = new GoDine();
        a.Insert_Money_2_GiftCard(giftCard.GCValue, giftCard.GCValue - fee, giftCard.BarCode, "Payment by credit card/paypal: " + giftCard.EmailFrom, 0); //IT IS NOT FORCED
        sendSuccessEmail(giftCard, companyName);
    }
Esempio n. 4
0
    } // End of the constructor

    #endregion

    #region Insert methods

    /// <summary>
    /// Add one gift card
    /// </summary>
    /// <param name="post">A reference to a gift card post</param>
    public static void Add(GiftCard post)
    {
        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "INSERT INTO dbo.gift_cards (id, language_id, currency_code, amount, end_date) "
            + "VALUES (@id, @language_id, @currency_code, @amount, @end_date);";

        // The using block is used to call dispose automatically even if there is a exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there is a exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", post.id);
                cmd.Parameters.AddWithValue("@language_id", post.language_id);
                cmd.Parameters.AddWithValue("@currency_code", post.currency_code);
                cmd.Parameters.AddWithValue("@amount", post.amount);
                cmd.Parameters.AddWithValue("@end_date", post.end_date);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases
                try
                {
                    // Open the connection
                    cn.Open();

                    // Execute the insert
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the Add method
        public HttpResponseMessage update(GiftCard post)
        {
            // Check for errors
            if (post == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null");
            }
            else if (Language.MasterPostExists(post.language_id) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The language does not exist");
            }
            else if (Currency.MasterPostExists(post.currency_code) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The currency does not exist");
            }

            // Make sure that the data is valid
            post.id = AnnytabDataValidation.TruncateString(post.id, 50);
            post.amount = AnnytabDataValidation.TruncateDecimal(post.amount, 0, 999999999999M);
            post.end_date = AnnytabDataValidation.TruncateDateTime(post.end_date);

            // Get the saved post
            GiftCard savedPost = GiftCard.GetOneById(post.id);

            // Check if the post exists
            if (savedPost == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The record does not exist");
            }

            // Update the post
            GiftCard.Update(post);

            // Return the success response
            return Request.CreateResponse<string>(HttpStatusCode.OK, "The update was successful");

        } // End of the update method
Esempio n. 6
0
    public static void sendSuccessEmail(GiftCard giftCard, String companyName)
    {
        // Encrypt the barcode
        string encrypted = SecurityUtils.encrypt(UTILITIES.appendChecksum(giftCard.BarCode));

        // Create parameters for the email body
        Dictionary<string, string> parameters = new Dictionary<string, string>();
        parameters.Add("baseurl", HOST_URL);
        if (companyName == "")
        {
            parameters.Add("giftCardUrl", HOST_URL + "/ViewGiftCard.aspx?GC=" + encrypted);
            parameters.Add("COMPANYNAME", "Around Town Gifts");
        }
        else
        {
            parameters.Add("giftCardUrl", HOST_URL + "/ViewCompanyGiftCard.aspx?GC=" + encrypted);
            parameters.Add("COMPANYNAME", companyName);
        }

        parameters.Add("NAMETO", giftCard.NameTo);
        parameters.Add("NAMEFROM", giftCard.NameFrom);

        string to, subject, body;

        if(giftCard.MODE.Contains("EMAIL")){
            // Email must be sent to the gift card receiver
            to = giftCard.EmailTo;
            if (companyName == "")
            {
                subject = giftCard.NameFrom + " sent you an AroundTown gift card";
                body = GoDineEmails.prepareBody("newGiftCard.htm", parameters);
            }
            else
            {
                subject = giftCard.NameFrom + " sent you a gift card for " + companyName;
                body = GoDineEmails.prepareBody("newCompanyGiftCard.htm", parameters);
            }
        }
        else
        {
            // Email must be sent to the gift card buyer
            to = giftCard.EmailFrom;
            subject = "Gift Card for " + giftCard.NameTo;
            body = GoDineEmails.prepareBody("PrintGC_Email.htm", parameters);
        }

        // Send email
        SendMail(to, subject, body, ADMIN_EMAIL);
    }
Esempio n. 7
0
 // Emails the AroundTown admin to alert them of a problem with the gift card payment
 public static void sendPaymentFailureEmail(GiftCard giftCard, string errorMessage)
 {
     GoDineEmails.SendMail(ADMIN_EMAIL, "Problem with paypal payment", "We have found the following problem with Gift Card " + giftCard.GiftCardID + " : " + errorMessage);
 }
Esempio n. 8
0
 protected string TransformDataLineIntoCsv(GiftCard gc)
 {
     GiftCardExtras extra = new GoDine().getExtraFieldsFor(gc);
     string line = UTILITIES.appendChecksum(gc.BarCode);
     line = line + "," + gc.EmailTo;
     line = line + "," + gc.EmailToValidated.ToString();
     line = line + "," + gc.TotalIn;
     line = line + "," + gc.Money;
     line = line + "," + gc.SalesDealRate;
     line = line + "," + extra.compName;
     line = line + "," + extra.salesPerson;
     line = line + "," + gc.Forced.ToString();
     line = line + "," + gc.Date.ToString("yyyy/MM/dd HH:mm:ss");
     line = line + "," + gc.MODE;
     line = line + "," + gc.EmailFrom;
     return line;
 }
Esempio n. 9
0
 internal AuthorizationBuilder WithReplacementCard(GiftCard value)
 {
     ReplacementCard = value;
     return(this);
 }
Esempio n. 10
0
    } // End of the MasterPostExists method

    /// <summary>
    /// Get one gift card based on id
    /// </summary>
    /// <param name="id">The id for the post</param>
    /// <returns>A reference to a gift card post</returns>
    public static GiftCard GetOneById(string id)
    {
        // Create the post to return
        GiftCard post = null;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "SELECT * FROM dbo.gift_cards WHERE id = @id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", id);

                // Create a MySqlDataReader
                SqlDataReader reader = null;

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Fill the reader with one row of data.
                    reader = cmd.ExecuteReader();

                    // Loop through the reader as long as there is something to read and add values
                    while (reader.Read())
                    {
                        post = new GiftCard(reader);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    // Call Close when done reading to avoid memory leakage.
                    if (reader != null)
                        reader.Close();
                }
            }
        }

        // Return the post
        return post;

    } // End of the GetOneById method
Esempio n. 11
0
    public void AddDiscount(GiftCard.Discount type)
    {
        discountRemainingTime = 5;

        this.DiscountType = type;
    }
Esempio n. 12
0
 public void RemoveGiftCard(GiftCard giftCard, Checkout checkout, Action<Checkout, Response> success, Action<RetrofitError> failure)
 {
     RemoveGiftCard(giftCard, checkout, new RetrofitCallback<Checkout>(success, failure));
 }
Esempio n. 13
0
 public static GiftCard CreateGiftCard(int giftCardID, double amount)
 {
     GiftCard giftCard = new GiftCard();
     giftCard.GiftCardID = giftCardID;
     giftCard.Amount = amount;
     return giftCard;
 }
Esempio n. 14
0
    // Here we define the basics to work
    // we use PIN == -1 if we dont want to protect it
    // GCValue is the less important information is only used for display purposes, or email purposes (if it is used)
    public long GiftCard_Create_with_code(int PIN, int forced)
    {
        var existing_barcodes = from gc in db.GiftCards select gc.BarCode;

        long newBarcode = -1;
        bool searching = true;
        while (searching){
            newBarcode = RandomNumber(0, 1 * ((long) Math.Pow(10, 11)) - 1);
            //newBarcode = RandomNumber(2 * (10 ^ 11), 3 * (10 ^ 11) - 1);
            searching = false;
            foreach (long bc_i in existing_barcodes){
                if (bc_i == newBarcode){
                    searching = true;
                    break;
                }
            }
        }
        GiftCard gcard = new GiftCard
        {
            EmailTo = "",
            EmailToValidated = false,
            Money = 0,
            TotalIn = 0,
            PassCode = PIN,
            PassCodeFails = 0,
            BarCode = newBarcode,
            Forced = forced,
            MODE = "NO INFO",
            EmailFrom = "",
            NameFrom = "",
            NameTo = "",
            DIRImgGC = "",
            DIRImgText = "",
            GCText = "",
            GCValueSTR = "",
            GCValue = 0,
            Date = DateTime.Now,
            txn_id_paypal = "",
            DisplayName = 0,
            SellerID = "00000000-0000-0000-0000-000000000000",
            CompanyID = "00000000-0000-0000-0000-000000000000",
            Activated = 0

        };
        db.GiftCards.InsertOnSubmit(gcard);
        db.SubmitChanges();
        return newBarcode;
    }
Esempio n. 15
0
    ///*****GIFTCARD FUNCTIONS*****\\\
    public GiftCardExtras getExtraFieldsFor(GiftCard gc)
    {
        GiftCardExtras response;
        String companyName = "";
        String sellerName = "";
        SalesID seller = null;
        MembershipUser mu = null;

        if (gc.CompanyID != "00000000-0000-0000-0000-000000000000")
        {
            try
            {
                companyName = (from c in db.Companies where c.UserID == new Guid(gc.CompanyID) select c).Single().Name;
            }
            catch { }
        }
        if (gc.SellerID != "00000000-0000-0000-0000-000000000000")
        {
            try
            {
                seller = (from s in db.SalesIDs where s.SellerID == new Guid(gc.SellerID) select s).Single();
                mu = Membership.GetUser(seller.UserID);
                sellerName = mu.UserName;
            }
            catch { }
        }

        response = new GiftCardExtras();
        response.salesPerson = sellerName;
        response.compName = companyName;
        return response;
    }
        /// <summary>
        /// Prepare gift card usage history search model
        /// </summary>
        /// <param name="searchModel">Gift card usage history search model</param>
        /// <param name="giftCard">Gift card</param>
        /// <returns>Gift card usage history search model</returns>
        protected virtual GiftCardUsageHistorySearchModel PrepareGiftCardUsageHistorySearchModel(GiftCardUsageHistorySearchModel searchModel,
                                                                                                 GiftCard giftCard)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            if (giftCard == null)
            {
                throw new ArgumentNullException(nameof(giftCard));
            }

            searchModel.GiftCardId = giftCard.Id;

            //prepare page parameters
            searchModel.SetGridPageSize();

            return(searchModel);
        }
        /// <summary>
        /// Prepare paged gift usage history card list model
        /// </summary>
        /// <param name="searchModel">Gift card usage history search model</param>
        /// <param name="giftCard">Gift card</param>
        /// <returns>Gift card usage history list model</returns>
        public virtual GiftCardUsageHistoryListModel PrepareGiftCardUsageHistoryListModel(GiftCardUsageHistorySearchModel searchModel,
                                                                                          GiftCard giftCard)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            if (giftCard == null)
            {
                throw new ArgumentNullException(nameof(giftCard));
            }

            //get gift card usage history
            var usageHistory = giftCard.GiftCardUsageHistory.OrderByDescending(historyEntry => historyEntry.CreatedOnUtc).ToList();

            //prepare list model
            var model = new GiftCardUsageHistoryListModel
            {
                Data = usageHistory.PaginationByRequestModel(searchModel).Select(historyEntry =>
                {
                    //fill in model values from the entity
                    var giftCardUsageHistoryModel = new GiftCardUsageHistoryModel
                    {
                        Id                = historyEntry.Id,
                        OrderId           = historyEntry.UsedWithOrderId,
                        CustomOrderNumber = historyEntry.UsedWithOrder.CustomOrderNumber
                    };

                    //convert dates to the user time
                    giftCardUsageHistoryModel.CreatedOn = _dateTimeHelper.ConvertToUserTime(historyEntry.CreatedOnUtc, DateTimeKind.Utc);

                    //fill in additional values (not existing in the entity)
                    giftCardUsageHistoryModel.UsedValue = _priceFormatter.FormatPrice(historyEntry.UsedValue, true, false);

                    return(giftCardUsageHistoryModel);
                }),
                Total = usageHistory.Count
            };

            return(model);
        }
 private void AddIndexedProperties(CommercePipelineExecutionContext context, EntityView documentView, GiftCard giftCard)
 {
     documentView.Properties.Add(new ViewProperty
     {
         Name     = "EntityUniqueId",
         RawValue = giftCard.UniqueId.ToString()
     });
     documentView.Properties.Add(new ViewProperty
     {
         Name     = "EntityId",
         RawValue = giftCard.Id
     });
     documentView.Properties.Add(new ViewProperty
     {
         Name     = "GiftCardCode",
         RawValue = giftCard.GiftCardCode
     });
     documentView.Properties.Add(new ViewProperty
     {
         Name     = "ActivationDate",
         RawValue = giftCard.ActivationDate
     });
     documentView.Properties.Add(new ViewProperty
     {
         Name     = "Balance",
         RawValue = giftCard.Balance.Amount
     });
     documentView.Properties.Add(new ViewProperty
     {
         Name     = "OriginalAmount",
         RawValue = giftCard.OriginalAmount.Amount
     });
     documentView.Properties.Add(new ViewProperty
     {
         Name     = "DateCreated",
         RawValue = giftCard.DateCreated
     });
     documentView.Properties.Add(new ViewProperty
     {
         Name     = "DateUpdated",
         RawValue = giftCard.DateUpdated
     });
     documentView.Properties.Add(new ViewProperty
     {
         Name     = "ArtifactStoreId",
         RawValue = context.CommerceContext.Environment.ArtifactStoreId
     });
 }
Esempio n. 19
0
        public IActionResult Preview(GiftCard giftCard, string toDo)
        {
            if (giftCard.Shipping.FirstName == null)
            {
                ModelState.AddModelError("Shipping.FirstName", "Enter a shipping first name.");
            }

            if (giftCard.Shipping.LastName == null)
            {
                ModelState.AddModelError("Shipping.LastName", "Enter a shipping last name.");
            }

            if (giftCard.Shipping.Address == null)
            {
                ModelState.AddModelError("Shipping.Address", "Enter a shipping address.");
            }

            if (giftCard.Shipping.City == null)
            {
                ModelState.AddModelError("Shipping.City", "Enter a shipping city.");
            }

            if (giftCard.Shipping.State == "0")
            {
                ModelState.AddModelError("Shipping.State", "Enter a shipping state.");
            }

            if (giftCard.Shipping.Postal == null)
            {
                ModelState.AddModelError("Shipping.Postal", "Enter a shipping postal code.");
            }



            if (giftCard.Billing.FirstName == null)
            {
                ModelState.AddModelError("Billing.FirstName", "Enter a Billing first name.");
            }

            if (giftCard.Billing.LastName == null)
            {
                ModelState.AddModelError("Billing.LastName", "Enter a Billing last name.");
            }

            if (giftCard.Billing.Address == null)
            {
                ModelState.AddModelError("Billing.Address", "Enter a Billing address.");
            }

            if (giftCard.Billing.City == null)
            {
                ModelState.AddModelError("Billing.City", "Enter a Billing city.");
            }

            if (giftCard.Billing.State == "0")
            {
                ModelState.AddModelError("Billing.State", "Enter a Billing state.");
            }

            if (giftCard.Billing.Postal == null)
            {
                ModelState.AddModelError("Billing.Postal", "Enter a Billing postal code.");
            }
            if (giftCard.Billing.Phone == null)
            {
                ModelState.AddModelError("Billing.Phone", "Enter a Billing phone.");
            }

            Regex emailRegEx = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");

            if (giftCard.Billing.Email == null)
            {
                ModelState.AddModelError("Billing.Email", "Enter an email address.");
            }
            else if (!emailRegEx.Match(giftCard.Billing.Email).Success)
            {
                ModelState.AddModelError("Billing.Email", "Enter a valid email address.");
            }



            if (giftCard.Information.ShippingType == 0)
            {
                ModelState.AddModelError("Information.ShippingType", "Enter a shipping type.");
            }
            else if (giftCard.Information.ShippingType == 3)
            {
                giftCard.Information.ShippingCost    = 8;
                giftCard.Information.ShippingDisplay = "USPS 2-3 Days";
                giftCard.Total = giftCard.Amount + giftCard.Information.ShippingCost;
            }
            else if (giftCard.Information.ShippingType == 2)
            {
                giftCard.Information.ShippingCost    = 0;
                giftCard.Information.ShippingDisplay = "USPS Parcel";
                giftCard.Total = giftCard.Amount + giftCard.Information.ShippingCost;
            }
            else if (giftCard.Information.ShippingType == 1)
            {
                giftCard.Information.ShippingCost    = 0;
                giftCard.Information.ShippingDisplay = "Pickup";
                giftCard.Total = giftCard.Amount + giftCard.Information.ShippingCost;
            }


            if (giftCard.Information.SpecialInstructions == null)
            {
                giftCard.Information.SpecialInstructions = "N/A";
            }

            if (giftCard.Information.GiftMsg == null)
            {
                giftCard.Information.GiftMsg = "N/A";
            }


            if (toDo == "Back")
            {
                //adding giftCard to this makes the url a mess. This would however post back their original input.
                return(RedirectToAction("Index"));
            }
            else if (toDo == "Continue")
            {
                if (ModelState.IsValid)
                {
                    var mygiftcardcart = _context.GiftCardCart.Where(Uniq => Uniq.UniqueIdentifier == giftCard.UniqueIdentifier).FirstOrDefault();
                    if (mygiftcardcart != null)
                    {
                        //testWebsite.Name = "Test Website Updated";

                        mygiftcardcart.ShippingCost = giftCard.Information.ShippingCost;
                        mygiftcardcart.ShippingType = giftCard.Information.ShippingType;

                        mygiftcardcart.ShippingFirstName = giftCard.Shipping.FirstName;
                        mygiftcardcart.ShippingLastName  = giftCard.Shipping.LastName;

                        if (giftCard.Shipping.Apt != null)
                        {
                            mygiftcardcart.ShippingAddress1 = giftCard.Shipping.Address + " " + giftCard.Shipping.Apt;
                        }
                        else
                        {
                            mygiftcardcart.ShippingAddress1 = giftCard.Shipping.Address;
                        }

                        mygiftcardcart.ShippingCity       = giftCard.Shipping.City;
                        mygiftcardcart.ShippingState      = giftCard.Shipping.State;
                        mygiftcardcart.ShippingPostalCode = giftCard.Shipping.Postal;
                        mygiftcardcart.ShippingPhone      = giftCard.Shipping.Phone;
                        mygiftcardcart.ShippingEmail      = giftCard.Shipping.Email;

                        mygiftcardcart.BillingFirstName = giftCard.Billing.FirstName;
                        mygiftcardcart.BillingLastName  = giftCard.Billing.LastName;


                        if (giftCard.Billing.Apt != null)
                        {
                            mygiftcardcart.BillingAddress1 = giftCard.Billing.Address + " " + giftCard.Billing.Apt;
                        }
                        else
                        {
                            mygiftcardcart.BillingAddress1 = giftCard.Billing.Address;
                        }

                        //mygiftcardcart.BillingAddress1 = giftCard.Billing.Address;

                        mygiftcardcart.BillingCity       = giftCard.Billing.City;
                        mygiftcardcart.BillingState      = giftCard.Billing.State;
                        mygiftcardcart.BillingPostalCode = giftCard.Billing.Postal;
                        mygiftcardcart.BillingPhone      = giftCard.Billing.Phone;
                        mygiftcardcart.BillingEmail      = giftCard.Billing.Email;

                        mygiftcardcart.Message             = giftCard.Information.GiftMsg;
                        mygiftcardcart.SpecialInstructions = giftCard.Information.SpecialInstructions;

                        mygiftcardcart.OrderTotal = giftCard.Total.Value;


                        //_context.GiftCardCart.Remove(mygiftcardcart);

                        _context.SaveChanges();
                    }


                    return(View("Preview", giftCard));
                }

                return(View("Checkout", giftCard));
                //return RedirectToAction("Checkout", giftCard);
            }

            return(View("Index"));
        }
Esempio n. 20
0
 public int Create(GiftCard giftCard)
 {
     db.GiftCards.Add(giftCard);
     db.SaveChanges();
     return(giftCard.Id);
 }
        /// <summary>
        /// Initializes the specified gift card.
        /// </summary>
        /// <param name="giftCard">The gift card.</param>
        public virtual void Initialize(GiftCard giftCard)
        {
            Assert.ArgumentNotNull(giftCard, "giftCard");

            this.ExternalId = giftCard.ExternalId;
            this.Name = giftCard.Name;
            this.CustomerId = giftCard.CustomerId;
            this.ShopName = giftCard.ShopName;
            this.CurrencyCode = giftCard.CurrencyCode;
            this.Balance = giftCard.Balance;
            this.FormattedBalance = giftCard.Balance.ToCurrency(StorefrontConstants.Settings.DefaultCurrencyCode);
            this.OriginalAmount = giftCard.OriginalAmount.ToCurrency(StorefrontConstants.Settings.DefaultCurrencyCode);
            this.Description = giftCard.Description;
        }
Esempio n. 22
0
    /// <summary>
    /// This method read the GIFTCDS.TXT file and fill List<GiftCard>, List<Amenity> depends on which form it it call.
    /// </summary>
    /// <param name="clist"> List of GiftCard objects </param>
    /// <param name="alist"> List of Amenity objects</param>
    public static void getDataCards(List<GiftCard> clist)
    {
        try
        {
            string[] files = Directory.GetFiles("C:\\", "*.TXT");
            var filePath = GetFilePath(giftcardFile);
            if (File.Exists(filePath))
            {
                StreamReader sr = new StreamReader(filePath);

                string line;
                //read file till EOF
                while ((line = sr.ReadLine()) != null)
                {
                    GiftCard currentCard = new GiftCard();

                    //put all tokens into an array to have better access to them individually
                    string[] words = line.Split('|');

                    //assign to giftcard the properties from file that was read
                    currentCard.Voyage = words[0] != " " ? words[0].Trim().ToString() : " ";
                    currentCard.Saildate = words[1] != " " ? FixDate(words[1].Trim().ToString()) : " ";
                    currentCard.Deliverydate = words[2] != " " ? FixDate(words[2].Trim().ToString()) : " ";
                    currentCard.Amenity = words[3] != " " ? words[3].Trim().ToString() : " ";
                    // this is because if Qty is text then the sort on AllGiftCards dont work correct.
                    int tmpQty = 0;
                    if (words[4] != null) { int.TryParse(words[4].ToString(), out tmpQty); } currentCard.Qty = tmpQty;
                    currentCard.Compliments = words[5] != " " ? words[5].Trim().ToString() : " ";
                    currentCard.Message = words[6] != " " ? words[6].Trim().ToString() : " ";
                    currentCard.Cabin = words[7] != " " ? words[7].Trim().ToString() : " ";
                    currentCard.firstPaxFirst = words[8] != " " ? words[8].Trim().ToString() : " ";
                    currentCard.firstPaxLast = words[9] != " " ? words[9].Trim().ToString() : " ";
                    currentCard.secndPaxFirst = words[10] != " " ? words[10].Trim().ToString() : " ";
                    currentCard.secndPaxLast = words[11] != " " ? words[11].Trim().ToString() : " ";
                    currentCard.thirdPaxFirst = words[12] != " " ? words[12].Trim().ToString() : " ";
                    currentCard.thirdPaxLast = words[13] != " " ? words[13].Trim().ToString() : " ";
                    currentCard.fourthPaxFirst = words[14] != " " ? words[14].Trim().ToString() : " ";
                    currentCard.fourthPaxLast = words[15] != " " ? words[15].Trim().ToString() : " ";
                    currentCard.Ship = words[16] != " " ? words[16].Trim().ToString() : " ";
                    currentCard.Type = words[17] != " " ? words[17].Trim().ToString() : " ";
                    currentCard.DeliveryType = words[18] != " " ? words[18].Trim().ToString() : " ";
                    currentCard.DRoom = words[19] != " " ? words[19].Trim().ToString() : " ";
                    currentCard.Seating = words[20] != " " ? words[20].Trim().ToString() : " ";
                    currentCard.Table = words[21] != " " ? words[21].Trim().ToString() : " ";

                    // Add the new card to the list
                    clist.Add(currentCard);

                }// end while

                // close the file
                sr.Close();

            }//end if
            else
            {
                throw new FileNotFoundException("The file " + giftcardFile + " could not be found");
            }//end else

        }//end try
         catch (FileNotFoundException ex) { ReportLog(ex.Message); }//end catch
         catch (Exception ex) { ReportLog(ex.Message); }//end catch
    }
Esempio n. 23
0
    /// <summary>
    /// This method validate the data imput, create a new gift card, 
    /// </summary>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        // Validate data input
        Boolean Voyage = UtilityClass.isValidInt(txtVoyage, lblVoyage, "*", "Insert digits!");
        Boolean Saildate = UtilityClass.isValidDate(txtSilingDate, lblSailingDate, "*", "Format (MM/DD/YYYY)!");
        Boolean Deliverydate = UtilityClass.isValidDate(txtDeliveryDate, lblDeliveryDate, "*", "Format (MM/DD/YYYY)!");

        Boolean DeliverydateChronolog = false;
        if (Saildate && Deliverydate)
            DeliverydateChronolog = UtilityClass.isChronologicalDate(txtSilingDate, txtDeliveryDate, lblDeliveryDate, "Chronological error!");

        Boolean Cabin = UtilityClass.isValidInt(txtStateroom, lblStateroom, "*", "Insert digits!");
        Boolean Amenity = UtilityClass.isValidText(ddlAmenity, lblAmenity, "*");
        Boolean Qty = UtilityClass.isValidInt(txtQuantity, lblQuantity, "*", "Insert digits greater than zero!");
        Boolean DeliveryType = UtilityClass.isValidText(ddlDeliverTo, lblDelivery, "*");

        Boolean dinning = false;
        Boolean seating = false;
        Boolean table = false;
        if (DeliveryType && ddlDeliverTo.SelectedItem.Text == "Dinning room")
        {
            dinning = UtilityClass.isValidText(txtDiningRoom, lblDiningRoom, "*", null);
            seating = UtilityClass.isValidText(txtSeating, lblSeating, "*", null);
            table = UtilityClass.isValidText(txtTable, lblTable, "*", null);
        }// end if

        Boolean typeflag = false;
        if((DeliveryType && ddlDeliverTo.SelectedItem.Text.CompareTo("Dinning room")!=0) || (dinning && seating && table ))
        {
            typeflag = true;
        }// end if

        Boolean Compliments = UtilityClass.isValidText(txtCompliments, lblCompliments, "*", "Insert leters or digits!");
        Boolean Message = UtilityClass.isValidText(txtMessage, lblMessage, "*", "Insert leters or digits!");

        // if all the input are correct create a new GiftCard and add it to the list.
        if (Voyage && Saildate && Deliverydate && DeliverydateChronolog && Cabin && Amenity && Qty && typeflag && Compliments && Message)
        {
            GiftCard newBe = new GiftCard(); // create a new object GiftCard

            int stateroom = int.Parse(txtStateroom.Text.Trim());

            List<Gift_Cards.GuestService.GuestView> passenger = UtilityClass.TryGetGuestInfo(stateroom, lblCreated);  // 9219,

            if (passenger == null)
            {
                lblStateroom.Text = "The stateroom does not exist!";
            }
            else
            {
                newBe.Ship = UtilityClass.shipName.Trim();
                newBe.Voyage = txtVoyage.Text.Trim();
                newBe.Saildate = txtSilingDate.Text.Trim();
                newBe.Deliverydate = txtDeliveryDate.Text.Trim();
                newBe.Amenity = ddlAmenity.SelectedItem.Text.Trim();
                newBe.Cabin = txtStateroom.Text.Trim();
                //find the amenity type and update it in the GiftCard
                newBe.Type = Amenities.Find((t) => t.amenity == newBe.Amenity).type;

                newBe.Qty = int.Parse(txtQuantity.Text);
                newBe.Compliments = txtCompliments.Text;
                newBe.Message = txtMessage.Text;
                newBe.DeliveryType = ddlDeliverTo.SelectedItem.Text;
                newBe.Cabin = txtStateroom.Text;

                if (dinning && seating && table)
                {
                    newBe.DRoom = txtDiningRoom.Text;
                    newBe.Table = txtTable.Text;
                    newBe.Seating = txtSeating.Text;
                }// end if

                // set the names of the passengers
                newBe.setNamens(passenger);

                this.Cards.Add(newBe);// add the new GiftCard to the list

                //Apend the new gift card to the end of the file
                if (this.Cards.Count == 1)
                {
                    UtilityClass.overrideGiftCardFile(this.Cards);
                }
                else
                {
                    try
                    {
                        //Apend the new gift card to the end of the file
                        var filePath = UtilityClass.GetFilePath(UtilityClass.giftcardFile);
                        using (StreamWriter sw = File.AppendText(filePath))
                        {
                            sw.WriteLine(newBe.toStringToFile()); sw.Close(); sw.Dispose();
                        }// end using
                    }
                    catch (Exception ex) { UtilityClass.ReportLog(ex.Message); }//end catch
                }

                //Create a list with the new GiftCard and send it to print.
                List<GiftCard> toPrint = new List<GiftCard>();
                toPrint.Add(this.Cards[this.Cards.Count - 1]);
                Session["newGiftCard"] = toPrint;
                lblCreated.Text = "Gift Card succesfully created!";

                //Set to unvisible Dinning Room, Table, and Seating.
                this.toUnvisible();

            } // end if (newBe != null)

        }// end if(Voyage && Saildate && ------ )
    }
Esempio n. 24
0
    } // End of the Add method

    #endregion

    #region Update methods

    /// <summary>
    /// Update a gift card
    /// </summary>
    /// <param name="post">A reference to a gift card post</param>
    public static void Update(GiftCard post)
    {
        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "UPDATE dbo.gift_cards SET language_id = @language_id, currency_code = @currency_code, amount = @amount, "
            + "end_date = @end_date WHERE id = @id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", post.id);
                cmd.Parameters.AddWithValue("@language_id", post.language_id);
                cmd.Parameters.AddWithValue("@currency_code", post.currency_code);
                cmd.Parameters.AddWithValue("@amount", post.amount);
                cmd.Parameters.AddWithValue("@end_date", post.end_date);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Execute the update
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the Update method
Esempio n. 25
0
 public static GiftCard ToEntity(this GiftCardModel model, GiftCard destination)
 {
     return(model.MapTo(destination));
 }
        public ActionResult edit(FormCollection collection)
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get the return url
            string returnUrl = collection["returnUrl"];
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Get all the form values
            string id = collection["txtId"];
            Int32 language_id = Convert.ToInt32(collection["selectLanguage"]);
            string currency_code = collection["selectCurrency"];
            decimal amount = 0;
            decimal.TryParse(collection["txtAmount"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out amount);
            DateTime end_date = Convert.ToDateTime(collection["txtEndDate"]);

            // Get translated texts
            KeyStringList tt = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");

            // Get the gift card
            GiftCard giftCard = GiftCard.GetOneById(id);
            bool postExists = true;

            // Check if the gift card exists
            if (giftCard == null)
            {
                // Create an empty gift card
                giftCard = new GiftCard();
                postExists = false;
            }

            // Update values
            giftCard.id = id;
            giftCard.language_id = language_id;
            giftCard.currency_code = currency_code;
            giftCard.amount = amount;
            giftCard.end_date = AnnytabDataValidation.TruncateDateTime(end_date);

            // Create a error message
            string errorMessage = string.Empty;

            if (giftCard.id.Length == 0 || giftCard.id.Length > 50)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_certain_length"), tt.Get("id"), "1", "50") + "<br/>";
            }
            if (giftCard.language_id == 0)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_select_value"), tt.Get("language").ToLower()) + "<br/>";
            }
            if (giftCard.currency_code == "")
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_select_value"), tt.Get("currency").ToLower()) + "<br/>";
            }
            if (giftCard.amount < 0 || giftCard.amount > 999999999999M)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_range"), tt.Get("amount"), "999 999 999 999") + "<br/>";
            }

            // Check if there is errors
            if (errorMessage == string.Empty)
            {
                // Check if we should add or update the gift card
                if (postExists == false)
                {
                    // Add the gift card
                    GiftCard.Add(giftCard);
                }
                else
                {
                    // Update the gift card
                    GiftCard.Update(giftCard);
                }

                // Redirect the user to the list
                return Redirect("/admin_gift_cards" + returnUrl);
            }
            else
            {
                // Set form values
                ViewBag.ErrorMessage = errorMessage;
                ViewBag.TranslatedTexts = tt;
                ViewBag.Languages = Language.GetAll(currentDomain.back_end_language, "id", "ASC");
                ViewBag.GiftCard = giftCard;
                ViewBag.ReturnUrl = returnUrl;

                // Return the edit view
                return View("edit");
            }

        } // End of the edit method
Esempio n. 27
0
        public IActionResult Receipt(GiftCard giftCard, string toDo)
        {
            if (giftCard.Information.SpecialInstructions == null)
            {
                giftCard.Information.SpecialInstructions = "N/A";
            }

            if (giftCard.Information.GiftMsg == null)
            {
                giftCard.Information.GiftMsg = "N/A";
            }



            if (giftCard.Card.CardType == "0")
            {
                ModelState.AddModelError("Card.CardType", "Enter an card type.");
            }

            Regex cardValid = new Regex(@"^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$");

            if (giftCard.Card.CardNumber == null || giftCard.Card.CardNumber == 0)
            {
                ModelState.AddModelError("Card.CardNumber", "Enter an card number.");
            }
            else if (!cardValid.Match(giftCard.Card.CardNumber.Value.ToString()).Success)
            {
                ModelState.AddModelError("Card.CardNumber", "Enter a valid card number.");
            }


            if (giftCard.Card.CardMonth == 0)
            {
                ModelState.AddModelError("Card.CardMonth", "Enter a expiration month.");
            }

            if (giftCard.Card.CardYear == 0)
            {
                ModelState.AddModelError("Card.CardYear", "Enter a expiration year.");
            }

            if (giftCard.Card.CardYear == DateTime.Now.Year && giftCard.Card.CardMonth < DateTime.Now.Month)
            {
                ModelState.AddModelError("Card.CardMonth", "Your card has expired.");
            }



            //delete any one hour old. would be bad to put it here say if someone took 1 hour to buy their giftcard.

            DateTime hourago   = DateTime.Now.AddHours(-1);
            var      oldstatus = _context.GiftCardCart.Where(Dates => Dates.DateCreated < hourago).ToList();

            if (oldstatus != null)
            {
                foreach (var oldcart in oldstatus)
                {
                    oldcart.Status           = 2;
                    oldcart.UniqueIdentifier = null;
                }
            }



            if (toDo == "Back")
            {
                //couldn't get this to work.
                //return RedirectToAction("Checkout");
                //return View("Checkout", giftCard);
                return(RedirectToAction("Index"));
            }
            else if (toDo == "Purchase")
            {
                if (ModelState.IsValid)
                {
                    var mygiftcardcart = _context.GiftCardCart.Where(Uniq => Uniq.UniqueIdentifier == giftCard.UniqueIdentifier).FirstOrDefault();
                    if (mygiftcardcart != null)
                    {
                        //testWebsite.Name = "Test Website Updated";

                        mygiftcardcart.Status           = 1;
                        mygiftcardcart.CreditCardType   = giftCard.Card.CardType;
                        mygiftcardcart.UniqueIdentifier = null;


                        //_context.GiftCardCart.Remove(mygiftcardcart);

                        _context.SaveChanges();
                    }



                    Random random   = new Random();
                    int    confirm1 = random.Next(10000, 99999);
                    int    confirm2 = random.Next(10000, 99999);
                    giftCard.ConfirmationCode = confirm1.ToString() + "-" + confirm2.ToString();

                    return(View("Receipt", giftCard));
                }

                return(View("Preview", giftCard));
            }

            return(View("Index"));
        }
        /// <summary>
        /// Places an order
        /// </summary>
        /// <param name="processPaymentRequest">Process payment request</param>
        /// <returns>Place order result</returns>
        public override PlaceOrderResult PlaceOrder(ProcessPaymentRequest processPaymentRequest)
        {
            //think about moving functionality of processing recurring orders (after the initial order was placed) to ProcessNextRecurringPayment() method
            if (processPaymentRequest == null)
                throw new ArgumentNullException("processPaymentRequest");

            var result = new PlaceOrderResult();
            try
            {
                if (processPaymentRequest.OrderGuid == Guid.Empty)
                    processPaymentRequest.OrderGuid = Guid.NewGuid();

                //prepare order details
                var details = PreparePlaceOrderDetails(processPaymentRequest);

                #region Payment workflow


                //process payment
                ProcessPaymentResult processPaymentResult = null;
                //skip payment workflow if order total equals zero
                var skipPaymentWorkflow = details.OrderTotal == decimal.Zero;
                if (!skipPaymentWorkflow)
                {
                    var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(processPaymentRequest.PaymentMethodSystemName);
                    if (paymentMethod == null)
                        throw new NopException("Payment method couldn't be loaded");

                    //ensure that payment method is active
                    if (!paymentMethod.IsPaymentMethodActive(_paymentSettings))
                        throw new NopException("Payment method is not active");

                    if (!processPaymentRequest.IsRecurringPayment)
                    {
                        if (details.IsRecurringShoppingCart)
                        {
                            //recurring cart
                            var recurringPaymentType = _paymentService.GetRecurringPaymentType(processPaymentRequest.PaymentMethodSystemName);
                            switch (recurringPaymentType)
                            {
                                case RecurringPaymentType.NotSupported:
                                    throw new NopException("Recurring payments are not supported by selected payment method");
                                case RecurringPaymentType.Manual:
                                case RecurringPaymentType.Automatic:
                                    processPaymentResult = _paymentService.ProcessRecurringPayment(processPaymentRequest);
                                    break;
                                default:
                                    throw new NopException("Not supported recurring payment type");
                            }
                        }
                        else
                        {
                            //standard cart
                            processPaymentResult = _paymentService.ProcessPayment(processPaymentRequest);
                        }
                    }
                    else
                    {
                        if (details.IsRecurringShoppingCart)
                        {
                            //Old credit card info
                            processPaymentRequest.CreditCardType = details.InitialOrder.AllowStoringCreditCardNumber ? _encryptionService.DecryptText(details.InitialOrder.CardType) : "";
                            processPaymentRequest.CreditCardName = details.InitialOrder.AllowStoringCreditCardNumber ? _encryptionService.DecryptText(details.InitialOrder.CardName) : "";
                            processPaymentRequest.CreditCardNumber = details.InitialOrder.AllowStoringCreditCardNumber ? _encryptionService.DecryptText(details.InitialOrder.CardNumber) : "";
                            processPaymentRequest.CreditCardCvv2 = details.InitialOrder.AllowStoringCreditCardNumber ? _encryptionService.DecryptText(details.InitialOrder.CardCvv2) : "";
                            try
                            {
                                processPaymentRequest.CreditCardExpireMonth = details.InitialOrder.AllowStoringCreditCardNumber ? Convert.ToInt32(_encryptionService.DecryptText(details.InitialOrder.CardExpirationMonth)) : 0;
                                processPaymentRequest.CreditCardExpireYear = details.InitialOrder.AllowStoringCreditCardNumber ? Convert.ToInt32(_encryptionService.DecryptText(details.InitialOrder.CardExpirationYear)) : 0;
                            }
                            catch { }

                            var recurringPaymentType = _paymentService.GetRecurringPaymentType(processPaymentRequest.PaymentMethodSystemName);
                            switch (recurringPaymentType)
                            {
                                case RecurringPaymentType.NotSupported:
                                    throw new NopException("Recurring payments are not supported by selected payment method");
                                case RecurringPaymentType.Manual:
                                    processPaymentResult = _paymentService.ProcessRecurringPayment(processPaymentRequest);
                                    break;
                                case RecurringPaymentType.Automatic:
                                    //payment is processed on payment gateway site
                                    processPaymentResult = new ProcessPaymentResult();
                                    break;
                                default:
                                    throw new NopException("Not supported recurring payment type");
                            }
                        }
                        else
                        {
                            throw new NopException("No recurring products");
                        }
                    }
                }
                else
                {
                    //payment is not required
                    if (processPaymentResult == null)
                        processPaymentResult = new ProcessPaymentResult();
                    processPaymentResult.NewPaymentStatus = PaymentStatus.Paid;
                }

                if (processPaymentResult == null)
                    throw new NopException("processPaymentResult is not available");

                #endregion

                if (processPaymentResult.Success)
                {
                    #region Save order details

                    var order = new Order
                    {
                        StoreId = processPaymentRequest.StoreId,
                        OrderGuid = processPaymentRequest.OrderGuid,
                        CustomerId = details.Customer.Id,
                        CustomerLanguageId = details.CustomerLanguage.Id,
                        CustomerTaxDisplayType = details.CustomerTaxDisplayType,
                        CustomerIp = _webHelper.GetCurrentIpAddress(),
                        OrderSubtotalInclTax = details.OrderSubTotalInclTax,
                        OrderSubtotalExclTax = details.OrderSubTotalExclTax,
                        OrderSubTotalDiscountInclTax = details.OrderSubTotalDiscountInclTax,
                        OrderSubTotalDiscountExclTax = details.OrderSubTotalDiscountExclTax,
                        OrderShippingInclTax = details.OrderShippingTotalInclTax,
                        OrderShippingExclTax = details.OrderShippingTotalExclTax,
                        PaymentMethodAdditionalFeeInclTax = details.PaymentAdditionalFeeInclTax,
                        PaymentMethodAdditionalFeeExclTax = details.PaymentAdditionalFeeExclTax,
                        TaxRates = details.TaxRates,
                        OrderTax = details.OrderTaxTotal,
                        OrderTotal = details.OrderTotal,
                        RefundedAmount = decimal.Zero,
                        OrderDiscount = details.OrderDiscountAmount,
                        CheckoutAttributeDescription = details.CheckoutAttributeDescription,
                        CheckoutAttributesXml = details.CheckoutAttributesXml,
                        CustomerCurrencyCode = details.CustomerCurrencyCode,
                        CurrencyRate = details.CustomerCurrencyRate,
                        AffiliateId = details.AffiliateId,
                        OrderStatus = OrderStatus.Pending,
                        AllowStoringCreditCardNumber = processPaymentResult.AllowStoringCreditCardNumber,
                        CardType = processPaymentResult.AllowStoringCreditCardNumber ? _encryptionService.EncryptText(processPaymentRequest.CreditCardType) : string.Empty,
                        CardName = processPaymentResult.AllowStoringCreditCardNumber ? _encryptionService.EncryptText(processPaymentRequest.CreditCardName) : string.Empty,
                        CardNumber = processPaymentResult.AllowStoringCreditCardNumber ? _encryptionService.EncryptText(processPaymentRequest.CreditCardNumber) : string.Empty,
                        MaskedCreditCardNumber = _encryptionService.EncryptText(_paymentService.GetMaskedCreditCardNumber(processPaymentRequest.CreditCardNumber)),
                        CardCvv2 = processPaymentResult.AllowStoringCreditCardNumber ? _encryptionService.EncryptText(processPaymentRequest.CreditCardCvv2) : string.Empty,
                        CardExpirationMonth = processPaymentResult.AllowStoringCreditCardNumber ? _encryptionService.EncryptText(processPaymentRequest.CreditCardExpireMonth.ToString()) : string.Empty,
                        CardExpirationYear = processPaymentResult.AllowStoringCreditCardNumber ? _encryptionService.EncryptText(processPaymentRequest.CreditCardExpireYear.ToString()) : string.Empty,
                        PaymentMethodSystemName = processPaymentRequest.PaymentMethodSystemName,
                        AuthorizationTransactionId = processPaymentResult.AuthorizationTransactionId,
                        AuthorizationTransactionCode = processPaymentResult.AuthorizationTransactionCode,
                        AuthorizationTransactionResult = processPaymentResult.AuthorizationTransactionResult,
                        CaptureTransactionId = processPaymentResult.CaptureTransactionId,
                        CaptureTransactionResult = processPaymentResult.CaptureTransactionResult,
                        SubscriptionTransactionId = processPaymentResult.SubscriptionTransactionId,
                        PaymentStatus = processPaymentResult.NewPaymentStatus,
                        PaidDateUtc = null,
                        BillingAddress = details.BillingAddress,
                        ShippingAddress = details.ShippingAddress,
                        ShippingStatus = details.ShippingStatus,
                        ShippingMethod = details.ShippingMethodName,
                        PickUpInStore = details.PickUpInStore,
                        ShippingRateComputationMethodSystemName = details.ShippingRateComputationMethodSystemName,
                        CustomValuesXml = processPaymentRequest.SerializeCustomValues(),
                        VatNumber = details.VatNumber,
                        CreatedOnUtc = DateTime.UtcNow
                    };
                    _orderService.InsertOrder(order);

                    #region Promo

                    _promoService.SendConfirmedBasket(order);

                    BasketResponse basketResponse = _promoUtilities.GetBasketResponse();

                    if (basketResponse == null)
                    {
                        throw new NopException(string.Format("Failed to create PromoOrder for order: {0}", order.Id));
                    }
                    else
                    {

                        PromoOrder promoOrder = new PromoOrder()
                        {
                            RequestXml = _workContext.CurrentCustomer.GetAttribute<string>(PromoCustomerAttributeNames.PromoBasketRequest, _genericAttributeService, _storeContext.CurrentStore.Id),
                            ResponseXml = basketResponse.ToXml(),
                            OrderId = order.Id,
                            DeliveryOriginalPrice = basketResponse.DeliveryOriginalPrice
                        };

                        _promoOrderService.InsertPromoOrder(promoOrder);

                        basketResponse.Items.ForEach(bi =>
                        {
                            PromoOrderItem promoOrderItem = new PromoOrderItem()
                            {
                                LineAmount = bi.LineAmount,
                                OrderId = order.Id,
                                PromoOrderId = promoOrder.Id,
                                IsDelivery = bi.IsDelivery,
                                ProductCode = bi.ProductCode,
                                VariantCode = bi.VariantCode,
                                LinePromotionDiscount = bi.LinePromotionDiscount,
                                Barcode = bi.Barcode,
                                Generated = bi.Generated,
                                ManualDiscount = bi.ManualDiscount,
                                OriginalAmount = bi.OriginalAmount,
                                OriginalPrice = bi.OriginalPrice,
                                OriginalQuantity = bi.OriginalQuantity,
                                Price = bi.Price,
                                ProductDescription = bi.ProductDescription,
                                Quantity = bi.Quantity,
                                SplitFromLineId = bi.SplitFromLineId,
                                TotalDiscount = bi.TotalDiscount,
                                TotalIssuedPoints = bi.TotalIssuedPoints
                            };

                            promoOrder.PromoOrderItems.Add(promoOrderItem);
                            _promoOrderService.UpdatePromoOrder(promoOrder);

                            bi.AppliedPromotions.ForEach(ap =>
                            {
                                string promotionTypeDisplay = string.Empty;
                                string promotionType = string.Empty;
                                string promotionName = string.Empty;
                                string promotionDisplayText = string.Empty;
                                var appliedPromo = (from sap in basketResponse.Summary.AppliedPromotions where sap.PromotionId == ap.PromotionId select sap).FirstOrDefault();
                                if (appliedPromo != null)
                                {
                                    promotionName = appliedPromo.PromotionName;
                                    promotionType = appliedPromo.PromotionType;
                                    promotionTypeDisplay = appliedPromo.PromotionTypeDisplay;
                                    promotionDisplayText = appliedPromo.DisplayText;
                                }

                                PromoOrderItemPromotion promoOrderItemPromotion = new PromoOrderItemPromotion()
                                {
                                    BasketLevel = ap.BasketLevelPromotion,
                                    DeliveryLevel = ap.DeliveryLevelPromotion,
                                    DiscountAmount = ap.DiscountAmount,
                                    ForLineId = ap.AssociatedLine,
                                    Instance = ap.InstanceId,
                                    PointsIssued = ap.PointsIssued,
                                    PromotionId = ap.PromotionId,
                                    DisplayText = promotionDisplayText,
                                    PromotionTypeDisplay = promotionTypeDisplay,
                                    PromotionName = promotionName,
                                    PromotionType = promotionType,
                                    ExternalIdentifier = ap.ExternalIdentifier,
                                    ReportingGroupCode = ap.ReportingGroupCode
                                };
                                promoOrderItem.PromoOrderItemPromotions.Add(promoOrderItemPromotion);
                                _promoOrderService.UpdatePromoOrder(promoOrder);
                            });
                        });

                        basketResponse.Coupons.ForEach(c =>
                            {
                                PromoOrderCoupon promoOrderCoupon = new PromoOrderCoupon()
                                {
                                    CouponCode = c.CouponCode,
                                    Issued = c.Issued,
                                    OrderId = order.Id,
                                    PromoOrderId = promoOrder.Id,
                                    CouponName = c.CouponName,
                                    IssuedConfirmed = c.IssuedConfirmed,
                                    DisplayText = c.DisplayText
                                };
                                promoOrder.PromoOrderCoupons.Add(promoOrderCoupon);
                                _promoOrderService.UpdatePromoOrder(promoOrder);
                            });
                    }

                    #region clean up

                    Customer customer = _workContext.CurrentCustomer;

                    // basket guid
                    _genericAttributeService.SaveAttribute<string>(customer, PromoCustomerAttributeNames.PromoBasketUniqueReference, null, _storeContext.CurrentStore.Id);

                    // basket response
                    _genericAttributeService.SaveAttribute<string>(customer, PromoCustomerAttributeNames.PromoBasketResponse, null, _storeContext.CurrentStore.Id);

                    // basket request
                    _genericAttributeService.SaveAttribute<string>(customer, PromoCustomerAttributeNames.PromoBasketRequest, null, _storeContext.CurrentStore.Id);

                    // coupon code
                    _genericAttributeService.SaveAttribute<string>(customer, SystemCustomerAttributeNames.DiscountCouponCode, null);

                    #endregion

                    #endregion

                    result.PlacedOrder = order;

                    if (!processPaymentRequest.IsRecurringPayment)
                    {
                        //move shopping cart items to order items
                        foreach (var sc in details.Cart)
                        {
                            var basketResponseItems = basketResponse.FindBasketResponseItems(sc);

                            if (basketResponseItems == null)
                            {
                                // TODO: handle this error
                            }
                            else
                            {
                                //prices
                                decimal taxRate;
                                decimal discountAmount = basketResponseItems.Sum(i => i.LinePromotionDiscount);
                                decimal scUnitPrice = _priceCalculationService.GetUnitPrice(sc);
                                decimal scSubTotal = basketResponseItems.Sum(i => i.LineAmount);
                                decimal scUnitPriceInclTax = _taxService.GetProductPrice(sc.Product, scUnitPrice, true, details.Customer, out taxRate);
                                decimal scUnitPriceExclTax = _taxService.GetProductPrice(sc.Product, scUnitPrice, false, details.Customer, out taxRate);
                                decimal scSubTotalInclTax = _taxService.GetProductPrice(sc.Product, scSubTotal, true, details.Customer, out taxRate);
                                decimal scSubTotalExclTax = _taxService.GetProductPrice(sc.Product, scSubTotal, false, details.Customer, out taxRate);

                                decimal discountAmountInclTax = _taxService.GetProductPrice(sc.Product, discountAmount, true, details.Customer, out taxRate);
                                decimal discountAmountExclTax = _taxService.GetProductPrice(sc.Product, discountAmount, false, details.Customer, out taxRate);

                                //attributes
                                string attributeDescription = _productAttributeFormatter.FormatAttributes(sc.Product, sc.AttributesXml, details.Customer);

                                var itemWeight = _shippingService.GetShoppingCartItemWeight(sc);

                                //save order item
                                var orderItem = new OrderItem
                                {
                                    OrderItemGuid = Guid.NewGuid(),
                                    Order = order,
                                    ProductId = sc.ProductId,
                                    UnitPriceInclTax = scUnitPriceInclTax,
                                    UnitPriceExclTax = scUnitPriceExclTax,
                                    PriceInclTax = scSubTotalInclTax,
                                    PriceExclTax = scSubTotalExclTax,
                                    OriginalProductCost = _priceCalculationService.GetProductCost(sc.Product, sc.AttributesXml),
                                    AttributeDescription = attributeDescription,
                                    AttributesXml = sc.AttributesXml,
                                    Quantity = sc.Quantity,
                                    DiscountAmountInclTax = discountAmountInclTax,
                                    DiscountAmountExclTax = discountAmountExclTax,
                                    DownloadCount = 0,
                                    IsDownloadActivated = false,
                                    LicenseDownloadId = 0,
                                    ItemWeight = itemWeight,
                                    RentalStartDateUtc = sc.RentalStartDateUtc,
                                    RentalEndDateUtc = sc.RentalEndDateUtc
                                };
                                order.OrderItems.Add(orderItem);
                                _orderService.UpdateOrder(order);

                                //gift cards
                                if (sc.Product.IsGiftCard)
                                {
                                    string giftCardRecipientName, giftCardRecipientEmail,
                                        giftCardSenderName, giftCardSenderEmail, giftCardMessage;
                                    _productAttributeParser.GetGiftCardAttribute(sc.AttributesXml,
                                        out giftCardRecipientName, out giftCardRecipientEmail,
                                        out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage);

                                    for (int i = 0; i < sc.Quantity; i++)
                                    {
                                        var gc = new GiftCard
                                        {
                                            GiftCardType = sc.Product.GiftCardType,
                                            PurchasedWithOrderItem = orderItem,
                                            Amount = scUnitPriceExclTax,
                                            IsGiftCardActivated = false,
                                            GiftCardCouponCode = _giftCardService.GenerateGiftCardCode(),
                                            RecipientName = giftCardRecipientName,
                                            RecipientEmail = giftCardRecipientEmail,
                                            SenderName = giftCardSenderName,
                                            SenderEmail = giftCardSenderEmail,
                                            Message = giftCardMessage,
                                            IsRecipientNotified = false,
                                            CreatedOnUtc = DateTime.UtcNow
                                        };
                                        _giftCardService.InsertGiftCard(gc);
                                    }
                                }

                                //inventory
                                _productService.AdjustInventory(sc.Product, -sc.Quantity, sc.AttributesXml);
                            }
                        }

                        //clear shopping cart
                        details.Cart.ToList().ForEach(sci => _shoppingCartService.DeleteShoppingCartItem(sci, false));
                    }
                    else
                    {
                        //recurring payment
                        var initialOrderItems = details.InitialOrder.OrderItems;
                        foreach (var orderItem in initialOrderItems)
                        {
                            //save item
                            var newOrderItem = new OrderItem
                            {
                                OrderItemGuid = Guid.NewGuid(),
                                Order = order,
                                ProductId = orderItem.ProductId,
                                UnitPriceInclTax = orderItem.UnitPriceInclTax,
                                UnitPriceExclTax = orderItem.UnitPriceExclTax,
                                PriceInclTax = orderItem.PriceInclTax,
                                PriceExclTax = orderItem.PriceExclTax,
                                OriginalProductCost = orderItem.OriginalProductCost,
                                AttributeDescription = orderItem.AttributeDescription,
                                AttributesXml = orderItem.AttributesXml,
                                Quantity = orderItem.Quantity,
                                DiscountAmountInclTax = orderItem.DiscountAmountInclTax,
                                DiscountAmountExclTax = orderItem.DiscountAmountExclTax,
                                DownloadCount = 0,
                                IsDownloadActivated = false,
                                LicenseDownloadId = 0,
                                ItemWeight = orderItem.ItemWeight,
                                RentalStartDateUtc = orderItem.RentalStartDateUtc,
                                RentalEndDateUtc = orderItem.RentalEndDateUtc
                            };
                            order.OrderItems.Add(newOrderItem);
                            _orderService.UpdateOrder(order);

                            //gift cards
                            if (orderItem.Product.IsGiftCard)
                            {
                                string giftCardRecipientName, giftCardRecipientEmail,
                                    giftCardSenderName, giftCardSenderEmail, giftCardMessage;
                                _productAttributeParser.GetGiftCardAttribute(orderItem.AttributesXml,
                                    out giftCardRecipientName, out giftCardRecipientEmail,
                                    out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage);

                                for (int i = 0; i < orderItem.Quantity; i++)
                                {
                                    var gc = new GiftCard
                                    {
                                        GiftCardType = orderItem.Product.GiftCardType,
                                        PurchasedWithOrderItem = newOrderItem,
                                        Amount = orderItem.UnitPriceExclTax,
                                        IsGiftCardActivated = false,
                                        GiftCardCouponCode = _giftCardService.GenerateGiftCardCode(),
                                        RecipientName = giftCardRecipientName,
                                        RecipientEmail = giftCardRecipientEmail,
                                        SenderName = giftCardSenderName,
                                        SenderEmail = giftCardSenderEmail,
                                        Message = giftCardMessage,
                                        IsRecipientNotified = false,
                                        CreatedOnUtc = DateTime.UtcNow
                                    };
                                    _giftCardService.InsertGiftCard(gc);
                                }
                            }

                            //inventory
                            _productService.AdjustInventory(orderItem.Product, -orderItem.Quantity, orderItem.AttributesXml);
                        }
                    }

                    //discount usage history
                    // TODO: replace with Promo discount usage history?

                    //gift card usage history
                    if (!processPaymentRequest.IsRecurringPayment)
                        if (details.AppliedGiftCards != null)
                            foreach (var agc in details.AppliedGiftCards)
                            {
                                decimal amountUsed = agc.AmountCanBeUsed;
                                var gcuh = new GiftCardUsageHistory
                                {
                                    GiftCard = agc.GiftCard,
                                    UsedWithOrder = order,
                                    UsedValue = amountUsed,
                                    CreatedOnUtc = DateTime.UtcNow
                                };
                                agc.GiftCard.GiftCardUsageHistory.Add(gcuh);
                                _giftCardService.UpdateGiftCard(agc.GiftCard);
                            }

                    //reward points history
                    if (details.RedeemedRewardPointsAmount > decimal.Zero)
                    {
                        details.Customer.AddRewardPointsHistoryEntry(-details.RedeemedRewardPoints,
                            string.Format(_localizationService.GetResource("RewardPoints.Message.RedeemedForOrder", order.CustomerLanguageId), order.Id),
                            order,
                            details.RedeemedRewardPointsAmount);
                        _customerService.UpdateCustomer(details.Customer);
                    }

                    //recurring orders
                    if (!processPaymentRequest.IsRecurringPayment && details.IsRecurringShoppingCart)
                    {
                        //create recurring payment (the first payment)
                        var rp = new RecurringPayment
                        {
                            CycleLength = processPaymentRequest.RecurringCycleLength,
                            CyclePeriod = processPaymentRequest.RecurringCyclePeriod,
                            TotalCycles = processPaymentRequest.RecurringTotalCycles,
                            StartDateUtc = DateTime.UtcNow,
                            IsActive = true,
                            CreatedOnUtc = DateTime.UtcNow,
                            InitialOrder = order,
                        };
                        _orderService.InsertRecurringPayment(rp);


                        var recurringPaymentType = _paymentService.GetRecurringPaymentType(processPaymentRequest.PaymentMethodSystemName);
                        switch (recurringPaymentType)
                        {
                            case RecurringPaymentType.NotSupported:
                                {
                                    //not supported
                                }
                                break;
                            case RecurringPaymentType.Manual:
                                {
                                    //first payment
                                    var rph = new RecurringPaymentHistory
                                    {
                                        RecurringPayment = rp,
                                        CreatedOnUtc = DateTime.UtcNow,
                                        OrderId = order.Id,
                                    };
                                    rp.RecurringPaymentHistory.Add(rph);
                                    _orderService.UpdateRecurringPayment(rp);
                                }
                                break;
                            case RecurringPaymentType.Automatic:
                                {
                                    //will be created later (process is automated)
                                }
                                break;
                            default:
                                break;
                        }
                    }

                    #endregion

                    #region Notifications & notes

                    //notes, messages
                    if (_workContext.OriginalCustomerIfImpersonated != null)
                    {
                        //this order is placed by a store administrator impersonating a customer
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = string.Format("Order placed by a store owner ('{0}'. ID = {1}) impersonating the customer.",
                                _workContext.OriginalCustomerIfImpersonated.Email, _workContext.OriginalCustomerIfImpersonated.Id),
                            DisplayToCustomer = false,
                            CreatedOnUtc = DateTime.UtcNow
                        });
                        _orderService.UpdateOrder(order);
                    }
                    else
                    {
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = "Order placed",
                            DisplayToCustomer = false,
                            CreatedOnUtc = DateTime.UtcNow
                        });
                        _orderService.UpdateOrder(order);
                    }

                    //send email notifications
                    int orderPlacedStoreOwnerNotificationQueuedEmailId = _workflowMessageService.SendOrderPlacedStoreOwnerNotification(order, _localizationSettings.DefaultAdminLanguageId);
                    if (orderPlacedStoreOwnerNotificationQueuedEmailId > 0)
                    {
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = string.Format("\"Order placed\" email (to store owner) has been queued. Queued email identifier: {0}.", orderPlacedStoreOwnerNotificationQueuedEmailId),
                            DisplayToCustomer = false,
                            CreatedOnUtc = DateTime.UtcNow
                        });
                        _orderService.UpdateOrder(order);
                    }

                    var orderPlacedAttachmentFilePath = _orderSettings.AttachPdfInvoiceToOrderPlacedEmail ?
                        _pdfService.PrintOrderToPdf(order, order.CustomerLanguageId) : null;
                    var orderPlacedAttachmentFileName = _orderSettings.AttachPdfInvoiceToOrderPlacedEmail ?
                        "order.pdf" : null;
                    int orderPlacedCustomerNotificationQueuedEmailId = _workflowMessageService
                        .SendOrderPlacedCustomerNotification(order, order.CustomerLanguageId, orderPlacedAttachmentFilePath, orderPlacedAttachmentFileName);
                    if (orderPlacedCustomerNotificationQueuedEmailId > 0)
                    {
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = string.Format("\"Order placed\" email (to customer) has been queued. Queued email identifier: {0}.", orderPlacedCustomerNotificationQueuedEmailId),
                            DisplayToCustomer = false,
                            CreatedOnUtc = DateTime.UtcNow
                        });
                        _orderService.UpdateOrder(order);
                    }

                    var vendors = GetVendorsInOrder(order);
                    foreach (var vendor in vendors)
                    {
                        int orderPlacedVendorNotificationQueuedEmailId = _workflowMessageService.SendOrderPlacedVendorNotification(order, vendor, order.CustomerLanguageId);
                        if (orderPlacedVendorNotificationQueuedEmailId > 0)
                        {
                            order.OrderNotes.Add(new OrderNote
                            {
                                Note = string.Format("\"Order placed\" email (to vendor) has been queued. Queued email identifier: {0}.", orderPlacedVendorNotificationQueuedEmailId),
                                DisplayToCustomer = false,
                                CreatedOnUtc = DateTime.UtcNow
                            });
                            _orderService.UpdateOrder(order);
                        }
                    }

                    //check order status
                    CheckOrderStatus(order);

                    //reset checkout data
                    if (!processPaymentRequest.IsRecurringPayment)
                        _customerService.ResetCheckoutData(details.Customer, processPaymentRequest.StoreId, clearCouponCodes: true, clearCheckoutAttributes: true);

                    if (!processPaymentRequest.IsRecurringPayment)
                    {
                        _customerActivityService.InsertActivity(
                            "PublicStore.PlaceOrder",
                            _localizationService.GetResource("ActivityLog.PublicStore.PlaceOrder"),
                            order.Id);
                    }

                    //raise event       
                    _eventPublisher.Publish(new OrderPlacedEvent(order));

                    if (order.PaymentStatus == PaymentStatus.Paid)
                    {
                        ProcessOrderPaid(order);
                    }
                    #endregion
                }
                else
                {
                    foreach (var paymentError in processPaymentResult.Errors)
                        result.AddError(string.Format(_localizationService.GetResource("Checkout.PaymentError"), paymentError));
                }
            }
            catch (Exception exc)
            {
                _logger.Error(exc.Message, exc);
                result.AddError(exc.Message);
            }

            #region Process errors

            string error = "";
            for (int i = 0; i < result.Errors.Count; i++)
            {
                error += string.Format("Error {0}: {1}", i + 1, result.Errors[i]);
                if (i != result.Errors.Count - 1)
                    error += ". ";
            }
            if (!String.IsNullOrEmpty(error))
            {
                //log it
                string logError = string.Format("Error while placing order. {0}", error);
                _logger.Error(logError);
            }

            #endregion

            return result;
        }
Esempio n. 29
0
 public static GiftCardModel ToModel(this GiftCard entity)
 {
     return(entity.MapTo <GiftCard, GiftCardModel>());
 }