@RequestMapping(value = "/order/search/integral")
  public void searchUserIntegralByOrder(String orderNoes, HttpServletResponse response)
      throws IOException {
    String[] orderNoArray = orderNoes.split("\\n");

    Map<Integer, UserIntegralAndCoupon> uicMap =
        new LinkedHashMap<Integer, UserIntegralAndCoupon>();
    StringBuilder sbd = new StringBuilder();
    for (String orderNo : orderNoArray) {
      if (StringUtils.isBlank(orderNo) || NumberUtils.toLong(orderNo) <= 0) continue;

      long no = NumberUtils.toLong(orderNo.trim());
      Order order = tradeCenterBossClient.queryOrderByOrderNo(no);
      if (order == null) continue;

      User user = userService.getUserById(order.getUserId());
      if (user == null || uicMap.get(user.getId()) != null) continue;

      UserIntegralAndCoupon uic = new UserIntegralAndCoupon();
      uic.setUserId(user.getId());
      uic.setUserName(user.getUserName());
      uic.setPhone(StringUtils.isNotBlank(user.getPhone()) ? user.getPhone() : "");
      uic.setEmail(StringUtils.isNotBlank(user.getEmail()) ? user.getEmail() : "");
      uic.setIntegral(user.getCurrency());

      List<Coupon> coupons = couponService.queryCouponByUserId(order.getUserId());
      sbd.delete(0, sbd.length());
      int i = 0;
      String str = "";
      for (Coupon coupon : coupons) {
        sbd.append(coupon.getCode());
        if (coupon.isUsed()) str = "已使用";
        else if (coupon.isExpire()) str = "已过期";
        if (StringUtils.isNotBlank(str)) sbd.append("(").append(str).append(")");

        if (i != coupons.size() - 1) sbd.append(", ");

        i++;
      }
      uic.setCoupon(sbd.toString());

      sbd.delete(0, sbd.length());
      // 从地址中去寻找
      List<Address> addresses = addressService.queryAllAddress(order.getUserId());
      i = 0;
      for (Address address : addresses) {
        sbd.append(address.getName()).append("/").append(address.getMobile()).append("/");
        sbd.append(address.getProvince()).append(address.getLocation());
        if (address.isDefaultAddress()) sbd.append("<span style='color:red;'>(默认地址)</span>");

        if (i != addresses.size() - 1) sbd.append("\n");
      }
      uic.setAddress(sbd.toString());

      uicMap.put(user.getId(), uic);
    }
    new JsonResult(true).addData("orderList", uicMap.values()).toJson(response);
  }
  @SuppressWarnings("unchecked")
  @ResponseBody
  @RequestMapping(value = "/order/applyVoucher.ajax", method = RequestMethod.POST)
  public ResponseEntity<byte[]> applyVoucher(
      HttpServletRequest request, @RequestParam(value = "voucherId") String voucherId)
      throws Exception {

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Applying voucher to order");
    }

    Map<String, Object> model = new HashMap<String, Object>();
    voucherId = voucherId == null ? "" : voucherId.trim();

    try {

      boolean success = true;
      String reason = null;

      HttpSession session = request.getSession(true);
      String orderId = (String) session.getAttribute("orderid");
      Order order = null;
      if (orderId != null) {
        order = orderRepository.findByOrderId(orderId);
      }

      if (order != null) {
        if (order.getVoucher() != null) {
          success = false;
          reason = "voucher-already-applied";
        } else {
          Voucher voucher = voucherRepository.findByVoucherId(voucherId);
          if (voucher == null) {
            success = false;
            reason = "voucher-not-found";
          } else {
            if (voucher.isUsed()) {
              success = false;
              reason = "voucher-already-used";
            } else {
              order.setVoucher(voucher);
              order = orderRepository.saveOrder(order);
            }
          }
        }
      }

      // Return processed status
      model.put("success", success);
      model.put("order", order);
      model.put("reason", reason);

    } catch (Exception ex) {
      LOGGER.error("", ex);
      model.put("success", false);
      model.put("reason", "error");
      model.put("message", ex.getMessage());
    }
    return buildOrderResponse(model);
  }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (container == null) {
      return null;
    }

    mainLayout = inflater.inflate(R.layout.full_order_fragment, null);

    if (getArguments() != null) {
      Date date = (Date) getArguments().getSerializable("execDate");
      int orderId = getArguments().getInt("orderId", 0);
      if (date != null) {
        Order order = new Order();
        order.setExecDate(date);
        showOrder(order);
      } else if (orderId != 0) {
        showOrder(Order.getOrderFromBase(orderId));
      }
    } else {
      showOrder(new Order());
    }

    return mainLayout;
  }
  @SuppressWarnings("unchecked")
  @ResponseBody
  @RequestMapping(value = "/order/updateAdditionalInstructions.ajax", method = RequestMethod.POST)
  public ResponseEntity<byte[]> updateAdditionalInstructions(
      @RequestParam(value = "orderId") String orderId,
      @RequestParam(value = "additionalInstructions") String additionalInstructions)
      throws Exception {

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Updating additional instructions for orderId: " + orderId);
    }

    Map<String, Object> model = new HashMap<String, Object>();

    try {
      Order order = orderRepository.findByOrderId(orderId);
      order.setAdditionalInstructions(additionalInstructions);
      order = orderRepository.saveOrder(order);
      model.put("success", true);
      model.put("order", order);
    } catch (Exception ex) {
      LOGGER.error("", ex);
      model.put("success", false);
      model.put("message", ex.getMessage());
    }
    return buildOrderResponse(model);
  }
  @SuppressWarnings("unchecked")
  @ResponseBody
  @RequestMapping(value = "/order/clearOrder.ajax", method = RequestMethod.POST)
  public ResponseEntity<byte[]> clearOrder(
      @RequestParam(value = "orderId") String orderId,
      @RequestParam(value = "restaurantId") String restaurantId)
      throws Exception {

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Clearing order for orderId: " + orderId);
    }

    Map<String, Object> model = new HashMap<String, Object>();

    try {
      Order order = orderRepository.findByOrderId(orderId);
      Restaurant restaurant = restaurantRepository.findByRestaurantId(restaurantId);
      order.setRestaurant(restaurant);
      order.getOrderItems().clear();
      order.getOrderDiscounts().clear();
      order = orderRepository.saveOrder(order);
      model.put("success", true);
      model.put("order", order);
    } catch (Exception ex) {
      LOGGER.error("", ex);
      model.put("success", false);
      model.put("message", ex.getMessage());
    }
    return buildOrderResponse(model);
  }
  public void msgNewOrder(WaiterAgent w, int tableNum, String order) {
    print("msgNewOrder() from Waiter " + w.getName());
    long timeFinish = -1;
    if (findFood(order).amount > 0) {
      timeFinish =
          (System.currentTimeMillis() + (long) ((menu.menuItems.get(order)) * Constants.SECOND));
      int previousInventoryAmount = inventory.get(order);
      inventory.put(order, previousInventoryAmount - 1);
      print("Number of items of type " + order + " left: " + inventory.get(order));

      Order incomingOrder = new Order(w, tableNum, order, timeFinish);
      orders.add(incomingOrder);
      Food f = findFood(order);
      f.amount--;
      if (f.amount <= f.low) {
        marketOrders.add(new MarketOrder(f.choice, f.capacity - f.amount));
        f.ordered = true;
      }
    } else {
      Order incomingOrder = new Order(w, tableNum, order, timeFinish);
      incomingOrder.state = OrderState.UnableToBeSupplied;
      menu.menuList.remove(order);
      orders.add(incomingOrder);
      Food f = findFood(order);
      marketOrders.add(new MarketOrder(f.choice, f.capacity - f.amount));
    }
    stateChanged();
  }
  public void testChanged() throws Exception {

    Order po = OrderMother.makeOrder();
    save(po.getRestaurant());
    save(po);
    final Serializable orderId = po.getId();

    Order detachedOrder = am.detach(po);

    doWithTransaction(
        new TxnCallback() {
          public void execute() throws Exception {
            Order po = (Order) load(Order.class, orderId.toString());
            po.noteSent("msgid", new Date());
            po.accept("x");
          }
        });

    try {
      Order attachedOrder = am.attach(detachedOrder);
      fail("Expected exception");
    } catch (OptimisticLockingFailureException e) {

    }
  }
  protected boolean pickAndExecuteAnAction() {

    synchronized (orders) {
      for (Order o : orders) {
        if (o.state == OrderState.UnableToBeSupplied) {
          TellWaiterWeAreOut(o);
          return true;
        }
      }
    }
    synchronized (orders) {
      for (Order o : orders) {
        if (o.state == OrderState.NotReady) {
          o.state = OrderState.BeingPrepared;
          PrepareOrder(o);
          return true;
        }
      }
    }
    synchronized (orders) {
      for (Order o : orders) {
        if (o.state == OrderState.Ready) {
          OrderIsReady(o);
          return true;
        }
      }
    }
    synchronized (marketOrders) {
      for (MarketOrder mo : marketOrders) {
        if (mo.os == moState.pending) {
          print("Ordering " + mo.amount + " " + mo.food + "'s");
          mo.os = moState.ordered;
          print("COWABUNGA ordering from market");
          goToMarket(restaurant, "Italian", mo.amount, mo.id);
          return true;
        }
      }
    }
    // Producer-consumer handling
    StandOrder orderFromStand = restaurant.revolvingStand.remove();
    if (orderFromStand != null) {

      WaiterAgent standWaiter = orderFromStand.waiter;
      int standTableNum = orderFromStand.tableNum;
      String standOrderType = orderFromStand.order;

      if (menu.menuItems.containsKey(orderFromStand.order)
          && inventory.get(orderFromStand.order) > 0) {
        long timeFinish =
            (System.currentTimeMillis()
                + (long) ((menu.menuItems.get(standOrderType)) * Constants.SECOND));
        Order newStandOrder = new Order(standWaiter, standTableNum, standOrderType, timeFinish);
        AddNewOrderFromStand(newStandOrder);
      }
      return true;
    }
    return false;
  }
Exemple #9
0
  public Order getOrder(int[] spotPrices, int[] futurePrices, int pos, long money, int restDay) {

    Order order = new Order();
    // Decide buy or sell based on difference of the last two futures prices.
    int price1 = futurePrices[futurePrices.length - 1];
    int price2 = futurePrices[futurePrices.length - 2];
    if (price1 > 0 && price2 > 0) {
      if (price1 < price2) {
        order.buysell = Order.BUY; // buy if downward trend
      } else if (price1 > price2) {
        order.buysell = Order.SELL; // sell if upward trend
      } else {
        order.buysell = Order.NONE; // no order if price is constant
        return order;
      }
    } else {
      order.buysell = fRandom.nextInt(2) + 1; // randomly by or sell
      // if price is not well defined.
    }
    // Cancel decision if it may increase absolute value of the position
    if (order.buysell == Order.BUY) {
      if (pos > fMaxPosition) {
        order.buysell = Order.NONE;
        return order;
      }
    } else if (order.buysell == Order.SELL) {
      if (pos < -fMaxPosition) {
        order.buysell = Order.NONE;
        return order;
      }
    }
    int prevPrice = getLatestPrice(futurePrices);
    if (prevPrice == -1) {
      prevPrice = getLatestPrice(spotPrices); // use spot price instead
    }
    if (prevPrice == -1) {
      prevPrice = fNominalPrice; // use nominal value instead
    }
    while (true) {
      order.price = prevPrice + (int) (fWidthOfPrice * fRandom.nextGaussian());
      if (order.price > 0) {
        break;
      }
    }
    order.quant = fMinQuant + fRandom.nextInt(fMaxQuant - fMinQuant + 1);
    // Message
    message(
        Order.buySellToString(order.buysell)
            + ", price = "
            + order.price
            + ", volume = "
            + order.quant
            + " (trend = "
            + (price1 - price2)
            + "  )");
    return order;
  }
  @Test
  @Ignore
  public void anOrderCanBeShipped() throws Exception {
    Order order = new Order("x", "y", "z");
    assertEquals(false, order.isShipped());

    order.ship();

    assertEquals("order should be shipped", true, order.isShipped());
  }
 /**
  * @param session
  * @param restaurantId
  * @return
  */
 private Order buildAndRegister(HttpSession session, String restaurantId) {
   Order order = orderRepository.create();
   Restaurant restaurant = restaurantRepository.findByRestaurantId(restaurantId);
   order.setRestaurantId(restaurantId);
   order.setRestaurant(restaurant);
   order = orderRepository.save(order);
   session.setAttribute("orderid", order.getOrderId());
   session.removeAttribute("completedorderid");
   return order;
 }
  /**
   * 显示订单的收货信息,客服可修改,修改的和原来的用-隔开
   *
   * @param orderId
   * @param response
   * @throws IOException
   */
  @RequestMapping(value = "/order/addressInfo/{orderId}")
  public void addressInfoGrid(@PathVariable("orderId") long orderId, HttpServletResponse response)
      throws IOException {
    AddressInfo addressInfo = new AddressInfo();
    Logistics logistics = tradeCenterBossClient.queryLogisticsByOrderId(orderId);
    LogisticsRedundancy logisticsRedundancy =
        tradeCenterBossClient.queryLogisticsRedundancy(logistics.getId());
    Order order = tradeCenterBossClient.queryOrderById(orderId);
    List<AddressInfo> list = new LinkedList<AddressInfo>();
    if (order != null) {
      addressInfo.setOrderState(order.getOrderState().toString());
      String[] province = (logistics.getProvince()).split(",");
      if (province.length == 2) {
        addressInfo.setProvince(province[0]);
        addressInfo.setCity(province[0]);
        addressInfo.setDistricts(province[1]);
      } else {
        addressInfo.setProvince(province[0]);
        addressInfo.setCity(province[1]);
        addressInfo.setDistricts(province[2]);
      }
      addressInfo.setConsignee(logistics.getName());
      addressInfo.setLocation(logistics.getLocation());
      addressInfo.setMobile(logistics.getMobile());
      addressInfo.setZipCode(logistics.getZipCode());

      if (StringUtils.isNotEmpty(logisticsRedundancy.getNameRewrite())) {
        addressInfo.setConsignee(
            addressInfo.getConsignee() + Old_New_Gap + logisticsRedundancy.getNameRewrite());
      }
      if (StringUtils.isNotEmpty(logisticsRedundancy.getLocationRewrite())) {
        addressInfo.setLocation(
            addressInfo.getLocation() + Old_New_Gap + logisticsRedundancy.getLocationRewrite());
      }
      if (StringUtils.isNotEmpty(logisticsRedundancy.getMobileRewrite())) {
        addressInfo.setMobile(
            addressInfo.getMobile() + Old_New_Gap + logisticsRedundancy.getMobileRewrite());
      }
      if (StringUtils.isNotEmpty(logisticsRedundancy.getZipCodeRewrite())) {
        addressInfo.setZipCode(
            addressInfo.getZipCode() + Old_New_Gap + logisticsRedundancy.getZipCodeRewrite());
      }

      String provinceRewrite = logisticsRedundancy.getProvinceRewrite();
      if (StringUtils.isNotEmpty(provinceRewrite)) {
        String[] newProvince = (logisticsRedundancy.getProvinceRewrite()).split(",");
        addressInfo.setProvince(addressInfo.getProvince() + Old_New_Gap + newProvince[0]);
        addressInfo.setCity(addressInfo.getCity() + Old_New_Gap + newProvince[1]);
        addressInfo.setDistricts(addressInfo.getDistricts() + Old_New_Gap + newProvince[2]);
      }
      list.add(addressInfo);
    }
    new JsonResult(true).addData("totalCount", 1).addData("result", list).toJson(response);
  }
  private String invoice(Order order) {
    // 不需要开发票
    if (!order.getInvoiceInfo().isInvoice()) return "";

    StringBuilder sbd = new StringBuilder("发票: (");
    sbd.append(order.getInvoiceInfo().getInvoiceType()).append("/");
    sbd.append(order.getInvoiceInfo().getInvoiceTitle().toDesc()).append("/");

    if (StringUtils.isNotBlank(order.getInvoiceInfo().getCompanyName()))
      sbd.append(order.getInvoiceInfo().getCompanyName()).append("/");

    sbd.append(order.getInvoiceInfo().getInvoiceContent()).append(")");
    return sbd.toString();
  }
  // for Instrument code with "#"
  // for IsBuy = true:
  // SumBuy = all confirmed order.Buy.LotBalance + all unconfirmed order.Buy.Lot
  // SumSell = all confirmed order.Sell.LotBalance
  // for IsBuy = false:
  // SumSell = all confirmed order.Sell.LotBalance + all unconfirmed order.Sell.Lot
  // SumBuy = all confirmed order.Buy.LotBalance
  public GetSumLotBSForOpenOrderWithFlagResult getSumLotBSForOpenOrderWithFlag(boolean isBuy) {
    BigDecimal[] sumLot = new BigDecimal[] {BigDecimal.ZERO, BigDecimal.ZERO};
    boolean isExistsUnconfirmedOrder = false;
    HashMap<Guid, Transaction> accountInstrumentTransactions =
        this.getAccountInstrumentTransactions();
    for (Iterator<Transaction> iterator = accountInstrumentTransactions.values().iterator();
        iterator.hasNext(); ) {
      Transaction transaction = iterator.next();
      if (transaction.get_Phase() == Phase.Executed
          || transaction.get_Phase() == Phase.Placing
          || transaction.get_Phase() == Phase.Placed) {
        for (Iterator<Order> iterator2 = transaction.get_Orders().values().iterator();
            iterator2.hasNext(); ) {
          Order order = iterator2.next();
          if (order.get_LotBalance().compareTo(BigDecimal.ZERO) > 0) {
            if (isBuy) {
              if (order.get_IsBuy()) {
                if (transaction.get_Phase() == Phase.Executed) {
                  sumLot[0] = sumLot[0].add(order.get_LotBalance());
                } else {
                  sumLot[0] = sumLot[0].add(order.get_Lot());
                  isExistsUnconfirmedOrder = true;
                }
              } else {
                if (transaction.get_Phase() == Phase.Executed) {
                  sumLot[1] = sumLot[1].add(order.get_LotBalance());
                }
              }
            } else {
              if (order.get_IsBuy()) {
                if (transaction.get_Phase() == Phase.Executed) {
                  sumLot[0] = sumLot[0].add(order.get_LotBalance());
                }
              } else {
                if (transaction.get_Phase() == Phase.Executed) {
                  sumLot[1] = sumLot[1].add(order.get_LotBalance());
                } else {
                  sumLot[1] = sumLot[1].add(order.get_Lot());
                  isExistsUnconfirmedOrder = true;
                }
              }
            }
          }
        }
      }
    }

    return new GetSumLotBSForOpenOrderWithFlagResult(
        sumLot[0], sumLot[1], isExistsUnconfirmedOrder);
  }
 /**
  * 订单价格备注详情
  *
  * @param orderId
  * @param response
  * @throws IOException
  */
 @RequestMapping(value = "/order/priceMessageDetail/{orderId}")
 public void priceMessageDetailByOrderId(
     @PathVariable("orderId") long orderId, HttpServletResponse response) throws IOException {
   OrderDetail orderDetail = new OrderDetail();
   List<OrderDetail> list = new LinkedList<OrderDetail>();
   Order order = tradeCenterBossClient.queryOrderById(orderId);
   if (order.getPriceMessageDetail() != null) {
     orderDetail.setPriceMessageDetail(order.getPriceMessageDetail());
     list.add(orderDetail);
   }
   new JsonResult(true)
       .addData("totalCount", list.size())
       .addData("result", list)
       .toJson(response);
 }
 public static void addOrderToDB(Order o) {
   Customer customer = CustomerServiceImpl.getCustomer(o.getCustomerID());
   customer.setOrders(OrderServiceImpl.retrieveUnpaidOrders(customer));
   customer.addOrder(o);
   if (customer.getOrders().contains(o)) {
     orderDAO.addOrder(o);
     List<OrderItem> items = o.getItems();
     Inventory inventory = new Inventory(InventoryServiceImpl.getAllAvailableProductsInDB());
     for (OrderItem i : items) {
       Product product = ProductServiceImpl.getProduct(i.getItemSKUNumber());
       InventoryItem inventoryitem = InventoryServiceImpl.getInventoryItem(inventory, product);
       InventoryServiceImpl.deductFromInventory(inventory, inventoryitem, i.getQuantity());
     }
   }
 }
  @Test
  @Ignore
  public void shippedOrdersAreNotShown() throws Exception {
    Order shipped = new Order("X");
    Order notShipped = new Order("Y");
    orders.addAll(asList(shipped, notShipped));
    shipped.ship();

    when(request.getMethod()).thenReturn("GET");
    when(request.getRequestURI()).thenReturn("/orders");

    ordersController.service();

    verify(ordersView).show(asList(notShipped));
  }
  @Test
  @Ignore
  public void theControllerWillShipAnOrder() throws Exception {
    Order order = new Order("5555", "_", "_");
    orders.add(order);

    when(request.getMethod()).thenReturn("POST");
    when(request.getRequestURI()).thenReturn("/orders/shipped");
    when(request.getParameter("order_code")).thenReturn("5555");

    ordersController.service();

    assertEquals("controller should set shipped", true, order.isShipped());
    verify(ordersView).refresh();
  }
 public void orderTest() {
   Customer customer = customerDAO.getCustomerById(3);
   List<Commodity> commodityList = commoDAO.getCommoditiesByIdString("2;3;4");
   List<OrderCommodityRel> relationLsit = CommodityListTools.commoToRel(commodityList);
   Order order = new Order(customer, relationLsit, 100);
   Map<Integer, Integer> map = new HashMap<Integer, Integer>();
   map.put(2, 2);
   map.put(3, 4);
   map.put(4, 4);
   order.setBuyNum(map);
   Date date = new Date();
   order.setOrderTime(new Timestamp(date.getTime()));
   orderDAO.createOrder(order);
   System.out.println(order.getOrderId());
 }
 public void run() {
   try {
     while (!Thread.interrupted()) {
       // Blocks until an order appears:
       Order order = restaurant.orders.take();
       Food requestedItem = order.item();
       // Time to prepare order:
       TimeUnit.MILLISECONDS.sleep(rand.nextInt(500));
       Plate plate = new Plate(order, requestedItem);
       order.getWaitPerson().filledOrders.put(plate);
     }
   } catch (InterruptedException e) {
     print(this + " interrupted");
   }
   print(this + " off duty");
 }
  private String buildInvoice() {
    double taxRate = 6;
    String message;

    this.grandTotal = ((taxRate / 100) * this.subtotal) + this.subtotal;

    DateFormat dateFormat = new SimpleDateFormat("dd/MM/YY HH:mm:ss z");
    this.transDate = new Date();

    message = "Date: " + dateFormat.format(this.transDate) + "\n\n";
    message += "Number of line items: " + this.totalItems + "\n\n";
    message += "Item# / ID / Title / Price / Qty / Disc % / Subtotal:\n\n";
    int counter = 0;
    for (Item i : order.getOrder()) {
      counter++;
      message += counter + ". " + i.toString() + "\n";
    }
    message += "\n";
    message += "Order subtotal: " + formatter.format(this.subtotal) + "\n\n";
    message += "Tax rate: " + taxRate + "%\n\n";
    message += "Tax amount: " + formatter.format(((taxRate / 100) * this.subtotal)) + "\n\n";
    message += "Order total: " + formatter.format(this.grandTotal) + "\n\n";
    message += "Thanks for shopping at Funky Town Books\n\n";

    return message;
  }
 private void DeliverOrder(Order o) {
   print("Delivering " + o);
   // marketGui.DoPlateIt(/*o.choicename*/);
   cashier.msgRestockingBill(this, o.food.type, o.food.orderamt * o.food.price);
   o.c.msgOrderDone(this, o.food.type, o.food.orderamt);
   o.s = OrderState.finished;
 }
Exemple #23
0
 public Order copy() {
   Order dst = new Order();
   dst.date = date == null ? null : date.copy();
   dst.subject = subject == null ? null : subject.copy();
   dst.source = source == null ? null : source.copy();
   dst.target = target == null ? null : target.copy();
   dst.reason = reason == null ? null : reason.copy();
   dst.authority = authority == null ? null : authority.copy();
   dst.when = when == null ? null : when.copy(dst);
   dst.detail = new ArrayList<ResourceReference>();
   for (ResourceReference i : detail) dst.detail.add(i.copy());
   return dst;
 }
 private void saveOrder(Order orderToSave) {
   valueList.put("_id", currentOrder.getOrderId());
   for (EditText fieldToSave : editFields) {
     if (fieldToSave.getText() != null) {
       valueList.put(fieldToSave.getTag().toString(), fieldToSave.getText().toString());
     }
   }
   orderToSave.setOrderValues(valueList);
   if (orderToSave.save()) {
     Toast toast =
         Toast.makeText(
             MainActivity.appContext,
             "Order " + orderToSave.getOrderId() + " saved",
             Toast.LENGTH_LONG);
     toast.show();
   }
 }
 public void RestockDone(Order o) {
   o.food.inventory = o.food.inventory - o.food.orderamt;
   o.s = OrderState.done;
   print("Done restocking " + o.food);
   System.out.print(o.food.inventory + "\n");
   // o.c.msgOrderDone(o.food.type);
   stateChanged();
 }
  @SuppressWarnings("unchecked")
  @ResponseBody
  @RequestMapping(value = "/order/updateItemQuantity.ajax", method = RequestMethod.POST)
  public ResponseEntity<byte[]> updateItemQuantity(
      HttpServletRequest request, @RequestParam(value = "body") String body) throws Exception {

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Updating order items: " + body);
    }

    Map<String, Object> model = new HashMap<String, Object>();

    try {
      // Extract request parameters
      Map<String, Object> params = (Map<String, Object>) jsonUtils.deserialize(body);
      String orderItemId = (String) params.get("orderItemId");
      Integer quantity = (Integer) params.get("quantity");

      HttpSession session = request.getSession(true);
      String orderId = (String) session.getAttribute("orderid");
      Order order = null;
      if (orderId != null) {
        order = orderRepository.findByOrderId(orderId);
        if (order != null) {
          order.updateItemQuantity(orderItemId, quantity);
          order = orderRepository.saveOrder(order);
          // Update can checkout status of order
          session.setAttribute("cancheckout", order.getCanCheckout());

          // Update order restaurant id session attribute if any items present
          if (order.getOrderItems().size() > 0) {
            session.setAttribute("orderrestaurantid", order.getRestaurantId());
            session.setAttribute("orderrestauranturl", order.getRestaurant().getUrl());
          } else {
            // If the restaurant session id does not match the order restaurant id, update the order
            String restaurantId = (String) session.getAttribute("restaurantid");
            if (!order.getRestaurantId().equals(restaurantId)) {
              Restaurant restaurant = restaurantRepository.findByRestaurantId(restaurantId);
              order.setRestaurant(restaurant);
              order = orderRepository.save(order);
            }
            session.removeAttribute("orderrestaurantid");
            session.removeAttribute("orderrestauranturl");
          }
        }
      }
      model.put("success", true);
      model.put("order", order);
    } catch (Exception ex) {
      LOGGER.error("", ex);
      model.put("success", false);
      model.put("message", ex.getMessage());
    }
    return buildOrderResponse(model);
  }
  @SuppressWarnings("unchecked")
  @ResponseBody
  @RequestMapping(value = "/order/getOrder.ajax", method = RequestMethod.POST)
  public ResponseEntity<byte[]> getOrder(HttpServletRequest request) throws Exception {

    Map<String, Object> model = new HashMap<String, Object>();

    try {
      HttpSession session = request.getSession(true);
      String orderId = (String) session.getAttribute("orderid");
      String restaurantId = (String) session.getAttribute("restaurantid");
      Order order = null;
      if (orderId != null) {
        order = orderRepository.findByOrderId(orderId);

        // If the current order has no items but is linked to another restauarant, update it now
        if (order.getOrderItems().size() == 0 && !order.getRestaurantId().equals(restaurantId)) {
          order.setRestaurant(restaurantRepository.findByRestaurantId(restaurantId));
        }
        order.updateCosts();

        // Update can checkout status of order
        session.setAttribute("cancheckout", order.getCanCheckout());
        session.setAttribute("cansubmitpayment", order.getCanSubmitPayment());
      }

      model.put("success", true);
      model.put("order", order);
    } catch (Exception ex) {
      LOGGER.error("", ex);
      model.put("success", false);
      model.put("message", ex.getMessage());
    }
    return buildOrderResponse(model);
  }
 private int getOrder(@NotNull Object o) {
   Queue<Class<?>> toCheck = new ArrayDeque<Class<?>>();
   toCheck.add(o.getClass());
   while (!toCheck.isEmpty()) {
     Class<?> clazz = toCheck.poll();
     Order annotation = clazz.getAnnotation(Order.class);
     if (annotation != null) {
       return annotation.value();
     }
     Class<?> c = clazz.getSuperclass();
     if (c != null) {
       toCheck.add(c);
     }
     Class<?>[] interfaces = clazz.getInterfaces();
     Collections.addAll(toCheck, interfaces);
   }
   return ExternalSystemConstants.UNORDERED;
 }
  private String remark(Order order) {
    StringBuilder sbd = new StringBuilder();
    String invoice = invoice(order);
    String message = message(order.getId());

    sbd.append(invoice);
    if (StringUtils.isNotBlank(invoice) && StringUtils.isNotBlank(message)) sbd.append("\n");
    sbd.append(message);

    return sbd.toString();
  }
  /*
  Remarks
  sum (SellLotBalance) = all confirmed order.Sell.LotBalance
    + unconfirmed order (stop).Sell.Lot
    + iif("MOC/MOO allow New" = False,
   unconfirmed order (MOO/MOC).Sell.Lot,
   0)

  sum (BuyLotBalance) = all confirmed order.Buy.LotBalance
    + unconfirmed order (stop).Buy.Lot
    + iif("MOC/MOO allow New" = False,
   unconfirmed order (MOO/MOC).Buy.Lot,
   0)
  */
  public BigDecimal[] getSumLotBSForMakeStopOrder() {
    BigDecimal[] sumLot = new BigDecimal[] {BigDecimal.ZERO, BigDecimal.ZERO};
    TradePolicyDetail tradePolicyDetail = this.getTradePolicyDetail();
    HashMap<Guid, Transaction> accountInstrumentTransactions =
        this.getAccountInstrumentTransactions();
    for (Iterator<Transaction> iterator = accountInstrumentTransactions.values().iterator();
        iterator.hasNext(); ) {
      Transaction transaction = iterator.next();
      if (transaction.get_Phase() == Phase.Executed) {
        for (Iterator<Order> iterator2 = transaction.get_Orders().values().iterator();
            iterator2.hasNext(); ) {
          Order order = iterator2.next();
          if (order.get_LotBalance().compareTo(BigDecimal.ZERO) > 0) {
            if (order.get_IsBuy()) {
              sumLot[0] = sumLot[0].add(order.get_LotBalance());
            } else {
              sumLot[1] = sumLot[1].add(order.get_LotBalance());
            }
          }
        }
      } else if (transaction.get_Phase() == Phase.Placing
          || transaction.get_Phase() == Phase.Placed) {
        for (Iterator<Order> iterator2 = transaction.get_Orders().values().iterator();
            iterator2.hasNext(); ) {
          Order order = iterator2.next();
          if (order.get_TradeOption() == TradeOption.Stop
              || (!tradePolicyDetail.get_IsAcceptNewMOOMOC()
                  && (transaction.get_OrderType() == OrderType.MarketOnOpen
                      || transaction.get_OrderType() == OrderType.MarketOnClose))) {
            if (order.get_IsBuy()) {
              sumLot[0] = sumLot[0].add(order.get_Lot());
            } else {
              sumLot[1] = sumLot[1].add(order.get_Lot());
            }
          }
        }
      }
    }
    return sumLot;
  }