/src/main/java/com/kawauso/base/controller/CartController.java
Java | 836 lines | 547 code | 189 blank | 100 comment | 86 complexity | 78c502598cbe0df2b94eccb58c776c3e MD5 | raw file
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package com.kawauso.base.controller;
- import com.google.gson.Gson;
- import com.influx.bean.SyncCart;
- import com.influx.bean.SyncCartItem;
- import com.kawauso.base.ConfigReader;
- import com.kawauso.base.SecurityAnnotation;
- import com.kawauso.base.Utilities.ELUtilities;
- import com.kawauso.base.Utilities.Emailer;
- import com.kawauso.base.Utilities.Encryption;
- import com.kawauso.base.Utilities.URLEncodedUtils;
- import com.kawauso.base.Utilities.URLEncodedUtils.NameValuePair;
- import com.kawauso.base.bean.*;
- import com.kawauso.base.form.CartForm;
- import com.kawauso.base.service.*;
- import org.apache.log4j.Logger;
- import org.hibernate.Query;
- import org.hibernate.SessionFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.http.MediaType;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.ModelMap;
- import org.springframework.validation.BeanPropertyBindingResult;
- import org.springframework.validation.BindingResult;
- import org.springframework.validation.Errors;
- import org.springframework.validation.ValidationUtils;
- import org.springframework.web.bind.annotation.*;
- import org.springframework.web.servlet.ModelAndView;
- import javax.servlet.http.HttpSession;
- import java.math.BigDecimal;
- import java.util.*;
- @Controller
- public class CartController {
- private static final Logger log = Logger.getLogger(CartController.class);
- @Autowired
- private CartService cartService;
- @Autowired
- private ProductService productService;
- @Autowired
- private AccountService accountService;
- @Autowired
- private UserService userService;
- @Autowired
- private LocationService locationService;
- @Autowired
- private SessionFactory sessionFactory;
- private static final int CONO = ConfigReader.getPropertyAsInt("sxe.cono");
- private static final String OPER = ConfigReader.getProperty("sxe.oper");
- @RequestMapping(value = "/cart/index", method = RequestMethod.GET)
- @SecurityAnnotation(requireLogin = true)
- public ModelAndView index(ModelMap model, HttpSession session) {
- //fetch httpSession data
- Session userSession = (Session) session.getAttribute("session");
- //not authorized
- if (userSession.getUser().isSecurityOrderCreate() != true)
- return new ModelAndView("/unauthorized", model);
- //breadcrumbs
- List<Breadcrumb> crumbs = new ArrayList<Breadcrumb>();
- crumbs.add(new Breadcrumb("Shopping Cart", "", ""));
- model.put("navTree", crumbs);
- //@todo clean up the shopping carts remove functionality... this code works in conjunction with LayoutInterceptor... not good implementation
- String cartLineErrors = (String)session.getAttribute("cartLineErrors");
- StringTokenizer st = new StringTokenizer(cartLineErrors, ";");
- org.hibernate.Session currentSession = sessionFactory.getCurrentSession();
- while (st.hasMoreTokens()){
- Query q = currentSession.createQuery("DELETE CartItem WHERE userId=:userId AND productCode=:prod");
- q.setString("userId", userSession.getUserId());
- q.setString("prod", st.nextToken());
- q.executeUpdate(); //returns # of records affected
- }
- //fetch cart
- //@todo; need to setup a one-to-one mapping in hibernate but for now this works pretty well
- //since it does fetch pricing if user is logged in
- BigDecimal subtot = BigDecimal.ZERO;
- List<CartItem> items = cartService.getCartItems(userSession.getUserId());
- for (CartItem item : items) {
- Product p = productService.getProduct(CONO, OPER, userSession.getCustomerNumber(), userSession.getShipTo(), userSession.getWarehouse(), item.getProductCode());
- //base64 encode the cartitem; still have access to prod in productDetail
- item.setProductCode(item.getProductCode());
- //figure out price - for now it's just the price of the product from sx
- item.setUnitPrice(p.getPrice());
- //attach product details to CartItem
- item.setProductDetail(p);
- subtot = subtot.add(new BigDecimal(item.getQty() * p.getPrice().doubleValue()));
- }
- model.put("items", items);
- model.put("subTotal", subtot);
- return new ModelAndView("/cart/index", model);
- }
- @RequestMapping(value = "/cart/index", method = RequestMethod.POST)
- @SecurityAnnotation(requireLogin = true)
- public ModelAndView index(@RequestParam(value = "productCode", required = false) String productCode,
- @RequestParam(value = "quantity", required = false) String quantity,
- HttpSession session) {
- ModelMap model = new ModelMap();
- //fetch httpSession data
- Session userSession = (Session) session.getAttribute("session");
- addItem(userSession.getUserId(), ELUtilities.base64Decode(productCode), quantity, false, "S", null);
- return index(model, session);
- }
- @RequestMapping(value = "/cart/checkout", method = RequestMethod.GET)
- @SecurityAnnotation(requireLogin = true)
- public ModelAndView checkout(HttpSession session) {
- Map<String, Object> model = new HashMap<String, Object>();
- //fetch httpSession data
- Session userSession = (Session) session.getAttribute("session");
- //@todo;user and session are starting to look identical; what about merging into mongodb?
- User user = userService.getUser(userSession.getUserId());
- model.put("defaultShipVia", user.getShipVia());
- //if cart is empty, send to main cart screen
- if (cartService.getCartItems(userSession.getUserId()).isEmpty() == true)
- return new ModelAndView("/cart/index", model);
- //get cart head if exists
- Cart cartData = cartService.getCart(userSession.getUserId());
- model.put("cartData", cartData);
- //fetch shipto's
- model.put("shipToList", accountService.getShipToList(CONO, OPER, userSession.getCustomerNumber(), true));
- //shipvia's
- model.put("shipViaList", cartService.getShipViaList());
- //order defaults
- model.put("orderingInfo", accountService.getOrderingInfo(CONO, OPER, userSession.getCustomerNumber()));
- //date stuff
- Calendar cal = Calendar.getInstance();
- try {
- String[] shipDateArr = cartData.getShipDate().split("/|-");
- model.put("calYear", Integer.parseInt(shipDateArr[0]));
- model.put("calMonth", Integer.parseInt(shipDateArr[1]));
- model.put("calDay", Integer.parseInt(shipDateArr[2]));
- } catch (Exception e) {
- model.put("calYear", cal.get(Calendar.YEAR));
- model.put("calMonth", cal.get(Calendar.MONTH) + 1);
- model.put("calDay", cal.get(Calendar.DATE));
- }
- //breadcrumbs
- List<Breadcrumb> crumbs = new ArrayList<Breadcrumb>();
- crumbs.add(new Breadcrumb("Shopping Cart", "/cart/index.htm", ""));
- crumbs.add(new Breadcrumb("Checkout", "", ""));
- model.put("navTree", crumbs);
- model.put("cartForm", new CartForm());
- return new ModelAndView("/cart/shipInfo", model);
- }
- @RequestMapping(value = "/cart/checkout", method = RequestMethod.POST)
- @SecurityAnnotation(requireLogin = true)
- public String checkout(@ModelAttribute("cartForm") CartForm cartForm, BindingResult result, ModelMap model, HttpSession session) {
- //fetch httpSession data
- Session userSession = (Session) session.getAttribute("session");
- //@todo;user and session are starting to look identical; what about merging into mongodb?
- User user = userService.getUser(userSession.getUserId());
- model.put("defaultShipVia", user.getShipVia());
- if (cartForm.getStep() != null && cartForm.getStep().equals("shipInfo")) {
- //fetch shipto's
- model.put("shipToList", accountService.getShipToList(CONO, OPER, userSession.getCustomerNumber(), true));
- //shipvia's
- model.put("shipViaList", cartService.getShipViaList());
- //order defaults
- Map<String, Object> orderingInfo = accountService.getOrderingInfo(CONO, OPER, userSession.getCustomerNumber());
- model.put("orderingInfo", orderingInfo);
- //date stuff
- Calendar cal = Calendar.getInstance();
- model.put("calMonth", cal.get(Calendar.MONTH) + 1); //zero-based idx
- model.put("calDay", cal.get(Calendar.DATE));
- model.put("calYear", cal.get(Calendar.YEAR));
- //breadcrumbs
- List<Breadcrumb> crumbs = new ArrayList<Breadcrumb>();
- crumbs.add(new Breadcrumb("Shopping Cart", "/cart/index.htm", ""));
- crumbs.add(new Breadcrumb("Checkout", "", ""));
- model.put("navTree", crumbs);
- //validate field data
- Errors errors = new BeanPropertyBindingResult(cartForm, "cartForm");
- ValidationUtils.rejectIfEmptyOrWhitespace(errors, "shipToName", "field.required");
- ValidationUtils.rejectIfEmptyOrWhitespace(errors, "shipToAddr1", "field.required");
- ValidationUtils.rejectIfEmptyOrWhitespace(errors, "shipToCity", "field.required");
- if (cartForm.getShipToState().trim().isEmpty() && errors.getFieldError("shipToCity").getDefaultMessage() != null)
- errors.rejectValue("shipToCity", "field.required");
- if (cartForm.getShipToZip().trim().isEmpty() && errors.getFieldError("shipToCity").getDefaultMessage() != null)
- errors.rejectValue("shipToCity", "field.required");
- if (orderingInfo.get("poReq").equals(true))
- ValidationUtils.rejectIfEmptyOrWhitespace(errors, "custPo", "field.required");
- if (orderingInfo.get("shipToReq").equals(true))
- ValidationUtils.rejectIfEmptyOrWhitespace(errors, "jobId", "field.required");
- ValidationUtils.rejectIfEmptyOrWhitespace(errors, "shipVia", "field.required");
- if (errors.getErrorCount() > 0) {
- model.put("formError", true);
- result.addAllErrors(errors);
- return "/cart/shipInfo";
- }
- //fetch existing cart id from db
- Cart cart = cartService.getCart(userSession.getUserId());
- if (cart != null) {
- cart.setFields(cartForm);
- } else {
- cart = new Cart(cartForm);
- cart.setUserId(userSession.getUserId());
- }
- if (cart.getShipVia().equalsIgnoreCase("PKP"))
- cart.setDisposition("W");
- cart.setShipWhseId(userSession.getWarehouse());
- cart.setShipDate(cartForm.getShipDate());
- //save data to db
- cartService.saveCart(cart);
- //fetch cart lines and calc subtotal
- BigDecimal subtot = BigDecimal.ZERO;
- //we have to do this again because the price could be different across job accounts
- //and the user might decide at the last minute to create the order in a different job acct
- List<CartItem> items = cartService.getCartItems(userSession.getUserId());
- for (CartItem item : items) {
- //instead of getting session jobaccount, fetch the cart assigned job account
- Product p = productService.getProduct(CONO, OPER, userSession.getCustomerNumber(), cart.getJobId(), cart.getShipWhseId(), item.getProductCode());
- //base64 encode the cartitem; still have access to prod in productDetail
- item.setProductCode(item.getProductCode());
- //figure out price - for now it's just the price of the product from sx
- item.setUnitPrice(p.getPrice());
- //attach product details to CartItem
- item.setProductDetail(p);
- //update subtotal
- subtot = subtot.add(new BigDecimal(item.getQty() * p.getPrice().doubleValue()));
- }
- model.put("cartLines", items);
- model.put("subTotal", subtot);
- //fetch bill to info
- try {
- model.put("accountInfo", accountService.getAccountInfo(CONO, OPER, userSession.getCustomerNumber()));
- } catch (Exception ex) {
- //@todo; do something with this error
- }
- return "/cart/review";
- } else if (cartForm.getStep() != null && cartForm.getStep().equals("commit")) {
- Cart cart = cartService.getCart(userSession.getUserId());
- List<CartItem> lines = cartService.getCartItems(userSession.getUserId());
- //make sure all 'stock' items exist in order whse. if not, create
- for (CartItem line : lines) {
- line = loadItemDetail(line, userSession);
- if (line.getPriceType().equalsIgnoreCase("S") || line.getPriceType().equalsIgnoreCase("K")) {
- //product pricing whse not same as httpSession whse so product wasn't found in httpSession whse
- if (!line.getProductDetail().getPriceWhse().equals(userSession.getWarehouse())) {
- String res = productService.createWarehouseProduct(CONO, OPER, line.getProductDetail().getProduct(), userSession.getWarehouse());
- if (res != null && !res.isEmpty()) {
- try {
- Emailer email = new Emailer(ConfigReader.getProperty("email.smtpserver"));
- int smtpPort = Integer.valueOf(ConfigReader.getProperty("email.smtpPort"));
- email.setSmtpPort(smtpPort);
- email.setFromAddress(ConfigReader.getProperty("email.sender"));
- email.addToAddress(ConfigReader.getProperty("email.sender"));
- email.setSubject(ConfigReader.getProperty("site.name") + " had a warehouse product created!");
- String message = "Created product " + line.getProductDetail().getProduct() +
- " in warehouse " + userSession.getWarehouse() + ".\n\n" + res;
- email.setMessage(message);
- email.sendMessage();
- } catch (Exception ee) {
- log.error("Unable to send ICSW create notice. " + ee);
- }
- }
- }
- }
- }
- //@todo; need to work on exception handling here. order can succeed but email can
- //fail causing cart to not clean up and give user idea that order wasn't placed...
- //count the number of (N)onstock, (L)oss of Business, (S)upersede product items in the order
- int nonstockspecialitems = 0;
- try {
- OrderResults results = accountService.placeOrder(CONO, OPER, userSession.getUserId(), userSession.getCustomerNumber(), cart, lines);
- //count the number of (N)onstock, (L)oss of Business, (S)upersede product items in the order
- String nonstockcd = "NLS";
- for (CartItem line : lines) {
- Product product = line.getProductDetail();
- if (product != null) {
- String status = product.getStatus();
- status = (status != null) ? status : ""; //make sure you have a valid string
- if (nonstockcd.contains(status)) {
- ++nonstockspecialitems;
- }
- }
- }
- //something happened to keep the order from being created
- if ((results.getAckMsg() != null && results.getAckMsg().contains("Error")) && !results.getErrorMsg().isEmpty()) {
- model.put("messageTitle", "Shopping Cart Error");
- model.put("messageNum", results.getAckErrorNum());
- model.put("message", results.getAckMsg());
- model.put("linkUrl", "/cart/checkout.htm");
- model.put("linkText", "Resolve Error");
- return "/error/service";
- }
- //haven't seen these with the new api but better safe than sorry
- if (!results.getErrorMsg().isEmpty()) {
- model.put("messageTitle", "Shopping Cart Error");
- model.put("messageNum", "2186");
- model.put("message", results.getErrorMsg());
- model.put("linkUrl", "/cart/checkout.htm");
- model.put("linkText", "Resolve Error");
- return "/error/service";
- }
- //fetch order details and tie back results
- Order order = accountService.getOrder(CONO,
- OPER,
- userSession.getCustomerNumber(),
- results.getOrderDetails().getOrderNo(),
- results.getOrderDetails().getOrderSuf());
- results.setOrderDetails(order);
- //if (nonstockspecialitems > 0) {
- //send email to user
- sendEmailConfirmation(userSession, results);
- //send email to counter
- sendInternalEmailConfirmation(userSession, results);
- //}
- //attach order results
- model.put("results", results);
- //clean up cart
- cartService.clear(userSession.getUserId());
- } catch (Exception ex) {
- log.error(ex);
- model.put("messageTitle", "Shopping Cart Error");
- model.put("messageNum", 8675309);
- model.put("message", "An unknown error has occurred. If you continue to receive this message, please contact support.");
- model.put("linkUrl", "/cart/index.htm");
- model.put("linkText", "Resolve Error");
- return "/error/service";
- }
- return "/cart/confirm";
- } else {
- return "redirect:/cart/index.htm";
- }
- }
- @RequestMapping(value = "/cart/clear", method = RequestMethod.GET)
- @SecurityAnnotation(requireLogin = true)
- public ModelAndView clear(@RequestParam(value = "confirm", required = false) String confirm,
- HttpSession session) {
- Map<String, Object> model = new HashMap<String, Object>();
- //fetch httpSession data
- Session userSession = (Session) session.getAttribute("session");
- if (confirm != null) {
- cartService.clear(userSession.getUserId());
- return new ModelAndView("redirect:/cart/index.htm", model);
- } else {
- model.put("messageTitle", "Clear Shopping Cart");
- model.put("message", "Are you certain you want to remove all items from your shopping cart?");
- model.put("button_yes", "/cart/clear.htm?confirm=yes");
- model.put("button_no", "/cart/index.htm");
- return new ModelAndView("/modal-message", model);
- }
- }
- @RequestMapping(value = "/cart/updateItem", method = RequestMethod.POST)
- @SecurityAnnotation(requireLogin = true)
- public ModelAndView updateItem(HttpSession session) {
- ModelMap model = new ModelMap();
- ModelAndView mv = index(model, session);
- mv.getModel().put("message", "yes, it worked");
- return mv;
- }
- @RequestMapping(value = "/cart/removeItem", method = RequestMethod.POST)
- @SecurityAnnotation(requireLogin = true)
- public ModelAndView removeItem(HttpSession session) {
- Map<String, Object> model = new HashMap<String, Object>();
- return new ModelAndView("redirect:/cart/index.htm", model);
- }
- @RequestMapping(value = "/cart/addItem", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
- @SecurityAnnotation(requireLogin = true)
- public
- @ResponseBody
- String
- addItem(@RequestParam(value = "productCode", required = false) String productCode,
- @RequestParam(value = "quantity", required = false) String quantity,
- HttpSession session) {
- int qty = 1;
- try {
- qty = Integer.parseInt(quantity);
- } catch (Exception ignore) {
- }
- Session userSession = (Session) session.getAttribute("session");
- if (productCode != null && !productCode.isEmpty())
- cartService.saveItem(userSession.getUserId(), productCode, "", qty, true, null);
- Map<String, Object> model = new HashMap<String, Object>();
- //return new ModelAndView("redirect:/cart/index.htm", model);
- return this.getItems(session);
- }
- /**
- * @param userId
- * @param productCode
- * @param quantity
- * @return
- */
- private boolean addItem(String userId, String productCode, String quantity, boolean overrideQty, String priceType, BigDecimal price) {
- int qty = 1;
- try {
- qty = Integer.parseInt(quantity);
- } catch (Exception ignore) {
- }
- if (productCode != null && !productCode.isEmpty()) {
- cartService.saveItem(userId, productCode, "", qty, overrideQty, null);
- return true;
- }
- return false;
- }
- /**
- * @param httpSession
- * @return
- */
- @RequestMapping(value = "/cart/getItems", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
- @SecurityAnnotation(requireLogin = true)
- public
- @ResponseBody
- String getItems(HttpSession httpSession) {
- Session session = (Session) httpSession.getAttribute("session");
- //@todo; need to setup a one-to-one mapping in hibernate but for now this works pretty well since it does fetch pricing if user is logged in
- //@todo; duplicate effort with getCart()?
- //@todo; move this logic to service so that all calls use same price calculations?
- List<CartItem> items = cartService.getCartItems(session.getUserId());
- for (CartItem item : items) {
- Product p = productService.getProduct(CONO, OPER, session.getCustomerNumber(), session.getShipTo(), session.getWarehouse(), item.getProductCode());
- //base64 encode the cartitem; still have access to prod in productDetail
- item.setProductCode(item.getProductCode());
- //figure out price - for now it's just the price of the product from sx
- item.setUnitPrice(p.getPrice());
- //attach product details to CartItem
- item.setProductDetail(p);
- }
- Gson gson = new Gson();
- return gson.toJson(items);
- }
- @RequestMapping(value = "/cart/test-enc", method = RequestMethod.GET)
- @SecurityAnnotation(requireLogin = true)
- public ModelAndView testEncryption(@RequestParam(value = "key", required = true) String key,
- @RequestParam(value = "data", required = true) String data,
- @RequestParam(value = "d", required = true) String direction) {
- Map<String, Object> model = new HashMap<String, Object>();
- try {
- data = data.replace(" ", "+");
- String results = "";
- if (direction.equals("encrypt")) {
- results = Encryption.DES3Encrypt(data, key);
- } else {
- results = Encryption.DES3Decrypt(data, key);
- }
- System.out.println(results);
- model.put("status", "warn");
- model.put("button_continue", "/cart/index.htm");
- model.put("message", results);
- } catch (Exception ex) {
- model.put("status", "error");
- model.put("button_continue", "/cart/index.htm");
- model.put("message", "There was an error in the conversion process: " + ex);
- }
- return new ModelAndView("/message", model);
- }
- @RequestMapping(value = "/cart/convert-external", method = RequestMethod.GET)
- @SecurityAnnotation(requireLogin = true)
- public ModelAndView convertExternal(@RequestParam(value = "uid", required = true) String uid,
- @RequestParam(value = "data", required = true) String data,
- HttpSession session) {
- boolean success = false;
- String message = "";
- Session userSession = (Session) session.getAttribute("session");
- data = data.replace(" ", "+");
- log.error(uid);
- log.error(data);
- Map<String, Object> model = new HashMap<String, Object>();
- try {
- //fetch Influx user
- com.influx.bean.User infxUser = userService.getInfluxById(uid);
- log.error(infxUser.getSecurityKey());
- //decrypt data using User private key
- String decryptData = Encryption.DES3Decrypt(data, infxUser.getSecurityKey());
- log.error("decryptData " + decryptData);
- //store data into key/value pair array <-- why not HashMap???
- List<NameValuePair> nvpList = URLEncodedUtils.parse(decryptData, "UTF-8");
- //get influx username/password from data-feed and
- //compare to username/password stored in influx db; if match continue
- String sfUser = nvpList.get(nvpList.indexOf(new NameValuePair("username", null))).getValue();
- String sfPass = nvpList.get(nvpList.indexOf(new NameValuePair("password", null))).getValue();
- if (sfUser.equals(infxUser.getUsername()) && sfPass.equals(infxUser.getPassword())) {
- String sfToken = nvpList.get(nvpList.indexOf(new NameValuePair("token", null))).getValue();
- if (sfToken != null) {
- //copy cart from mongo to mssql
- SyncCart syncCart = cartService.getExternalCart(sfToken);
- if (syncCart == null) {
- model.put("status", "error");
- message = "Unable to locate any items in external cart.";
- return new ModelAndView("/message", model);
- }
- List<String[]> itemResults = new ArrayList<String[]>();
- List<SyncCartItem> items = syncCart.getItems();
- for (SyncCartItem item : items) {
- if (productService.getProduct(item.getItemName()) == null) {
- itemResults.add(new String[]{item.getItemName(), "Invalid Product SKU"});
- } else {
- cartService.saveItem(userSession.getUserId(), item.getItemName(), "", item.getQuantity(), false, new BigDecimal(0.00));
- itemResults.add(new String[]{item.getItemName(), "Product added to cart"});
- }
- }
- model.put("itemResults", itemResults);
- success = true;
- message = "Your shopping cart was converted successfully.";
- } else {
- message = "Token not found";
- }
- } else {
- message = "Invalid Username / Password combination.";
- }
- } catch (Exception ex) {
- log.error(ex);
- model.put("status", "error");
- model.put("button_continue", "/cart/index.htm");
- model.put("message", "There was an error in the conversion process: " + ex);
- return new ModelAndView("/message", model);
- }
- model.put("status", "success");
- model.put("message", message);
- model.put("button_continue", "/cart/index.htm");
- return new ModelAndView("/message", model);
- }
- private CartItem loadItemDetail(CartItem item, Session userSession) {
- Product p = productService.getProduct(CONO, OPER, userSession.getCustomerNumber(), userSession.getShipTo(), userSession.getWarehouse(), item.getProductCode());
- //base64 encode the cartitem; still have access to prod in productDetail
- item.setProductCode(item.getProductCode());
- //figure out price - for now it's just the price of the product from sx
- item.setUnitPrice(p.getPrice());
- //attach product details to CartItem
- item.setProductDetail(p);
- return item;
- }
- /**
- * @todo; at some point would be nice to let ION do this instead of it
- * being embedded into code
- */
- public boolean sendEmailConfirmation(Session session, OrderResults results) {
- boolean success = false;
- try {
- //Email customer
- Emailer email = new Emailer(ConfigReader.getProperty("email.smtpserver"));
- int smtpPort = Integer.valueOf(ConfigReader.getProperty("email.smtpPort"));
- email.setSmtpPort(smtpPort);
- email.setFromAddress(ConfigReader.getProperty("email.sender"));
- email.setFromName(ConfigReader.getProperty("site.name"));
- email.addToAddress(session.getContact().getEmailAddr());
- email.setSubject(
- ConfigReader.getProperty("site.name") + " Order Confirmation -- " +
- results.getOrderDetails().getOrderNo() + "-" + results.getOrderDetails().getOrderSuf());
- email.setMessage(
- "Thank you for your internet order!\n" +
- "Certain equipment might not be available from your ordering warehouse and will have to be shipped from another location.\n" +
- "-----------------------------------------------------------\n" +
- "Thank you again for your order\n" +
- "Sincerely,\n" +
- "WeatherZone Online Sales\n" +
- "-----------------------------------------------------------\n\n" +
- "http://" + ConfigReader.getProperty("site.url"));
- email.sendMessage();
- success = true;
- } catch (Exception ex) {
- //@TODO: SMS site admins...
- log.error("sendEmailConfirmation(); site=" + ConfigReader.getProperty("site.url") +
- " username=" + session.getUserId() + " custno=" + session.getCustomerNumber() +
- " error: " + ex.toString());
- }
- return success;
- }
- /**
- * @todo; would be nice to let ION do this instead of it being embedded into code
- */
- public boolean sendSMSConfirmation(OrderResults results) {
- return false;
- }
- public boolean sendInternalEmailConfirmation(Session session, OrderResults results) {
- boolean success = false;
- try {
- Location location = locationService.getLocation(results.getOrderDetails().getWhse());
- SalesRep salesRep = accountService.getSalesRep(CONO, session.getAccount().getSlsRepOut());
- //email others
- Emailer email = new Emailer(ConfigReader.getProperty("email.smtpserver"));
- int smtpPort = Integer.valueOf(ConfigReader.getProperty("email.smtpPort"));
- email.setSmtpPort(smtpPort);
- email.setFromAddress(ConfigReader.getProperty("email.sender"));
- email.setFromName(ConfigReader.getProperty("site.name"));
- email.addToAddress(location.getEmailAddr());
- List<String> sendToList = getSendToList();
- Iterator<String> iter = sendToList.iterator();
- while(iter.hasNext())
- {
- String sendTo = iter.next();
- System.out.println(sendTo);
- email.addToAddress(sendTo);
- }
- String whse = session.getWarehouse();
- List<String> sendToList2 = getSendToList(whse);
- Iterator<String> iter2 = sendToList2.iterator();
- while(iter2.hasNext())
- {
- String sendTo = iter2.next();
- System.out.println(sendTo);
- email.addToAddress(sendTo);
- }
- if (salesRep != null)
- email.addCcAddress(salesRep.getEmailAddr());
- email.setSubject(ConfigReader.getProperty("site.name") + " Order Placed -- " + results.getOrderDetails().getOrderNo());
- String message = "Order Number " + results.getOrderDetails().getOrderNo() + " has been placed by " +
- results.getOrderDetails().getSoldToName() + " (" + results.getOrderDetails().getCustNo() + ") on " +
- ConfigReader.getProperty("site.name") + " and is awaiting processing.";
- ////include notes if any
- //if(results.getNotes() != null && results.getNotes().length() > 0)
- // message += "\n\nSpecial Instructions:\n" + results.getNotes();
- message += "\n\n***********************************************************\n";
- message += "Debug Info:\n" + results.getAckMsg();
- email.setMessage(message);
- email.sendMessage();
- success = true;
- } catch (Exception ex) {
- //@TODO: SMS site admins...
- log.error("sendInternalEmailConfirmation(); site=" + ConfigReader.getProperty("site.url") +
- " username=" + session.getUserId() + " custno=" + session.getCustomerNumber() +
- " error: " + ex.toString());
- }
- return success;
- }
- public List<String> getSendToList() {
- List<String> list = new ArrayList<String>();
- String sendToProp = ConfigReader.getProperty("email.sendTo.orders");
- if (sendToProp != null && !sendToProp.equals("")) {
- StringTokenizer st = new StringTokenizer(sendToProp, ";");
- while (st.hasMoreElements()) {
- list.add((String) st.nextToken());
- }
- }
- return list;
- }
- public List<String> getSendToList(String whse) {
- List<String> list = new ArrayList<String>();
- if (whse == null || whse.equals("")) return list;
- String sendToProp = ConfigReader.getProperty("email.sendTo.orders." + whse);
- if (sendToProp == null || sendToProp.equals("")) return list;
- if (sendToProp != null && !sendToProp.equals("")) {
- StringTokenizer st = new StringTokenizer(sendToProp, ";");
- while (st.hasMoreElements()) {
- list.add((String) st.nextToken());
- }
- }
- return list;
- }
- public static void main(String args[]) {
- CartController cc = new CartController();
- Iterator<String> iter = cc.getSendToList().listIterator();
- while (iter.hasNext()) {
- System.out.println(iter.next());
- }
- }
- }