Пример #1
0
  public void testShouldCallInsertOrderOnOrderDao() {

    Mock seqDao = mock(SequenceDao.class);
    seqDao.expects(once()).method("getNextId").with(NOT_NULL).will(returnValue(1));

    Mock orderDao = mock(OrderDao.class);
    orderDao.expects(once()).method("insertOrder").with(NOT_NULL);

    Mock itemDao = mock(ItemDao.class);
    itemDao.expects(once()).method("updateAllQuantitiesFromOrder").with(NOT_NULL);

    Mock daoManager = mock(DaoManager.class);
    daoManager.expects(once()).method("startTransaction").withNoArguments();

    daoManager.expects(once()).method("commitTransaction").withNoArguments();

    daoManager.expects(once()).method("endTransaction").withNoArguments();

    OrderService service =
        new OrderService(
            (DaoManager) daoManager.proxy(),
            (ItemDao) itemDao.proxy(),
            (OrderDao) orderDao.proxy(),
            (SequenceDao) seqDao.proxy());
    service.insertOrder(DomainFixture.newTestOrder());
  }
 private void assertEntriesOrder(final OrderModel order) {
   if (!modelService.isNew(order)) {
     Assert.assertEquals(
         "Unexpected product in order entry 1: ",
         product1,
         orderService.getEntryForNumber(order, 0).getProduct());
     Assert.assertEquals(
         "Unexpected product in order entry 2: ",
         product2,
         orderService.getEntryForNumber(order, 1).getProduct());
     Assert.assertEquals(
         "Unexpected product in order entry 3: ",
         product3,
         orderService.getEntryForNumber(order, 2).getProduct());
     Assert.assertEquals(
         "Unexpected product in order entry 4: ",
         product4,
         orderService.getEntryForNumber(order, 3).getProduct());
   }
   Assert.assertEquals(
       "Unexpected product in order entry 1: ", product1, order.getEntries().get(0).getProduct());
   Assert.assertEquals(
       "Unexpected product in order entry 2: ", product2, order.getEntries().get(1).getProduct());
   Assert.assertEquals(
       "Unexpected product in order entry 3: ", product3, order.getEntries().get(2).getProduct());
   Assert.assertEquals(
       "Unexpected product in order entry 4: ", product4, order.getEntries().get(3).getProduct());
 }
Пример #3
0
  public void testShouldCallGetNextIdOnSequenceDao() {

    Mock seqDao = mock(SequenceDao.class);
    seqDao.expects(once()).method("getNextId").with(NOT_NULL).will(returnValue(1));

    OrderService service = new OrderService(null, null, null, (SequenceDao) seqDao.proxy());
    service.getNextId("ordernum");
  }
Пример #4
0
 public void testShouldCallGetOrdersByUsernameOnOrderDao() {
   Mock orderDao = mock(OrderDao.class);
   orderDao
       .expects(once())
       .method("getOrdersByUsername")
       .with(NOT_NULL)
       .will(returnValue(new PaginatedArrayList(5)));
   OrderService service = new OrderService(null, null, (OrderDao) orderDao.proxy(), null);
   service.getOrdersByUsername("j2ee");
 }
Пример #5
0
  public void testShouldCallGetOrderOnOrderDao() {

    Mock orderDao = mock(OrderDao.class);
    orderDao.expects(once()).method("getOrder").with(NOT_NULL).will(returnValue(new Order()));

    Mock daoManager = mock(DaoManager.class);
    daoManager.expects(once()).method("startTransaction").withNoArguments();

    daoManager.expects(once()).method("commitTransaction").withNoArguments();

    daoManager.expects(once()).method("endTransaction").withNoArguments();

    OrderService service =
        new OrderService((DaoManager) daoManager.proxy(), null, (OrderDao) orderDao.proxy(), null);
    service.getOrder(1);
  }
Пример #6
0
  @RequestMapping(value = "/waiter/bills/{billId}", method = RequestMethod.GET)
  public String showBillInWaiter(
      @PathVariable("billId") String billId, Model uiModel, Locale locale) {

    // warmup stuff
    Bill bill = warmupRestaurant(billId, uiModel);
    Restaurant resto = bill.getDiningTable().getRestaurant();

    List<Order> allPreparedOrders = orderService.findPreparedOrdersForRestaurant(resto);
    uiModel.addAttribute("allPreparedOrders", allPreparedOrders);

    List<Bill> allSubmittedBills = billService.findSubmittedBillsForRestaurant(resto);
    uiModel.addAttribute("allSubmittedBills", allSubmittedBills);

    uiModel.addAttribute(
        "message",
        new Message(
            "info",
            messageSource.getMessage("label_bill_amount", new Object[] {}, locale)
                + ": "
                + bill.getPriceAllOrders()
                + " "
                + messageSource.getMessage("label_currency", new Object[] {}, locale)));

    return "hartigehap/waiter";
  }
Пример #7
0
  /**
   * @param orderId
   * @param percent
   */
  public void payAllMoneyBackButService(int orderId, float percent) {
    if (percent > 100) {
      System.err.println("the return money percent > 100 in payMoneyBack");
      return;
    }
    Order order = orderService.getOrderById(orderId);
    if (order.getOrderStatus() == OrderStatus.CLOSE) {
      return;
    }

    FinanceUnit originToSeller =
        getFinanceUnitByRelatedIdAndDetailsTypeForSeller(orderId, FinanceType.Normal);
    FinanceUnit originToPlatform =
        getFinanceUnitByRelatedIdAndDetailsTypeForAdmin(orderId, FinanceType.Normal);

    FinanceUnit sellerToPlatform = new FinanceUnit(originToSeller, percent);
    sellerToPlatform.setReceiver(originToSeller.getSender());
    sellerToPlatform.setSender(originToSeller.getReceiver());
    sellerToPlatform.setFinanceDetailsType(FinanceType.Return);

    FinanceUnit platformToCustomer = new FinanceUnit(originToPlatform, percent);
    platformToCustomer.setReceiver(originToPlatform.getSender());
    platformToCustomer.setSender(originToPlatform.getReceiver());
    platformToCustomer.setFinanceDetailsType(FinanceType.Return);

    insertDirectly(platformToCustomer);
    insertDirectly(sellerToPlatform);
  }
Пример #8
0
 public Map<String, Object> payOrder(ShopReq shopReq) {
   Map<String, Object> map = shopMapper.getPayOrder(shopReq);
   String paytype = String.valueOf(map.get("paytype"));
   // 如未完成支付,调用第三方支付交易状态查询接口更新订单状态
   if ("0".equals(paytype)) {
     int _paytype = shopReq.getPayway();
     if (2 == _paytype) {
       String orderId = (String) map.get("order_number");
       Date created_at = (Date) map.get("created_at");
       String txnTime = sdf_simple.format(created_at);
       try {
         Map<String, String> queryResult = UnionpayService.query(orderId, txnTime);
         if (null != queryResult && "00".equals(queryResult.get("respCode"))) {
           OrderReq orderreq = new OrderReq();
           // 必须存在订单编号
           orderreq.setOrdernumber(orderId);
           orderreq.setType(_paytype);
           orderService.payFinish(orderreq);
           map = shopMapper.getPayOrder(shopReq);
         }
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
   }
   map.put("good", shopMapper.getPayOrderGood(shopReq));
   return map;
 }
Пример #9
0
  @RequestMapping(value = "/waiter/orders/{orderId}", method = RequestMethod.GET)
  public String showOrderInWaiter(
      @PathVariable("orderId") String orderId, Model uiModel, Locale locale) {

    // warmup stuff
    Order order = warmupRestaurantByOrder(orderId, uiModel);
    Restaurant resto = order.getBill().getDiningTable().getRestaurant();

    List<Order> allPreparedOrders = orderService.findPreparedOrdersForRestaurant(resto);
    uiModel.addAttribute("allPreparedOrders", allPreparedOrders);

    List<Bill> allSubmittedBills = billService.findSubmittedBillsForRestaurant(resto);
    uiModel.addAttribute("allSubmittedBills", allSubmittedBills);

    String orderContent = "";
    for (OrderItem orderItem : order.getOrderItems()) {
      orderContent +=
          orderItem.getMenuItem().getId() + " (" + orderItem.getQuantity() + "x)" + "; ";
    }

    uiModel.addAttribute(
        "message",
        new Message(
            "info",
            messageSource.getMessage("label_order_content", new Object[] {}, locale)
                + ": "
                + orderContent));

    return "hartigehap/waiter";
  }
Пример #10
0
  @RequestMapping(value = "/restaurants/{restaurantName}/kitchen", method = RequestMethod.GET)
  public String showKitchen(@PathVariable("restaurantName") String restaurantName, Model uiModel) {

    // warmup stuff
    Collection<Restaurant> restaurants = restaurantService.findAll();
    uiModel.addAttribute("restaurants", restaurants);
    Restaurant restaurant = restaurantService.fetchWarmedUp(restaurantName);
    uiModel.addAttribute("restaurant", restaurant);

    List<Order> allSubmittedOrders = orderService.findSubmittedOrdersForRestaurant(restaurant);
    uiModel.addAttribute("allSubmittedOrders", allSubmittedOrders);

    List<Order> allPlannedOrders = orderService.findPlannedOrdersForRestaurant(restaurant);
    uiModel.addAttribute("allPlannedOrders", allPlannedOrders);

    return "hartigehap/kitchen";
  }
Пример #11
0
 private Order warmupRestaurantByOrder(String orderId, Model uiModel) {
   Order order = orderService.findById(Long.valueOf(orderId));
   Collection<Restaurant> restaurants = restaurantService.findAll();
   uiModel.addAttribute("restaurants", restaurants);
   Restaurant restaurant =
       restaurantService.fetchWarmedUp(order.getBill().getDiningTable().getRestaurant().getId());
   uiModel.addAttribute("restaurant", restaurant);
   return order;
 }
  @Test
  public void updatesOrder() {
    Order order =
        new Order(
            OrderType.FOR_PICKUP, new Customer("Finn", "*****@*****.**", "+1(999)999-2187"));

    orderService.updateOrder(order);

    verify(mockOrderRepository).save(order);
  }
  @Test
  public void loadsAnOrderByItsId() {
    Order expectedOrder =
        new Order(
            OrderType.FOR_PICKUP, new Customer("Finn", "*****@*****.**", "+1(999)999-2187"));
    when(mockOrderRepository.findOne(1L)).thenReturn(expectedOrder);

    Order actualOrder = orderService.loadOrder(1L);
    assertThat(actualOrder, is(equalTo(expectedOrder)));
  }
  @Test
  public void loadsAPizzaByItsId() {
    Pizza expectedPizza =
        new Pizza(
            new Size("Large", BigDecimal.ZERO), new Crust("Hand Tossed"), new Sauce("Normal"));
    when(mockPizzaRepository.findOne(1L)).thenReturn(expectedPizza);

    Pizza actualPizza = orderService.loadPizza(1L);
    assertThat(actualPizza, is(equalTo(expectedPizza)));
  }
Пример #15
0
 private void orderHasBeenServed(Order order) {
   try {
     orderService.orderServed(order);
   } catch (StateException e) {
     log.error(
         "Internal error has occurred! Order "
             + Long.valueOf(order.getId())
             + "has not been changed to served state!",
         e);
   }
 }
  @Test
  public void updatesPizza() {
    Pizza pizza =
        new Pizza(new Size("Large", BigDecimal.ZERO), new Crust("Thin"), new Sauce("Normal"));
    Order order =
        new Order(
            OrderType.FOR_PICKUP, new Customer("Finn", "*****@*****.**", "+1(999)999-2187"));
    pizza.setOrder(order);

    orderService.updatePizza(pizza);

    verify(mockPizzaRepository).save(pizza);
  }
  @Test
  public void startsANewPickupOrder() {
    Customer customer = new Customer("Finn", "*****@*****.**", "+1(999)999-2187");
    Order expectedResult = new Order(OrderType.FOR_PICKUP, customer);

    when(mockCustomerRepository.findOne(1L)).thenReturn(customer);

    Order result = orderService.startNewPickupOrder(1L);

    assertThat(result, is(equalTo(expectedResult)));
    verify(mockCustomerRepository).findOne(1L);
    verify(mockOrderRepository).save(expectedResult);
  }
  @Test
  public void startsANewDeliveryOrder() {
    Customer customer = new Customer("Finn", "*****@*****.**", "+1(999)999-2187");
    customer.setAddress(new Address("2187 Jakku Ave.", "Jakku", "CA", "92187"));
    Order expectedResult = new Order(OrderType.FOR_DELIVERY, customer);

    when(mockCustomerRepository.findOne(1L)).thenReturn(customer);

    Order result = orderService.startNewDeliveryOrder(1L);

    assertThat(result, is(equalTo(expectedResult)));
    verify(mockCustomerRepository).findOne(1L);
    verify(mockOrderRepository).save(expectedResult);
  }
Пример #19
0
  /** 插入某订单的退货仓库费 */
  public void insertStoreMoney(int orderId) {
    Order order = orderService.getOrderById(orderId);
    FinanceUnit unit = new FinanceUnit(order);
    unit.setFinanceType(FinanceType.Store);
    float money = 0f;

    List<OrderItem> orderItems = order.getOrderItems();
    for (OrderItem orderItem : orderItems) {
      int productId = orderItem.getProductId();
      Product product = productService.getSimpleProductById(productId);
      String size = product.getSizeWithPackage();
      float moneyTmp = computeStoreFee(size);
      money += (moneyTmp * orderItem.getNum());
    }
    int coinage = order.getCoinage();
    money = Coinage.convertToAimCoinage(coinage, money, Coinage.Dollar);
    unit.setMoney(money);
    unit.setSender(UserType.SELLER + "-" + order.getSellerId());
    unit.setReceiver(UserType.ADMIN);
    insert(unit);
  }
Пример #20
0
  public void payMoneyBackCauseReturnNoExcuse(int orderId, float percent) { // 无理由退货
    if (percent > 100) {
      System.err.println("the return money percent > 100 in payMoneyBack");
      return;
    }
    Order order = orderService.getOrderById(orderId);
    if (order.getOrderStatus() == OrderStatus.CLOSE) {
      return;
    }

    FinanceUnit originToSeller =
        getFinanceUnitByRelatedIdAndDetailsTypeForSeller(orderId, FinanceType.Normal);
    FinanceUnit originToPlatform =
        getFinanceUnitByRelatedIdAndDetailsTypeForAdmin(orderId, FinanceType.Normal);
    FinanceUnit serviceMoney =
        getFinanceUnitByRelatedIdAndDetailsTypeForAdmin(orderId, FinanceType.ServiceNormal);

    FinanceUnit sellerToPlatform = new FinanceUnit(originToSeller); // 不退运费
    float tmp_money = order.getOriginPrice() * percent / 100.0f;
    sellerToPlatform.setMoney(tmp_money);
    sellerToPlatform.setReceiver(originToSeller.getSender());
    sellerToPlatform.setSender(originToSeller.getReceiver());
    sellerToPlatform.setFinanceDetailsType(FinanceType.Return);

    FinanceUnit platformToCustomer = new FinanceUnit(originToPlatform); // 不退运费
    float money = order.getOriginPriceRMB() * percent / 100.0f;
    platformToCustomer.setMoney(money);
    platformToCustomer.setReceiver(originToPlatform.getSender());
    platformToCustomer.setSender(originToPlatform.getReceiver());
    platformToCustomer.setFinanceDetailsType(FinanceType.Return);

    FinanceUnit serviceMoneyBack = new FinanceUnit(serviceMoney, 100); // 服务费全退
    serviceMoneyBack.setReceiver(serviceMoney.getSender());
    serviceMoneyBack.setSender(serviceMoney.getReceiver());
    serviceMoneyBack.setFinanceDetailsType(FinanceType.ServiceBack);

    insertDirectly(platformToCustomer);
    insertDirectly(sellerToPlatform);
    insertDirectly(serviceMoneyBack);
  }
Пример #21
0
  @Transactional(rollbackFor = Exception.class)
  public void computeForSeller(Date begin, Date end, int userId) {
    String user = contructID(userId, UserType.SELLER);
    FinanceRecord record = new FinanceRecord();
    // 收入
    List<FinanceUnit> unitsReceiveThisRun =
        financeUnitMapper.getFinanceByReceiverAndMonthByPage(user, begin, end, null);
    float receive = 0f; // 从平台收的钱
    /** 计算平台需要支付给卖家的钱 1. 正常买卖 */
    for (FinanceUnit unit : unitsReceiveThisRun) {

      if (unit.getStatus() != FinanceUnit.NOPAY) {
        continue;
      }

      int financeType = unit.getFinanceType();
      int financeDetailsType = unit.getFinanceDetailsType();
      float money = unit.getMoney();
      switch (financeType) {
        case FinanceType.Order: // 订单的钱
          if (financeDetailsType == FinanceType.Normal) { // 正常订单
            Order order = orderService.getOrderById(unit.getRelatedId());
            int orderStatus = order.getOrderStatus();
            if (orderStatus == OrderStatus.AUTOCLOSE
                || // 自动结束
                orderStatus == OrderStatus.CLOSE
                || // 管理员关闭
                orderStatus == OrderStatus.CANCELBYSELLER) {
              receive += money;
              record.addId(unit.getId());
            }
          }
          break;
        case FinanceType.Service:
          if (financeDetailsType == FinanceType.ServiceBack) {
            receive += money;
            record.addId(unit.getId());
          }
          break;
        case FinanceType.Other:
          receive += money;
          record.addId(unit.getId());
          break;
      }
    }
    // 支出
    List<FinanceUnit> unitsSendThisRun =
        financeUnitMapper.getFinanceBySenderAndMonthByPage(user, begin, end, null);
    float translationFee = 0f; // 付给平台的翻译钱
    float returnFee = 0f; // 返款给平台的钱
    float storeFee = 0f; // 使用仓库的钱
    float serviceFee = 0f; // 付给平台的服务钱
    float otherFee = 0f;
    /** 计算需要付给平台的钱 1. 翻译 2. 退款 */
    for (FinanceUnit unit : unitsSendThisRun) {
      if (unit.getStatus() != FinanceUnit.NOPAY) {
        continue;
      }
      int financeType = unit.getFinanceType();
      int financeDetailsType = unit.getFinanceDetailsType();
      float money = unit.getMoney();
      switch (financeType) {
        case FinanceType.Translation: // 翻译的钱
          translationFee += money;
          record.addId(unit.getId());
          break;
        case FinanceType.Order: // 给平台的返款,如退款
          if (financeDetailsType == FinanceType.Return) {
            returnFee += money;
            record.addId(unit.getId());
          }
          break;
        case FinanceType.Other:
          otherFee += money;
          record.addId(unit.getId());
          break;
        case FinanceType.Store:
          {
            Order order = orderService.getOrderById(unit.getRelatedId());
            int orderStatus = order.getOrderStatus();
            if (orderStatus == OrderStatus.AUTOCLOSE
                || // 自动结束
                orderStatus == OrderStatus.CLOSE // 管理员关闭
            ) {
              storeFee += money;
              record.addId(unit.getId());
            }
          }
          break;
        case FinanceType.Service:
          {
            Order order = orderService.getOrderById(unit.getRelatedId());
            int orderStatus = order.getOrderStatus();
            if (orderStatus == OrderStatus.AUTOCLOSE
                || // 自动结束
                orderStatus == OrderStatus.CLOSE
                || // 管理员关闭
                orderStatus == OrderStatus.CANCELBYSELLER) {
              serviceFee += money;
              record.addId(unit.getId());
            }
          }
          break;
      }
    }

    float totalGetFromAdmin = receive;
    float payAdmin = translationFee + returnFee + storeFee + serviceFee + otherFee;
    float total = totalGetFromAdmin - payAdmin;

    ShopSetting shopSetting = shopSettingMapper.getShopSettingBySellerId(userId);
    int coinage = 0;
    if (shopSetting != null) {
      coinage = shopSetting.getDefaultCoinage();
    }

    record.setOrderMoney(totalGetFromAdmin);
    record.setOtherMoney(otherFee);
    record.setReceiver(contructID(userId, UserType.SELLER));
    record.setServiceMoney(serviceFee);
    record.setStoreMoney(storeFee);
    record.setTotalGetFromAdmin(totalGetFromAdmin);
    record.setTotalPayAdmin(payAdmin);
    record.setTotal(total);
    record.setBeginDate(begin);
    record.setEndDate(end);
    record.setCoinage(coinage);

    financeRecordService.insert(record);
  }
Пример #22
0
 public Order buy(Order order) {
   Order persistedOrder = orderService.buy(order);
   Client client = persistedOrder.getClient();
   client.setCredit(client.getCredit() - persistedOrder.getTotalPrice());
   return order;
 }
  private void doTestJaxWsPortAccess(Object... features) throws Exception {
    GenericApplicationContext ac = new GenericApplicationContext();

    GenericBeanDefinition serviceDef = new GenericBeanDefinition();
    serviceDef.setBeanClass(OrderServiceImpl.class);
    ac.registerBeanDefinition("service", serviceDef);

    GenericBeanDefinition exporterDef = new GenericBeanDefinition();
    exporterDef.setBeanClass(SimpleJaxWsServiceExporter.class);
    exporterDef.getPropertyValues().add("baseAddress", "http://localhost:9999/");
    ac.registerBeanDefinition("exporter", exporterDef);

    GenericBeanDefinition clientDef = new GenericBeanDefinition();
    clientDef.setBeanClass(JaxWsPortProxyFactoryBean.class);
    clientDef.getPropertyValues().add("wsdlDocumentUrl", "http://localhost:9999/OrderService?wsdl");
    clientDef.getPropertyValues().add("namespaceUri", "http://jaxws.remoting.springframework.org/");
    clientDef.getPropertyValues().add("username", "juergen");
    clientDef.getPropertyValues().add("password", "hoeller");
    clientDef.getPropertyValues().add("serviceName", "OrderService");
    clientDef.getPropertyValues().add("serviceInterface", OrderService.class);
    clientDef.getPropertyValues().add("lookupServiceOnStartup", Boolean.FALSE);
    if (features != null) {
      clientDef.getPropertyValues().add("webServiceFeatures", features);
    }
    ac.registerBeanDefinition("client", clientDef);

    GenericBeanDefinition serviceFactoryDef = new GenericBeanDefinition();
    serviceFactoryDef.setBeanClass(LocalJaxWsServiceFactoryBean.class);
    serviceFactoryDef
        .getPropertyValues()
        .add("wsdlDocumentUrl", "http://localhost:9999/OrderService?wsdl");
    serviceFactoryDef
        .getPropertyValues()
        .add("namespaceUri", "http://jaxws.remoting.springframework.org/");
    serviceFactoryDef.getPropertyValues().add("serviceName", "OrderService");
    ac.registerBeanDefinition("orderService", serviceFactoryDef);

    ac.registerBeanDefinition("accessor", new RootBeanDefinition(ServiceAccessor.class));
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);

    try {
      ac.refresh();

      OrderService orderService = ac.getBean("client", OrderService.class);
      assertTrue(orderService instanceof BindingProvider);
      ((BindingProvider) orderService).getRequestContext();

      String order = orderService.getOrder(1000);
      assertEquals("order 1000", order);
      try {
        orderService.getOrder(0);
        fail("Should have thrown OrderNotFoundException");
      } catch (OrderNotFoundException ex) {
        // expected
      }

      ServiceAccessor serviceAccessor = ac.getBean("accessor", ServiceAccessor.class);
      order = serviceAccessor.orderService.getOrder(1000);
      assertEquals("order 1000", order);
      try {
        serviceAccessor.orderService.getOrder(0);
        fail("Should have thrown OrderNotFoundException");
      } catch (OrderNotFoundException ex) {
        // expected
      }
    } catch (BeanCreationException ex) {
      if ("exporter".equals(ex.getBeanName())
          && ex.getRootCause() instanceof ClassNotFoundException) {
        // ignore - probably running on JDK < 1.6 without the JAX-WS impl present
      } else {
        throw ex;
      }
    } finally {
      ac.close();
    }
  }
Пример #24
0
 public List<OrderItem> listOrderItemsByClient(long clientId) {
   Calendar calendar = new GregorianCalendar();
   calendar.set(Calendar.DAY_OF_MONTH, 1);
   return orderService.listOrderItemsByClient(clientId, calendar.getTime());
 }
Пример #25
0
  // this method serves kitchen subsystem and waiter subsystem requests,
  // which is quite confusing!
  // Reason is that the actual resource "orders/{orderId}" that is asked for,
  // is the same for kitchen subsystem and waiter subsystem,
  // meaning that the request URI is the same (according to REST).
  // You cannot have two methods with the same request URI mapping.
  // It is because the "event" request parameter (which is the distinguishing
  // parameter) is part of the HTTP body and can therefore not be
  // used for the request mapping.
  @RequestMapping(value = "/orders/{orderId}", method = RequestMethod.PUT)
  public String receiveEvent(
      @PathVariable("orderId") String orderId,
      @RequestParam String event,
      Model uiModel,
      Locale locale) {

    Order order = orderService.findById(Long.valueOf(orderId));
    Restaurant restaurant = warmupRestaurant(order, uiModel);

    switch (event) {
      case "planOrder":
        try {
          orderService.planOrder(order);
        } catch (StateException e) {
          logger.error(
              "Internal error has occurred! Order "
                  + Long.valueOf(orderId)
                  + "has not been changed to planned state!",
              e);

          // StateException triggers a rollback; consequently all Entities are invalidated by
          // Hibernate
          // So new warmup needed
          warmupRestaurant(order, uiModel);
          return "hartigehap/kitchen";
        }
        return "redirect:/restaurants/" + restaurant.getId() + "/kitchen";
        // break unreachable

      case "orderHasBeenPrepared":
        try {
          orderService.orderPrepared(order);
        } catch (StateException e) {
          logger.error(
              "Internal error has occurred! Order "
                  + Long.valueOf(orderId)
                  + "has not been changed to prepared state!",
              e);

          // StateException triggers a rollback; consequently all Entities are invalidated by
          // Hibernate
          // So new warmup needed
          warmupRestaurant(order, uiModel);
          return "hartigehap/kitchen";
        }
        return "redirect:/restaurants/" + restaurant.getId() + "/kitchen";
        // break unreachable

      case "orderHasBeenServed":
        try {
          orderService.orderServed(order);
        } catch (StateException e) {
          logger.error(
              "Internal error has occurred! Order "
                  + Long.valueOf(orderId)
                  + "has not been changed to served state!",
              e);

          // StateException triggers a rollback; consequently all Entities are invalidated by
          // Hibernate
          // So new warmup needed
          warmupRestaurant(order, uiModel);
          return "hartigehap/waiter";
        }
        return "redirect:/restaurants/" + restaurant.getId() + "/waiter";
        // break unreachable

      default:
        logger.error("Internal error: event " + event + " not recognized");
        return "redirect:/restaurants/" + restaurant.getId();
    }
  }
Пример #26
0
 @Test
 public void shouldRetrieveSavedOrders() {
   OrderService orderService = new OrderServiceImpl();
   assertThat(orderService.getOrders().size(), 1);
   // fail("Not yet implemented");
 }