Ejemplo n.º 1
1
  @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);
  }
Ejemplo n.º 2
0
  public synchronized void run() {
    CookMessage("been started");
    while (getLoggedIn()) {

      Order order = WaitingOrders.poll();

      if (order == null) {
        // request a new order
        cookClient.outQueue.OutQueue.add("CookOrderRequest");
        try {
          cookClient.cookGUI.setCurrentlyCooking("Awaiting new order");
          wait();
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } else {
        try {
          // update the gui
          cookClient.cookGUI.setCurrentlyCooking(order.getOrderNumber().toString());
          wait(GetRandomWaitTime());
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        order.setCookedAtNow();
        order.setOrderStatus(OrderStatus.cooked);
        cookClient.outQueue.OutQueue.add(order); // pass back to server
      }
    }
    // TODO: if they still have incomplete orders do something
  }
Ejemplo n.º 3
0
  public double calculateMaximumDrawdown() {
    double bal = openingBalance;
    double low = bal;
    double high = bal;
    double maxDD = 0.0;

    for (Order order : orders) {
      bal += order.getProfitLoss();

      if (bal > high) {
        high = bal;
        low = bal;
      } else if (bal < low) {
        low = bal;
      }

      double dd = high - low;

      if (dd > maxDD) {
        maxDD = dd;
      }
    }

    return maxDD;
  }
 public void orderSorting() {
   for (int i = 0; i < this.order.size(); i++) {
     Order order1 = this.order.get(i);
     for (int p = 0; p < this.order.size(); p++) {
       Order order2 = this.order.get(p);
       int compare = order1.compareTo(order2);
       if (compare % 10 < 2) {
         int order1Index = this.order.indexOf(order1);
         this.order.remove(p);
         this.order.add(p, order1);
         this.order.remove(order1Index);
         this.order.add(order1Index, order2);
         order1 = order2;
       }
     }
   }
   for (int i = 0; i < this.order.size(); i++) {
     Order order1 = this.order.get(i);
     for (int p = 0; p < this.order.size(); p++) {
       Order order2 = this.order.get(p);
       int compare = order1.compareTo(order2);
       if ((compare / 1000 < 2) && (compare % 10 == 0)) {
         int order1Index = this.order.indexOf(order1);
         this.order.remove(p);
         this.order.add(p, order1);
         this.order.remove(order1Index);
         this.order.add(order1Index, order2);
         order1 = order2;
       }
     }
   }
 }
  @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;
  }
  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();
  }
  @Test
  public void testGetMultiValueConstraints() throws Exception {
    Engine engine = new Engine();
    Field[] fields = engine.getClass().getDeclaredFields();
    assertNotNull(fields);
    assertTrue(fields.length == 1);
    ReflectionHelper.setAccessibility(fields[0]);

    Annotation annotation = fields[0].getAnnotation(Pattern.List.class);
    assertNotNull(annotation);
    List<Annotation> multiValueConstraintAnnotations =
        constraintHelper.getMultiValueConstraints(annotation);
    assertTrue(
        multiValueConstraintAnnotations.size() == 2, "There should be two constraint annotations");
    assertTrue(
        multiValueConstraintAnnotations.get(0) instanceof Pattern, "Wrong constraint annotation");
    assertTrue(
        multiValueConstraintAnnotations.get(1) instanceof Pattern, "Wrong constraint annotation");

    Order order = new Order();
    fields = order.getClass().getDeclaredFields();
    assertNotNull(fields);
    assertTrue(fields.length == 1);
    ReflectionHelper.setAccessibility(fields[0]);

    annotation = fields[0].getAnnotation(NotNull.class);
    assertNotNull(annotation);
    multiValueConstraintAnnotations = constraintHelper.getMultiValueConstraints(annotation);
    assertTrue(
        multiValueConstraintAnnotations.size() == 0, "There should be no constraint annotations");
  }
  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) {

    }
  }
  public ExpressionProtos.WindowFunction toProtoBuf() {
    ExpressionProtos.WindowFunction.Builder builder = ExpressionProtos.WindowFunction.newBuilder();
    builder.setProject(project);
    builder.setName(name);
    builder.setIsDistinct(distinct);

    for (ScalarExpression param : parameters) {
      builder.addParameters(param.toProtoBuf());
    }

    for (ScalarExpression pb : partitionBy) {
      builder.addPartitionBy(pb.toProtoBuf());
    }

    if (sortBy != null && sortBy.size() > 0) {
      for (Order order : sortBy) {
        builder.addOrderBy(order.toProtoBuf());
      }
    }

    if (windowing != null) {
      builder.setWindowingClause(windowing.toProtoBuf());
    }

    return builder.build();
  }
Ejemplo n.º 10
0
 private BigDecimal calculateTotalSalesTax() {
   BigDecimal salesTax = BigDecimal.ZERO;
   for (Order order : orders) {
     salesTax = salesTax.add(order.calculateSalesTax());
   }
   return salesTax;
 }
Ejemplo n.º 11
0
  public Map<String, Object> lista(Map<String, Object> params) {
    log.debug("Buscando lista de facturas con params {}", params);
    if (params == null) {
      params = new HashMap<>();
    }

    if (!params.containsKey("max")) {
      params.put("max", 10);
    } else {
      params.put("max", Math.min((Integer) params.get("max"), 100));
    }

    if (params.containsKey("pagina")) {
      Long pagina = (Long) params.get("pagina");
      Long offset = (pagina - 1) * (Integer) params.get("max");
      params.put("offset", offset.intValue());
    }

    if (!params.containsKey("offset")) {
      params.put("offset", 0);
    }
    Criteria criteria = currentSession().createCriteria(FacturaAlmacen.class);
    Criteria countCriteria = currentSession().createCriteria(FacturaAlmacen.class);

    if (params.containsKey("almacen")) {
      criteria.createCriteria("almacen").add(Restrictions.idEq(params.get("almacen")));
      countCriteria.createCriteria("almacen").add(Restrictions.idEq(params.get("almacen")));
    }

    if (params.containsKey("filtro")) {
      String filtro = (String) params.get("filtro");
      Disjunction propiedades = Restrictions.disjunction();
      propiedades.add(Restrictions.ilike("folio", filtro, MatchMode.ANYWHERE));
      criteria.add(propiedades);
      countCriteria.add(propiedades);
    }

    if (params.containsKey("order")) {
      String campo = (String) params.get("order");
      if (params.get("sort").equals("desc")) {
        criteria.addOrder(Order.desc(campo));
      } else {
        criteria.addOrder(Order.asc(campo));
      }
    } else {
      criteria.createCriteria("estatus").addOrder(Order.asc("prioridad"));
    }
    criteria.addOrder(Order.desc("fechaModificacion"));

    if (!params.containsKey("reporte")) {
      criteria.setFirstResult((Integer) params.get("offset"));
      criteria.setMaxResults((Integer) params.get("max"));
    }
    params.put("facturas", criteria.list());

    countCriteria.setProjection(Projections.rowCount());
    params.put("cantidad", (Long) countCriteria.list().get(0));

    return params;
  }
 @org.junit.Test()
 public void testRemoveItem() throws Exception {
   order.addItem(item);
   int totalCount = order.total();
   order.removeItem(item);
   assertEquals(totalCount - order.total(), 1);
 }
Ejemplo n.º 13
0
 private BigDecimal calculateTotalAmount() {
   BigDecimal totalAmount = BigDecimal.ZERO;
   for (Order order : orders) {
     totalAmount = totalAmount.add(order.calculateTotalAmount());
   }
   return totalAmount;
 }
Ejemplo n.º 14
0
 private String getOrderDetails() {
   StringBuilder output = new StringBuilder();
   for (Order order : orders) {
     output.append(order.toString());
   }
   return output.toString();
 }
Ejemplo n.º 15
0
 private BigDecimal outstanding() {
   BigDecimal outstanding = BigDecimal.ZERO;
   for (Order order : orders) {
     outstanding = outstanding.add(order.getPrice());
   }
   return outstanding;
 }
  boolean equals(Order other) {
    if (other.getKind() == Kind.ANY && kind == Kind.ANY) return true;

    if (kind != other.getKind()) return false;

    return attrNames.equals(other.getAttrNames());
  }
Ejemplo n.º 17
0
  @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);
  }
Ejemplo n.º 18
0
  @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);
  }
Ejemplo n.º 19
0
  public void testReceivesWithTemplates() throws Exception {
    if (!isPrereqsMet("org.mule.providers.gs.GSFunctionalTestCase.testReceivesWithTemplates()")) {
      return;
    }

    MuleClient client = new MuleClient();
    Order order = new Order();
    order.setProcessed(Boolean.FALSE);
    client.send("gs:java://localhost/mule-space_container/mule-space?schema=cache", order, null);
    Thread.sleep(2000L);

    assertEquals(1, unprocessedCount);
    assertEquals(0, processedCount);
    client.send("gs:java://localhost/mule-space_container/mule-space?schema=cache", order, null);
    Thread.sleep(1000L);
    assertEquals(2, unprocessedCount);
    assertEquals(0, processedCount);

    order.setProcessed(Boolean.TRUE);
    client.send("gs:java://localhost/mule-space_container/mule-space?schema=cache", order, null);
    Thread.sleep(1000L);
    assertEquals(1, processedCount);
    assertEquals(2, unprocessedCount);
    client.send("gs:java://localhost/mule-space_container/mule-space?schema=cache", order, null);
    Thread.sleep(1000L);
    assertEquals(2, processedCount);
    assertEquals(2, unprocessedCount);
  }
Ejemplo n.º 20
0
  /**
   * Queries the given customer's order with the given identity.
   *
   * @param alias the customer alias
   * @param passwordHash the customer password-hash
   * @param orderIdentity the order identity
   * @return the customer's order
   * @throws IllegalStateException if the login data is invalid
   * @throws SQLException if there is a problem with the underlying JDBC connection
   */
  public Order queryOrder(final String alias, final byte[] passwordHash, final long orderIdentity)
      throws SQLException {
    final Order order = new Order();
    final Customer customer = this.queryCustomer(alias, passwordHash);

    synchronized (this.connection) {
      try (PreparedStatement statement = this.connection.prepareStatement(SQL_SELECT_PURCHASE)) {
        statement.setLong(1, orderIdentity);

        try (ResultSet resultSet = statement.executeQuery()) {
          if (!resultSet.next()) throw new IllegalStateException("purchase doesn't exist.");
          if (customer.getIdentity() != resultSet.getLong("customerIdentity"))
            throw new IllegalStateException("purchase not created by given customer.");

          order.setIdentity(resultSet.getLong("identity"));
          order.setCustomerIdentity(resultSet.getLong("customerIdentity"));
          order.setCreationTimestamp(resultSet.getLong("creationTimestamp"));
          order.setTaxRate(resultSet.getDouble("taxRate"));
        }
      }
    }

    this.populateOrderItems(order);
    return order;
  }
Ejemplo n.º 21
0
  /**
   * Queries the given customer's orders.
   *
   * @param alias the customer alias
   * @param passwordHash the customer password-hash
   * @return the customer's orders
   * @throws IllegalStateException if the login data is invalid
   * @throws SQLException if there is a problem with the underlying JDBC connection
   */
  public SortedSet<Order> queryOrders(final String alias, final byte[] passwordHash)
      throws SQLException {
    final SortedSet<Order> orders = new TreeSet<Order>();
    final Customer customer = this.queryCustomer(alias, passwordHash);

    synchronized (this.connection) {
      try (PreparedStatement statement = this.connection.prepareStatement(SQL_SELECT_PURCHASES)) {
        statement.setLong(1, customer.getIdentity());

        try (ResultSet resultSet = statement.executeQuery()) {
          while (resultSet.next()) {
            final Order purchase = new Order();
            purchase.setIdentity(resultSet.getLong("identity"));
            purchase.setCustomerIdentity(resultSet.getLong("customerIdentity"));
            purchase.setCreationTimestamp(resultSet.getLong("creationTimestamp"));
            purchase.setTaxRate(resultSet.getDouble("taxRate"));
            orders.add(purchase);
          }
        }
      }
    }

    for (final Order purchase : orders) {
      this.populateOrderItems(purchase);
    }

    return orders;
  }
Ejemplo n.º 22
0
  @Override
  public int compare(Order o1, Order o2) {
    int result = o2.price().compare(o1.price());
    if (result != 0) return result;

    return new Long(o1.timeStamp()).compareTo(new Long(o2.timeStamp()));
  }
Ejemplo n.º 23
0
  /**
   * Cancels an order. Note that cancel requests for orders will be rejected if they are older than
   * one hour, or don't target the given customer.
   *
   * @param alias the customer alias
   * @param passwordHash the customer password-hash
   * @param orderIdentity the order identity
   * @throws IllegalStateException if the login data is invalid, if the order is too old, or if it
   *     is not targeting the given customer
   * @throws SQLException if there is a problem with the underlying JDBC connection
   */
  public void deleteOrder(final String alias, final byte[] passwordHash, final long orderIdentity)
      throws SQLException {
    final Customer customer = this.queryCustomer(alias, passwordHash);
    final Order order = this.queryOrder(alias, passwordHash, orderIdentity);
    if (order.getCustomerIdentity() != customer.getIdentity())
      throw new IllegalStateException("purchase not created by given customer.");
    if (System.currentTimeMillis() > order.getCreationTimestamp() + TimeUnit.HOURS.toMillis(1))
      throw new IllegalStateException("purchase too old.");

    synchronized (this.connection) {
      try (PreparedStatement statement = this.connection.prepareStatement(SQL_DELETE_PURCHASE)) {
        statement.setLong(1, orderIdentity);
        statement.executeUpdate();
      }
    }

    for (final OrderItem item : order.getItems()) {
      synchronized (this.connection) {
        try (PreparedStatement statement =
            this.connection.prepareStatement(SQL_RELEASE_ARTICLE_UNITS)) {
          statement.setLong(1, item.getCount());
          statement.setLong(2, item.getArticleIdentity());
          statement.executeUpdate();
        }
      }
    }
  }
Ejemplo n.º 24
0
 public void update() {
   for (Order o : PendingOrders) {
     if (o.getClient().getStateConstant() == CCState.Approved) {
       ApprovedOrders.add(PendingOrders.get(PendingOrders.indexOf(o)));
     }
   }
 }
Ejemplo n.º 25
0
  @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);
  }
Ejemplo n.º 26
0
  /**
   * 构造子查询sql
   *
   * @param table
   * @param refKey
   * @param ids
   * @param ordersMap
   * @param fieldName
   * @return
   */
  private String buildChildQuerySql(
      String table,
      String refKey,
      StringBuffer ids,
      Map<String, Orders> ordersMap,
      String fieldName) {
    StringBuffer childSql = new StringBuffer();
    childSql
        .append("select * from ")
        .append(NameConverter.toTableName(Constants.DEFAULT_TABLE_PREFIX, table))
        .append(" where ")
        .append(NameConverter.toColumnName(Constants.DEFAULT_COLUMN_PREFIX, refKey))
        .append(" in (");
    childSql.append(ids);
    childSql.append(")");

    Orders orders = ordersMap.get(fieldName);
    if (orders != null && orders.value().length > 0) {
      childSql.append(" order by ");
      for (Order order : orders.value()) {
        childSql
            .append(NameConverter.toColumnName(Constants.DEFAULT_COLUMN_PREFIX, order.key()))
            .append(" ")
            .append(order.order())
            .append(",");
      }
      childSql.deleteCharAt(childSql.length() - 1);
    }

    return childSql.toString();
  }
Ejemplo n.º 27
0
 public boolean hasField(String attributeName) {
   for (Order order : this.orders) {
     if (order.getAttr().equals(attributeName)) {
       return true;
     }
   }
   return false;
 }
Ejemplo n.º 28
0
 public Order findOrder(String orderNumber) {
   for (Order o : orders) {
     if (o.getOrderNumber().equals(orderNumber)) {
       return o;
     }
   }
   return null;
 }
 public static Order parseConceptReferenceCode(String code) {
   for (Order candidate : values()) {
     if (candidate.getCodeInEmrConceptSource().equals(code)) {
       return candidate;
     }
   }
   return null;
 }
Ejemplo n.º 30
0
  private void createOrder5(Customer customer) {

    Order order = new Order();
    order.setCustomer(customer);
    order.addShipment(new OrderShipment());

    Ebean.save(order);
  }