PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/src/main/java/com/kawauso/base/controller/CartController.java

https://bitbucket.org/mingle_dev/holden_wz
Java | 837 lines | 546 code | 190 blank | 101 comment | 86 complexity | b6ff98e1a419838bbd6bc561fdd31db9 MD5 | raw file
  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package com.kawauso.base.controller;
  6. import com.google.gson.Gson;
  7. import com.influx.bean.SyncCart;
  8. import com.influx.bean.SyncCartItem;
  9. import com.kawauso.base.ConfigReader;
  10. import com.kawauso.base.SecurityAnnotation;
  11. import com.kawauso.base.Utilities.ELUtilities;
  12. import com.kawauso.base.Utilities.Emailer;
  13. import com.kawauso.base.Utilities.Encryption;
  14. import com.kawauso.base.Utilities.URLEncodedUtils;
  15. import com.kawauso.base.Utilities.URLEncodedUtils.NameValuePair;
  16. import com.kawauso.base.bean.*;
  17. import com.kawauso.base.form.CartForm;
  18. import com.kawauso.base.service.*;
  19. import org.apache.log4j.Logger;
  20. import org.hibernate.Query;
  21. import org.hibernate.SessionFactory;
  22. import org.springframework.beans.factory.annotation.Autowired;
  23. import org.springframework.http.MediaType;
  24. import org.springframework.stereotype.Controller;
  25. import org.springframework.ui.ModelMap;
  26. import org.springframework.validation.BeanPropertyBindingResult;
  27. import org.springframework.validation.BindingResult;
  28. import org.springframework.validation.Errors;
  29. import org.springframework.validation.ValidationUtils;
  30. import org.springframework.web.bind.annotation.*;
  31. import org.springframework.web.servlet.ModelAndView;
  32. import javax.servlet.http.HttpSession;
  33. import java.math.BigDecimal;
  34. import java.util.*;
  35. @Controller
  36. public class CartController {
  37. private static final Logger log = Logger.getLogger(CartController.class);
  38. @Autowired
  39. private CartService cartService;
  40. @Autowired
  41. private ProductService productService;
  42. @Autowired
  43. private AccountService accountService;
  44. @Autowired
  45. private UserService userService;
  46. @Autowired
  47. private LocationService locationService;
  48. @Autowired
  49. private SessionFactory sessionFactory;
  50. //private static final int CONO = ConfigReader.getPropertyAsInt("sxe.cono");
  51. private static final String OPER = ConfigReader.getProperty("sxe.oper");
  52. @RequestMapping(value = "/cart/index", method = RequestMethod.GET)
  53. @SecurityAnnotation(requireLogin = true)
  54. public ModelAndView index(ModelMap model, HttpSession session) {
  55. //fetch httpSession data
  56. Session userSession = (Session) session.getAttribute("session");
  57. //not authorized
  58. if (userSession.getUser().isSecurityOrderCreate() != true)
  59. return new ModelAndView("/unauthorized", model);
  60. //breadcrumbs
  61. List<Breadcrumb> crumbs = new ArrayList<Breadcrumb>();
  62. crumbs.add(new Breadcrumb("Shopping Cart", "", ""));
  63. model.put("navTree", crumbs);
  64. //@todo clean up the shopping carts remove functionality... this code works in conjunction with LayoutInterceptor... not good implementation
  65. String cartLineErrors = (String)session.getAttribute("cartLineErrors");
  66. StringTokenizer st = new StringTokenizer(cartLineErrors, ";");
  67. org.hibernate.Session currentSession = sessionFactory.getCurrentSession();
  68. while (st.hasMoreTokens()){
  69. Query q = currentSession.createQuery("DELETE CartItem WHERE userId=:userId AND productCode=:prod");
  70. q.setString("userId", userSession.getUserId());
  71. q.setString("prod", st.nextToken());
  72. q.executeUpdate(); //returns # of records affected
  73. }
  74. //fetch cart
  75. //@todo; need to setup a one-to-one mapping in hibernate but for now this works pretty well
  76. //since it does fetch pricing if user is logged in
  77. BigDecimal subtot = BigDecimal.ZERO;
  78. List<CartItem> items = cartService.getCartItems(userSession.getUserId());
  79. for (CartItem item : items) {
  80. Product p = productService.getProduct(userSession.getCono(), OPER, userSession.getCustomerNumber(), userSession.getShipTo(), userSession.getWarehouse(), item.getProductCode());
  81. //base64 encode the cartitem; still have access to prod in productDetail
  82. item.setProductCode(item.getProductCode());
  83. //figure out price - for now it's just the price of the product from sx
  84. item.setUnitPrice(p.getPrice());
  85. //attach product details to CartItem
  86. item.setProductDetail(p);
  87. subtot = subtot.add(new BigDecimal(item.getQty() * p.getPrice().doubleValue()));
  88. }
  89. model.put("items", items);
  90. model.put("subTotal", subtot);
  91. return new ModelAndView("/cart/index", model);
  92. }
  93. @RequestMapping(value = "/cart/index", method = RequestMethod.POST)
  94. @SecurityAnnotation(requireLogin = true)
  95. public ModelAndView index(@RequestParam(value = "productCode", required = false) String productCode,
  96. @RequestParam(value = "quantity", required = false) String quantity,
  97. HttpSession session) {
  98. ModelMap model = new ModelMap();
  99. //fetch httpSession data
  100. Session userSession = (Session) session.getAttribute("session");
  101. addItem(userSession.getUserId(), ELUtilities.base64Decode(productCode), quantity, false, "S", null);
  102. return index(model, session);
  103. }
  104. @RequestMapping(value = "/cart/checkout", method = RequestMethod.GET)
  105. @SecurityAnnotation(requireLogin = true)
  106. public ModelAndView checkout(HttpSession session) {
  107. Map<String, Object> model = new HashMap<String, Object>();
  108. //fetch httpSession data
  109. Session userSession = (Session) session.getAttribute("session");
  110. //@todo;user and session are starting to look identical; what about merging into mongodb?
  111. User user = userService.getUser(userSession.getUserId());
  112. model.put("defaultShipVia", user.getShipVia());
  113. //if cart is empty, send to main cart screen
  114. if (cartService.getCartItems(userSession.getUserId()).isEmpty() == true)
  115. return new ModelAndView("/cart/index", model);
  116. //get cart head if exists
  117. Cart cartData = cartService.getCart(userSession.getUserId());
  118. model.put("cartData", cartData);
  119. //fetch shipto's
  120. model.put("shipToList", accountService.getShipToList(userSession.getCono(), OPER, userSession.getCustomerNumber(), true));
  121. //shipvia's
  122. model.put("shipViaList", cartService.getShipViaList());
  123. //order defaults
  124. model.put("orderingInfo", accountService.getOrderingInfo(userSession.getCono(), OPER, userSession.getCustomerNumber()));
  125. //date stuff
  126. Calendar cal = Calendar.getInstance();
  127. try {
  128. String[] shipDateArr = cartData.getShipDate().split("/|-");
  129. model.put("calYear", Integer.parseInt(shipDateArr[0]));
  130. model.put("calMonth", Integer.parseInt(shipDateArr[1]));
  131. model.put("calDay", Integer.parseInt(shipDateArr[2]));
  132. } catch (Exception e) {
  133. model.put("calYear", cal.get(Calendar.YEAR));
  134. model.put("calMonth", cal.get(Calendar.MONTH) + 1);
  135. model.put("calDay", cal.get(Calendar.DATE));
  136. }
  137. //breadcrumbs
  138. List<Breadcrumb> crumbs = new ArrayList<Breadcrumb>();
  139. crumbs.add(new Breadcrumb("Shopping Cart", "/cart/index.htm", ""));
  140. crumbs.add(new Breadcrumb("Checkout", "", ""));
  141. model.put("navTree", crumbs);
  142. model.put("cartForm", new CartForm());
  143. return new ModelAndView("/cart/shipInfo", model);
  144. }
  145. @RequestMapping(value = "/cart/checkout", method = RequestMethod.POST)
  146. @SecurityAnnotation(requireLogin = true)
  147. public String checkout(@ModelAttribute("cartForm") CartForm cartForm, BindingResult result, ModelMap model, HttpSession session) {
  148. //fetch httpSession data
  149. Session userSession = (Session) session.getAttribute("session");
  150. //@todo;user and session are starting to look identical; what about merging into mongodb?
  151. User user = userService.getUser(userSession.getUserId());
  152. model.put("defaultShipVia", user.getShipVia());
  153. if (cartForm.getStep() != null && cartForm.getStep().equals("shipInfo")) {
  154. //fetch shipto's
  155. model.put("shipToList", accountService.getShipToList(userSession.getCono(), OPER, userSession.getCustomerNumber(), true));
  156. //shipvia's
  157. model.put("shipViaList", cartService.getShipViaList());
  158. //order defaults
  159. Map<String, Object> orderingInfo = accountService.getOrderingInfo(userSession.getCono(), OPER, userSession.getCustomerNumber());
  160. model.put("orderingInfo", orderingInfo);
  161. //date stuff
  162. Calendar cal = Calendar.getInstance();
  163. model.put("calMonth", cal.get(Calendar.MONTH) + 1); //zero-based idx
  164. model.put("calDay", cal.get(Calendar.DATE));
  165. model.put("calYear", cal.get(Calendar.YEAR));
  166. //breadcrumbs
  167. List<Breadcrumb> crumbs = new ArrayList<Breadcrumb>();
  168. crumbs.add(new Breadcrumb("Shopping Cart", "/cart/index.htm", ""));
  169. crumbs.add(new Breadcrumb("Checkout", "", ""));
  170. model.put("navTree", crumbs);
  171. //validate field data
  172. Errors errors = new BeanPropertyBindingResult(cartForm, "cartForm");
  173. ValidationUtils.rejectIfEmptyOrWhitespace(errors, "shipToName", "field.required");
  174. ValidationUtils.rejectIfEmptyOrWhitespace(errors, "shipToAddr1", "field.required");
  175. ValidationUtils.rejectIfEmptyOrWhitespace(errors, "shipToCity", "field.required");
  176. if (cartForm.getShipToState().trim().isEmpty() && errors.getFieldError("shipToCity").getDefaultMessage() != null)
  177. errors.rejectValue("shipToCity", "field.required");
  178. if (cartForm.getShipToZip().trim().isEmpty() && errors.getFieldError("shipToCity").getDefaultMessage() != null)
  179. errors.rejectValue("shipToCity", "field.required");
  180. if (orderingInfo.get("poReq").equals(true))
  181. ValidationUtils.rejectIfEmptyOrWhitespace(errors, "custPo", "field.required");
  182. if (orderingInfo.get("shipToReq").equals(true))
  183. ValidationUtils.rejectIfEmptyOrWhitespace(errors, "jobId", "field.required");
  184. ValidationUtils.rejectIfEmptyOrWhitespace(errors, "shipVia", "field.required");
  185. if (errors.getErrorCount() > 0) {
  186. model.put("formError", true);
  187. result.addAllErrors(errors);
  188. return "/cart/shipInfo";
  189. }
  190. //fetch existing cart id from db
  191. Cart cart = cartService.getCart(userSession.getUserId());
  192. if (cart != null) {
  193. cart.setFields(cartForm);
  194. } else {
  195. cart = new Cart(cartForm);
  196. cart.setUserId(userSession.getUserId());
  197. }
  198. if (cart.getShipVia().equalsIgnoreCase("PKP"))
  199. cart.setDisposition("W");
  200. cart.setShipWhseId(userSession.getWarehouse());
  201. cart.setShipDate(cartForm.getShipDate());
  202. //save data to db
  203. cartService.saveCart(cart);
  204. //fetch cart lines and calc subtotal
  205. BigDecimal subtot = BigDecimal.ZERO;
  206. //we have to do this again because the price could be different across job accounts
  207. //and the user might decide at the last minute to create the order in a different job acct
  208. List<CartItem> items = cartService.getCartItems(userSession.getUserId());
  209. for (CartItem item : items) {
  210. //instead of getting session jobaccount, fetch the cart assigned job account
  211. Product p = productService.getProduct(userSession.getCono(), OPER, userSession.getCustomerNumber(), cart.getJobId(), cart.getShipWhseId(), item.getProductCode());
  212. //base64 encode the cartitem; still have access to prod in productDetail
  213. item.setProductCode(item.getProductCode());
  214. //figure out price - for now it's just the price of the product from sx
  215. item.setUnitPrice(p.getPrice());
  216. //attach product details to CartItem
  217. item.setProductDetail(p);
  218. //update subtotal
  219. subtot = subtot.add(new BigDecimal(item.getQty() * p.getPrice().doubleValue()));
  220. }
  221. model.put("cartLines", items);
  222. model.put("subTotal", subtot);
  223. //fetch bill to info
  224. try {
  225. model.put("accountInfo", accountService.getAccountInfo(userSession.getCono(), OPER, userSession.getCustomerNumber()));
  226. } catch (Exception ex) {
  227. //@todo; do something with this error
  228. }
  229. return "/cart/review";
  230. } else if (cartForm.getStep() != null && cartForm.getStep().equals("commit")) {
  231. Cart cart = cartService.getCart(userSession.getUserId());
  232. List<CartItem> lines = cartService.getCartItems(userSession.getUserId());
  233. //make sure all 'stock' items exist in order whse. if not, create
  234. for (CartItem line : lines) {
  235. line = loadItemDetail(line, userSession);
  236. if (line.getPriceType().equalsIgnoreCase("S") || line.getPriceType().equalsIgnoreCase("K")) {
  237. //product pricing whse not same as httpSession whse so product wasn't found in httpSession whse
  238. if (!line.getProductDetail().getPriceWhse().equals(userSession.getWarehouse())) {
  239. String res = productService.createWarehouseProduct(userSession.getCono(), OPER, line.getProductDetail().getProduct(), userSession.getWarehouse());
  240. if (res != null && !res.isEmpty()) {
  241. try {
  242. Emailer email = new Emailer(ConfigReader.getProperty("email.smtpserver"));
  243. int smtpPort = Integer.valueOf(ConfigReader.getProperty("email.smtpPort"));
  244. email.setSmtpPort(smtpPort);
  245. email.setFromAddress(ConfigReader.getProperty("email.sender"));
  246. email.addToAddress(ConfigReader.getProperty("email.sender"));
  247. email.setSubject(ConfigReader.getProperty("site.name") + " had a warehouse product created!");
  248. String message = "Created product " + line.getProductDetail().getProduct() +
  249. " in warehouse " + userSession.getWarehouse() + ".\n\n" + res;
  250. email.setMessage(message);
  251. email.sendMessage();
  252. } catch (Exception ee) {
  253. log.error("Unable to send ICSW create notice. " + ee);
  254. }
  255. }
  256. }
  257. }
  258. }
  259. //@todo; need to work on exception handling here. order can succeed but email can
  260. //fail causing cart to not clean up and give user idea that order wasn't placed...
  261. //count the number of (N)onstock, (L)oss of Business, (S)upersede product items in the order
  262. int nonstockspecialitems = 0;
  263. try {
  264. OrderResults results = accountService.placeOrder(userSession.getCono(), OPER, userSession.getUserId(), userSession.getCustomerNumber(), cart, lines);
  265. //count the number of (N)onstock, (L)oss of Business, (S)upersede product items in the order
  266. String nonstockcd = "NLS";
  267. for (CartItem line : lines) {
  268. Product product = line.getProductDetail();
  269. if (product != null) {
  270. String status = product.getStatus();
  271. status = (status != null) ? status : ""; //make sure you have a valid string
  272. if (nonstockcd.contains(status)) {
  273. ++nonstockspecialitems;
  274. }
  275. }
  276. }
  277. //something happened to keep the order from being created
  278. if ((results.getAckMsg() != null && results.getAckMsg().contains("Error")) && !results.getErrorMsg().isEmpty()) {
  279. model.put("messageTitle", "Shopping Cart Error");
  280. model.put("messageNum", results.getAckErrorNum());
  281. model.put("message", results.getAckMsg());
  282. model.put("linkUrl", "/cart/checkout.htm");
  283. model.put("linkText", "Resolve Error");
  284. return "/error/service";
  285. }
  286. //haven't seen these with the new api but better safe than sorry
  287. if (!results.getErrorMsg().isEmpty()) {
  288. model.put("messageTitle", "Shopping Cart Error");
  289. model.put("messageNum", "2186");
  290. model.put("message", results.getErrorMsg());
  291. model.put("linkUrl", "/cart/checkout.htm");
  292. model.put("linkText", "Resolve Error");
  293. return "/error/service";
  294. }
  295. //fetch order details and tie back results
  296. Order order = accountService.getOrder(userSession.getCono(),
  297. OPER,
  298. userSession.getCustomerNumber(),
  299. results.getOrderDetails().getOrderNo(),
  300. results.getOrderDetails().getOrderSuf());
  301. results.setOrderDetails(order);
  302. //if (nonstockspecialitems > 0) {
  303. //send email to user
  304. sendEmailConfirmation(userSession, results);
  305. //send email to counter
  306. sendInternalEmailConfirmation(userSession, results);
  307. //}
  308. //attach order results
  309. model.put("results", results);
  310. //clean up cart
  311. cartService.clear(userSession.getUserId());
  312. } catch (Exception ex) {
  313. log.error(ex);
  314. model.put("messageTitle", "Shopping Cart Error");
  315. model.put("messageNum", 8675309);
  316. model.put("message", "An unknown error has occurred. If you continue to receive this message, please contact support.");
  317. model.put("linkUrl", "/cart/index.htm");
  318. model.put("linkText", "Resolve Error");
  319. return "/error/service";
  320. }
  321. return "/cart/confirm";
  322. } else {
  323. return "redirect:/cart/index.htm";
  324. }
  325. }
  326. @RequestMapping(value = "/cart/clear", method = RequestMethod.GET)
  327. @SecurityAnnotation(requireLogin = true)
  328. public ModelAndView clear(@RequestParam(value = "confirm", required = false) String confirm,
  329. HttpSession session) {
  330. Map<String, Object> model = new HashMap<String, Object>();
  331. //fetch httpSession data
  332. Session userSession = (Session) session.getAttribute("session");
  333. if (confirm != null) {
  334. cartService.clear(userSession.getUserId());
  335. return new ModelAndView("redirect:/cart/index.htm", model);
  336. } else {
  337. model.put("messageTitle", "Clear Shopping Cart");
  338. model.put("message", "Are you certain you want to remove all items from your shopping cart?");
  339. model.put("button_yes", "/cart/clear.htm?confirm=yes");
  340. model.put("button_no", "/cart/index.htm");
  341. return new ModelAndView("/modal-message", model);
  342. }
  343. }
  344. @RequestMapping(value = "/cart/updateItem", method = RequestMethod.POST)
  345. @SecurityAnnotation(requireLogin = true)
  346. public ModelAndView updateItem(HttpSession session) {
  347. ModelMap model = new ModelMap();
  348. ModelAndView mv = index(model, session);
  349. mv.getModel().put("message", "yes, it worked");
  350. return mv;
  351. }
  352. @RequestMapping(value = "/cart/removeItem", method = RequestMethod.POST)
  353. @SecurityAnnotation(requireLogin = true)
  354. public ModelAndView removeItem(HttpSession session) {
  355. Map<String, Object> model = new HashMap<String, Object>();
  356. return new ModelAndView("redirect:/cart/index.htm", model);
  357. }
  358. @RequestMapping(value = "/cart/addItem", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
  359. @SecurityAnnotation(requireLogin = true)
  360. public
  361. @ResponseBody
  362. String
  363. addItem(@RequestParam(value = "productCode", required = false) String productCode,
  364. @RequestParam(value = "quantity", required = false) String quantity,
  365. HttpSession session) {
  366. int qty = 1;
  367. try {
  368. qty = Integer.parseInt(quantity);
  369. } catch (Exception ignore) {
  370. }
  371. Session userSession = (Session) session.getAttribute("session");
  372. if (productCode != null && !productCode.isEmpty())
  373. cartService.saveItem(userSession.getUserId(), productCode, "", qty, true, null);
  374. Map<String, Object> model = new HashMap<String, Object>();
  375. //return new ModelAndView("redirect:/cart/index.htm", model);
  376. return this.getItems(session);
  377. }
  378. /**
  379. * @param userId
  380. * @param productCode
  381. * @param quantity
  382. * @return
  383. */
  384. private boolean addItem(String userId, String productCode, String quantity, boolean overrideQty, String priceType, BigDecimal price) {
  385. int qty = 1;
  386. try {
  387. qty = Integer.parseInt(quantity);
  388. } catch (Exception ignore) {
  389. }
  390. if (productCode != null && !productCode.isEmpty()) {
  391. cartService.saveItem(userId, productCode, "", qty, overrideQty, null);
  392. return true;
  393. }
  394. return false;
  395. }
  396. /**
  397. * @param httpSession
  398. * @return
  399. */
  400. @RequestMapping(value = "/cart/getItems", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
  401. @SecurityAnnotation(requireLogin = true)
  402. public
  403. @ResponseBody
  404. String getItems(HttpSession httpSession) {
  405. Session session = (Session) httpSession.getAttribute("session");
  406. //@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
  407. //@todo; duplicate effort with getCart()?
  408. //@todo; move this logic to service so that all calls use same price calculations?
  409. List<CartItem> items = cartService.getCartItems(session.getUserId());
  410. for (CartItem item : items) {
  411. Product p = productService.getProduct(session.getCono(), OPER, session.getCustomerNumber(), session.getShipTo(), session.getWarehouse(), item.getProductCode());
  412. //base64 encode the cartitem; still have access to prod in productDetail
  413. item.setProductCode(item.getProductCode());
  414. //figure out price - for now it's just the price of the product from sx
  415. item.setUnitPrice(p.getPrice());
  416. //attach product details to CartItem
  417. item.setProductDetail(p);
  418. }
  419. Gson gson = new Gson();
  420. return gson.toJson(items);
  421. }
  422. @RequestMapping(value = "/cart/test-enc", method = RequestMethod.GET)
  423. @SecurityAnnotation(requireLogin = true)
  424. public ModelAndView testEncryption(@RequestParam(value = "key", required = true) String key,
  425. @RequestParam(value = "data", required = true) String data,
  426. @RequestParam(value = "d", required = true) String direction) {
  427. Map<String, Object> model = new HashMap<String, Object>();
  428. try {
  429. data = data.replace(" ", "+");
  430. String results = "";
  431. if (direction.equals("encrypt")) {
  432. results = Encryption.DES3Encrypt(data, key);
  433. } else {
  434. results = Encryption.DES3Decrypt(data, key);
  435. }
  436. System.out.println(results);
  437. model.put("status", "warn");
  438. model.put("button_continue", "/cart/index.htm");
  439. model.put("message", results);
  440. } catch (Exception ex) {
  441. model.put("status", "error");
  442. model.put("button_continue", "/cart/index.htm");
  443. model.put("message", "There was an error in the conversion process: " + ex);
  444. }
  445. return new ModelAndView("/message", model);
  446. }
  447. @RequestMapping(value = "/cart/convert-external", method = RequestMethod.GET)
  448. @SecurityAnnotation(requireLogin = true)
  449. public ModelAndView convertExternal(@RequestParam(value = "uid", required = true) String uid,
  450. @RequestParam(value = "data", required = true) String data,
  451. HttpSession session) {
  452. boolean success = false;
  453. String message = "";
  454. Session userSession = (Session) session.getAttribute("session");
  455. data = data.replace(" ", "+");
  456. log.error(uid);
  457. log.error(data);
  458. Map<String, Object> model = new HashMap<String, Object>();
  459. try {
  460. //fetch Influx user
  461. com.influx.bean.User infxUser = userService.getInfluxById(uid);
  462. log.error(infxUser.getSecurityKey());
  463. //decrypt data using User private key
  464. String decryptData = Encryption.DES3Decrypt(data, infxUser.getSecurityKey());
  465. log.error("decryptData " + decryptData);
  466. //store data into key/value pair array <-- why not HashMap???
  467. List<NameValuePair> nvpList = URLEncodedUtils.parse(decryptData, "UTF-8");
  468. //get influx username/password from data-feed and
  469. //compare to username/password stored in influx db; if match continue
  470. String sfUser = nvpList.get(nvpList.indexOf(new NameValuePair("username", null))).getValue();
  471. String sfPass = nvpList.get(nvpList.indexOf(new NameValuePair("password", null))).getValue();
  472. if (sfUser.equals(infxUser.getUsername()) && sfPass.equals(infxUser.getPassword())) {
  473. String sfToken = nvpList.get(nvpList.indexOf(new NameValuePair("token", null))).getValue();
  474. if (sfToken != null) {
  475. //copy cart from mongo to mssql
  476. SyncCart syncCart = cartService.getExternalCart(sfToken);
  477. if (syncCart == null) {
  478. model.put("status", "error");
  479. message = "Unable to locate any items in external cart.";
  480. return new ModelAndView("/message", model);
  481. }
  482. List<String[]> itemResults = new ArrayList<String[]>();
  483. List<SyncCartItem> items = syncCart.getItems();
  484. for (SyncCartItem item : items) {
  485. if (productService.getProduct(item.getItemName()) == null) {
  486. itemResults.add(new String[]{item.getItemName(), "Invalid Product SKU"});
  487. } else {
  488. cartService.saveItem(userSession.getUserId(), item.getItemName(), "", item.getQuantity(), false, new BigDecimal(0.00));
  489. itemResults.add(new String[]{item.getItemName(), "Product added to cart"});
  490. }
  491. }
  492. model.put("itemResults", itemResults);
  493. success = true;
  494. message = "Your shopping cart was converted successfully.";
  495. } else {
  496. message = "Token not found";
  497. }
  498. } else {
  499. message = "Invalid Username / Password combination.";
  500. }
  501. } catch (Exception ex) {
  502. log.error(ex);
  503. model.put("status", "error");
  504. model.put("button_continue", "/cart/index.htm");
  505. model.put("message", "There was an error in the conversion process: " + ex);
  506. return new ModelAndView("/message", model);
  507. }
  508. model.put("status", "success");
  509. model.put("message", message);
  510. model.put("button_continue", "/cart/index.htm");
  511. return new ModelAndView("/message", model);
  512. }
  513. private CartItem loadItemDetail(CartItem item, Session userSession) {
  514. Product p = productService.getProduct(userSession.getCono(), OPER, userSession.getCustomerNumber(), userSession.getShipTo(), userSession.getWarehouse(), item.getProductCode());
  515. //base64 encode the cartitem; still have access to prod in productDetail
  516. item.setProductCode(item.getProductCode());
  517. //figure out price - for now it's just the price of the product from sx
  518. item.setUnitPrice(p.getPrice());
  519. //attach product details to CartItem
  520. item.setProductDetail(p);
  521. return item;
  522. }
  523. /**
  524. * @todo; at some point would be nice to let ION do this instead of it
  525. * being embedded into code
  526. */
  527. public boolean sendEmailConfirmation(Session session, OrderResults results) {
  528. boolean success = false;
  529. try {
  530. //Email customer
  531. Emailer email = new Emailer(ConfigReader.getProperty("email.smtpserver"));
  532. int smtpPort = Integer.valueOf(ConfigReader.getProperty("email.smtpPort"));
  533. email.setSmtpPort(smtpPort);
  534. email.setFromAddress(ConfigReader.getProperty("email.sender"));
  535. email.setFromName(ConfigReader.getProperty("site.name"));
  536. email.addToAddress(session.getContact().getEmailAddr());
  537. email.setSubject(
  538. ConfigReader.getProperty("site.name") + " Order Confirmation -- " +
  539. results.getOrderDetails().getOrderNo() + "-" + results.getOrderDetails().getOrderSuf());
  540. email.setMessage(
  541. "Thank you for your internet order!\n" +
  542. "Certain equipment might not be available from your ordering warehouse and will have to be shipped from another location.\n" +
  543. "-----------------------------------------------------------\n" +
  544. "Thank you again for your order\n" +
  545. "Sincerely,\n" +
  546. "WeatherZone Online Sales\n" +
  547. "-----------------------------------------------------------\n\n" +
  548. "http://" + ConfigReader.getProperty("site.url"));
  549. email.sendMessage();
  550. success = true;
  551. } catch (Exception ex) {
  552. //@TODO: SMS site admins...
  553. log.error("sendEmailConfirmation(); site=" + ConfigReader.getProperty("site.url") +
  554. " username=" + session.getUserId() + " custno=" + session.getCustomerNumber() +
  555. " error: " + ex.toString());
  556. }
  557. return success;
  558. }
  559. /**
  560. * @todo; would be nice to let ION do this instead of it being embedded into code
  561. */
  562. public boolean sendSMSConfirmation(OrderResults results) {
  563. return false;
  564. }
  565. public boolean sendInternalEmailConfirmation(Session session, OrderResults results) {
  566. boolean success = false;
  567. try {
  568. Location location = locationService.getLocation(results.getOrderDetails().getWhse());
  569. SalesRep salesRep = accountService.getSalesRep(session.getCono(), session.getAccount().getSlsRepOut());
  570. //email others
  571. Emailer email = new Emailer(ConfigReader.getProperty("email.smtpserver"));
  572. int smtpPort = Integer.valueOf(ConfigReader.getProperty("email.smtpPort"));
  573. email.setSmtpPort(smtpPort);
  574. email.setFromAddress(ConfigReader.getProperty("email.sender"));
  575. email.setFromName(ConfigReader.getProperty("site.name"));
  576. email.addToAddress(location.getEmailAddr());
  577. List<String> sendToList = getSendToList();
  578. Iterator<String> iter = sendToList.iterator();
  579. while(iter.hasNext())
  580. {
  581. String sendTo = iter.next();
  582. System.out.println(sendTo);
  583. email.addToAddress(sendTo);
  584. }
  585. String whse = session.getWarehouse();
  586. List<String> sendToList2 = getSendToList(whse);
  587. Iterator<String> iter2 = sendToList2.iterator();
  588. while(iter2.hasNext())
  589. {
  590. String sendTo = iter2.next();
  591. System.out.println(sendTo);
  592. email.addToAddress(sendTo);
  593. }
  594. if (salesRep != null)
  595. email.addCcAddress(salesRep.getEmailAddr());
  596. email.setSubject(ConfigReader.getProperty("site.name") + " Order Placed -- " + results.getOrderDetails().getOrderNo());
  597. String message = "Order Number " + results.getOrderDetails().getOrderNo() + " has been placed by " +
  598. results.getOrderDetails().getSoldToName() + " (" + results.getOrderDetails().getCustNo() + ") on " +
  599. ConfigReader.getProperty("site.name") + " and is awaiting processing.";
  600. ////include notes if any
  601. //if(results.getNotes() != null && results.getNotes().length() > 0)
  602. // message += "\n\nSpecial Instructions:\n" + results.getNotes();
  603. message += "\n\n***********************************************************\n";
  604. message += "Debug Info:\n" + results.getAckMsg();
  605. email.setMessage(message);
  606. email.sendMessage();
  607. success = true;
  608. } catch (Exception ex) {
  609. //@TODO: SMS site admins...
  610. log.error("sendInternalEmailConfirmation(); site=" + ConfigReader.getProperty("site.url") +
  611. " username=" + session.getUserId() + " custno=" + session.getCustomerNumber() +
  612. " error: " + ex.toString());
  613. }
  614. return success;
  615. }
  616. public List<String> getSendToList() {
  617. List<String> list = new ArrayList<String>();
  618. String sendToProp = ConfigReader.getProperty("email.sendTo.orders");
  619. if (sendToProp != null && !sendToProp.equals("")) {
  620. StringTokenizer st = new StringTokenizer(sendToProp, ";");
  621. while (st.hasMoreElements()) {
  622. list.add((String) st.nextToken());
  623. }
  624. }
  625. return list;
  626. }
  627. public List<String> getSendToList(String whse) {
  628. List<String> list = new ArrayList<String>();
  629. if (whse == null || whse.equals("")) return list;
  630. String sendToProp = ConfigReader.getProperty("email.sendTo.orders." + whse);
  631. if (sendToProp == null || sendToProp.equals("")) return list;
  632. if (sendToProp != null && !sendToProp.equals("")) {
  633. StringTokenizer st = new StringTokenizer(sendToProp, ";");
  634. while (st.hasMoreElements()) {
  635. list.add((String) st.nextToken());
  636. }
  637. }
  638. return list;
  639. }
  640. public static void main(String args[]) {
  641. CartController cc = new CartController();
  642. Iterator<String> iter = cc.getSendToList().listIterator();
  643. while (iter.hasNext()) {
  644. System.out.println(iter.next());
  645. }
  646. }
  647. }