private ProductNodeSubsetPane createBandSubsetPane() {
   Band[] bands = product.getBands();
   if (bands.length == 0) {
     return null;
   }
   return new ProductNodeSubsetPane(product.getBands(), true);
 }
  @RequestMapping(value = "/product/{prod}", method = RequestMethod.DELETE)
  @Transactional
  public ResponseEntity<ProductResult> doIt(
      @PathVariable("prod") String product, Authentication auth) {

    if (!ApplicationSecurity.isRoot(auth)) {
      return new ResponseEntity<ProductResult>(HttpStatus.FORBIDDEN);
    }

    Product reqProduct = new Product(product, null);
    List<String> errors = DomainValidator.checkForErrors(reqProduct);

    if (!errors.isEmpty()) {
      return new ResponseEntity<ProductResult>(
          new ProductResult(reqProduct, errors), HttpStatus.BAD_REQUEST);
    }

    if (!products.exists(reqProduct.getName())) {
      return new ResponseEntity<ProductResult>(
          new ProductResult(reqProduct, Product.NOT_FOUND), HttpStatus.NOT_FOUND);
    }

    products.delete(reqProduct.getName());
    components.deleteByKeyProduct(reqProduct.getName());
    properties.deleteByKeyProduct(reqProduct.getName());
    userProducts.deleteByKeyProduct(reqProduct.getName());
    return new ResponseEntity<ProductResult>(HttpStatus.OK);
  }
 private void stockRollBack(Sale sale) {
   for (SaleProductService saleProductService : sale.getProductsServices()) {
     if (saleProductService.getProduct() != null) {
       Product product = saleProductService.getProduct();
       product.setQuantity(product.getQuantity() + saleProductService.getQuantity());
       productDAO.merge(product);
     }
   }
 }
  // retrieve stored list of products from products file
  public Product[] getStoredProducts() {
    Product[] products = (Product[]) readFile(getProductFileName());

    // print names of products being returned
    for (Product product : products) {
      System.out.println("getStoredProducts: Returned " + product.getName());
    }

    return products;
  }
  // retrieve all reviews for a product from the database
  public String[][] getProductReviews(String name) {
    String[][] reviews = null;
    Product product = getProductEntry(name);

    if (product != null) {
      reviews = product.getRev(); // get product review
    }

    return reviews;
  }
 private ProductNodeSubsetPane createTiePointGridSubsetPane() {
   TiePointGrid[] tiePointGrids = product.getTiePointGrids();
   if (tiePointGrids.length == 0) {
     return null;
   }
   return new ProductNodeSubsetPane(
       product.getTiePointGrids(),
       new String[] {BeamConstants.LAT_DS_NAME, BeamConstants.LON_DS_NAME},
       true);
 }
  // retrieve product from database
  public Product getProductEntry(String name) {
    Product product = null;

    for (Product entry : getProducts()) {
      if (entry != null && entry.getName().equals(name)) {
        product = entry;
        break;
      }
    }

    return product;
  }
  // remove product review from database
  public boolean removeReviewEntry(String name, String review_id) {
    boolean success = true;

    Product product = getProductEntry(name); // retrieve product

    if (product != null) {
      product.deleteReview(review_id); // remove product review
    } else {
      success = false;
    }

    return success;
  }
  private static RasterDataNode[] getReferencedNodes(final RasterDataNode node) {
    final Product product = node.getProduct();
    if (product != null) {
      final List<String> expressions = new ArrayList<String>(10);
      if (node.getValidPixelExpression() != null) {
        expressions.add(node.getValidPixelExpression());
      }
      final ProductNodeGroup<Mask> overlayMaskGroup = node.getOverlayMaskGroup();
      if (overlayMaskGroup.getNodeCount() > 0) {
        final Mask[] overlayMasks =
            overlayMaskGroup.toArray(new Mask[overlayMaskGroup.getNodeCount()]);
        for (final Mask overlayMask : overlayMasks) {
          final String expression;
          if (overlayMask.getImageType() == Mask.BandMathsType.INSTANCE) {
            expression = Mask.BandMathsType.getExpression(overlayMask);
          } else if (overlayMask.getImageType() == Mask.RangeType.INSTANCE) {
            expression = Mask.RangeType.getExpression(overlayMask);
          } else {
            expression = null;
          }
          if (expression != null) {
            expressions.add(expression);
          }
        }
      }
      if (node instanceof VirtualBand) {
        final VirtualBand virtualBand = (VirtualBand) node;
        expressions.add(virtualBand.getExpression());
      }

      final ArrayList<Term> termList = new ArrayList<Term>(10);
      for (final String expression : expressions) {
        try {
          final Term term = product.parseExpression(expression);
          if (term != null) {
            termList.add(term);
          }
        } catch (ParseException e) {
          // @todo se handle parse exception
          Debug.trace(e);
        }
      }

      final Term[] terms = termList.toArray(new Term[termList.size()]);
      final RasterDataSymbol[] refRasterDataSymbols = BandArithmetic.getRefRasterDataSymbols(terms);
      return BandArithmetic.getRefRasters(refRasterDataSymbols);
    }
    return new RasterDataNode[0];
  }
  // remove product from database
  public boolean deleteProduct(String name) {
    boolean success = true;

    Iterator<Product> products = this.product_list.iterator();
    while (products.hasNext()) {
      Product entry = products.next();
      if (entry.getName().equals(name)) {
        success = this.product_list.remove(entry);
        removeStoredLocation(name); // remove product entry
        break;
      }
    }

    return success;
  }
  // add product review
  public boolean addProductReview(String name, String user, String score, String review) {
    boolean success = true;
    Product product = getProductEntry(name); // find product entry

    System.out.println("addProductReview: Retrived Entry " + product);

    if (product != null) {
      // add product review
      product.addReview(user, score, review);
    } else {
      success = false;
    }

    return success;
  }
  // add product to database using a product object
  public boolean addProductEntry(Product product, String server_name) {
    boolean success = true;

    this.product_list.add(product); // add product to database
    addStoredLocation(product.getName(), server_name); // update stored locations of product

    return success;
  }
 private void createProductListAndOffersMap() {
   productList = new ArrayList<>();
   offersMap = new HashMap<>();
   List<Long> productsId = optimizationParams.getProductsId();
   for (Long productId : productsId) {
     Product product = productRepository.findOne(productId);
     if (product != null) {
       List<Offer> offerList = offerRepository.findByIdProduct(productId);
       if (offerList.size() > 0) {
         productList.add(product);
         offersMap.put(product, offerList);
       } else {
         missedProductList.add(new MissedProduct(product.getName()));
       }
     } else {
       missedProductList.add(new MissedProduct("Id: " + productId));
     }
   }
 }
Beispiel #14
0
  public static void main(String[] args) throws NamingException, RemoteException {
    System.setProperty("java.security.policy", "client.policy");
    System.setSecurityManager(new SecurityManager());
    Context namingContext = new InitialContext();

    System.out.print("RMI registry bindings: ");
    NamingEnumeration<NameClassPair> e = namingContext.list("rmi://localhost/");
    while (e.hasMore()) System.out.println(e.next().getName());

    String url = "rmi://localhost/central_warehouse";
    Warehouse centralWarehouse = (Warehouse) namingContext.lookup(url);

    Scanner in = new Scanner(System.in);
    System.out.print("Enter keywords: ");
    List<String> keywords = Arrays.asList(in.nextLine().split("\\s+"));
    Product prod = centralWarehouse.getProduct(keywords);

    System.out.println(prod.getDescription() + ": " + prod.getPrice());
  }
 private static void showPage(String custId, String errMsg) {
   // Obviously this is inefficient -- the list of customer and products never changes,
   // so we could cache it.
   List<Customer> customers = Customer.find("order by name").fetch();
   List<Product> products = Product.find("order by name").fetch();
   Customer currentCustomer;
   if (custId == null || custId.trim().length() == 0) currentCustomer = customers.get(0);
   else currentCustomer = Customer.findById(new Long(custId));
   renderTemplate("Application/index.html", customers, currentCustomer, products, errMsg);
 }
  private boolean checkFlagDatasetIncluded() {
    final String[] nodeNames = productSubsetDef.getNodeNames();
    final List<String> flagDsNameList = new ArrayList<String>(10);
    boolean flagDsInSubset = false;
    for (int i = 0; i < product.getNumBands(); i++) {
      Band band = product.getBandAt(i);
      if (band.getFlagCoding() != null) {
        flagDsNameList.add(band.getName());
        if (StringUtils.contains(nodeNames, band.getName())) {
          flagDsInSubset = true;
        }
        break;
      }
    }

    final int numFlagDs = flagDsNameList.size();
    boolean ok = true;
    if (numFlagDs > 0 && !flagDsInSubset) {
      int status =
          JOptionPane.showConfirmDialog(
              getJDialog(),
              "No flag dataset selected.\n\n"
                  + "If you do not include a flag dataset in the subset,\n"
                  + "you will not be able to create bitmask overlays.\n\n"
                  + "Do you wish to include the available flag dataset(s)\n"
                  + "in the current subset?\n",
              "No Flag Dataset Selected",
              JOptionPane.YES_NO_CANCEL_OPTION);
      if (status == JOptionPane.YES_OPTION) {
        productSubsetDef.addNodeNames(flagDsNameList.toArray(new String[numFlagDs]));
        ok = true;
      } else if (status == JOptionPane.NO_OPTION) {
        /* OK, no flag datasets wanted */
        ok = true;
      } else if (status == JOptionPane.CANCEL_OPTION) {
        ok = false;
      }
    }

    return ok;
  }
 public static List<Variant> getPossibleVariants(
     Product product, Variant variant, String selectedAttribute) {
   List<Variant> matchingVariantList = new ArrayList<Variant>();
   List<Attribute> desiredAttributes = new ArrayList<Attribute>();
   for (Attribute attribute : variant.getAttributes()) {
     if (!selectedAttribute.equals(attribute.getName())
         && hasMoreAttributeValues(product, attribute.getName())) {
       desiredAttributes.add(attribute);
     }
   }
   VariantList variantList = product.getVariants().byAttributes(desiredAttributes);
   for (Attribute attr : product.getVariants().getAvailableAttributes(selectedAttribute)) {
     if (variantList.byAttributes(attr).size() < 1) {
       matchingVariantList.add((product.getVariants().byAttributes(attr).first()).orNull());
     } else {
       matchingVariantList.add((variantList.byAttributes(attr).first()).orNull());
     }
   }
   matchingVariantList.removeAll(Collections.singleton(null));
   return matchingVariantList;
 }
Beispiel #18
0
  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Product product = (Product) o;

    boolean setsAreEqual = true;

    for (Expr arg : arguments) {
      if (!product.getArguments().contains(arg)) {
        setsAreEqual = false;
      }
    }

    for (Expr arg : product.getArguments()) {
      if (!arguments.contains(arg)) {
        setsAreEqual = false;
      }
    }

    return !(arguments != null ? !setsAreEqual : product.arguments != null);
  }
 private static void processUpdate(String type, String id, String att, String value) {
   if (type == null || type.trim().length() == 0) return;
   if ("Order".equals(type)) {
     PurchaseOrder order = PurchaseOrder.findById(new Long(id));
     if ("paid".equals(att)) {
       Boolean oldValue = order.paid;
       if (oldValue == null) oldValue = Boolean.FALSE;
       order.paid = !oldValue;
       if (oldValue) setCurrentUseCaseName("Order unpaid");
       else setCurrentUseCaseName("Order paid");
     } else if ("customer".equals(att)) {
       if (value == null
           || value.startsWith(
               "- ")) // Do nothing if somehow the "- select a customer -" item was selected
       return;
       Customer customer = Customer.findById(new Long(value));
       order.customer = customer;
       Flash.current().success("The order has been reassigned to customer " + customer.name);
       setCurrentUseCaseName("Order reassigned");
     } else if ("notes".equals(att)) {
       order.notes = value;
       setCurrentUseCaseName("Order notes updated");
     }
     order.save();
   } else if ("Customer".equals(type)) {
     Customer customer = Customer.findById(new Long(id));
     if ("creditLimit".equals(att)) {
       BigDecimal val = NumberFormat.parseMoney(value);
       customer.creditLimit = val;
       setCurrentUseCaseName("Customer credit limit updated");
     }
     customer.save();
   } else if ("LineItem".equals(type)) {
     LineItem lineitem = LineItem.findById(new Long(id));
     if ("quantity".equals(att)) {
       Integer val = NumberFormat.parseNumber(value);
       lineitem.qtyOrdered = val;
       setCurrentUseCaseName("Line Item quantity updated");
     } else if ("unitPrice".equals(att)) {
       BigDecimal val = NumberFormat.parseMoney(value);
       lineitem.productPrice = val;
       setCurrentUseCaseName("Line Item unit price updated");
     } else if ("product".equals(att)) {
       Product product = Product.findById(new Long(value));
       lineitem.product = product;
       setCurrentUseCaseName("Line Item product changed");
     }
     lineitem.save();
   }
 }
 private void updateMemDisplay() {
   if (product != null) {
     long storageMem = product.getRawStorageSize(productSubsetDef);
     double factor = 1.0 / (1024 * 1024);
     double megas = MathUtils.round(factor * storageMem, 10);
     if (megas > memWarnLimit) {
       memLabel.setForeground(MEM_LABEL_WARN_COLOR);
     } else {
       memLabel.setForeground(MEM_LABEL_NORM_COLOR);
     }
     memLabel.setText(MEM_LABEL_TEXT + megas + "M");
   } else {
     memLabel.setText(" ");
   }
 }
  private boolean checkReferencedRastersIncluded() {
    final Set<String> notIncludedNames = new TreeSet<String>();
    final List<String> includedNodeNames = Arrays.asList(productSubsetDef.getNodeNames());
    for (final String nodeName : includedNodeNames) {
      final RasterDataNode rasterDataNode = product.getRasterDataNode(nodeName);
      if (rasterDataNode != null) {
        collectNotIncludedReferences(rasterDataNode, notIncludedNames);
      }
    }

    boolean ok = true;
    if (!notIncludedNames.isEmpty()) {
      StringBuilder nameListText = new StringBuilder();
      for (String notIncludedName : notIncludedNames) {
        nameListText.append("  '").append(notIncludedName).append("'\n");
      }

      final String pattern =
          "The following dataset(s) are referenced but not included\n"
              + "in your current subset definition:\n"
              + "{0}\n"
              + "If you do not include these dataset(s) into your selection,\n"
              + "you might get unexpected results while working with the\n"
              + "resulting product.\n\n"
              + "Do you wish to include the referenced dataset(s) into your\n"
              + "subset definition?\n"; /*I18N*/
      final MessageFormat format = new MessageFormat(pattern);
      int status =
          JOptionPane.showConfirmDialog(
              getJDialog(),
              format.format(new Object[] {nameListText.toString()}),
              "Incomplete Subset Definition", /*I18N*/
              JOptionPane.YES_NO_CANCEL_OPTION);
      if (status == JOptionPane.YES_OPTION) {
        final String[] nodenames = notIncludedNames.toArray(new String[notIncludedNames.size()]);
        productSubsetDef.addNodeNames(nodenames);
        ok = true;
      } else if (status == JOptionPane.NO_OPTION) {
        ok = true;
      } else if (status == JOptionPane.CANCEL_OPTION) {
        ok = false;
      }
    }
    return ok;
  }
 private ProductNodeSubsetPane createAnnotationSubsetPane() {
   final MetadataElement metadataRoot = product.getMetadataRoot();
   final MetadataElement[] metadataElements = metadataRoot.getElements();
   final String[] metaNodes;
   if (metadataElements.length == 0) {
     return null;
   }
   // metadata elements must be added to includeAlways list
   // to ensure that they are selected if isIgnoreMetada is set to false
   if (givenProductSubsetDef != null && !givenProductSubsetDef.isIgnoreMetadata()) {
     metaNodes = new String[metadataElements.length];
     for (int i = 0; i < metadataElements.length; i++) {
       final MetadataElement metadataElement = metadataElements[i];
       metaNodes[i] = metadataElement.getName();
     }
   } else {
     metaNodes = new String[0];
   }
   final String[] includeNodes = StringUtils.addToArray(metaNodes, Product.HISTORY_ROOT_NAME);
   return new ProductNodeSubsetPane(metadataElements, includeNodes, true);
 }
 private static void processInsert(
     String custId, String type, String id, String att, String value) {
   if (type == null || type.trim().length() == 0) return;
   if ("LineItem".equals(type)) {
     PurchaseOrder order = PurchaseOrder.findById(new Long(id));
     Product product = Product.findById(new Long(1));
     LineItem newItem = new LineItem();
     newItem.purchaseOrder = order;
     order.lineItems.add(newItem);
     newItem.product = product;
     product.lineItems.add(newItem);
     newItem.qtyOrdered = 1;
     setCurrentUseCaseName("New Line Item created");
     newItem.save();
   } else if ("Order".equals(type)) {
     Customer customer = Customer.findById(new Long(custId));
     PurchaseOrder newOrder = new PurchaseOrder();
     newOrder.customer = customer;
     newOrder.paid = Boolean.FALSE;
     newOrder.notes = "";
     setCurrentUseCaseName("New Order created");
     newOrder.save();
   }
 }
  public void testPropertyValidatorsAsBeanValidationAnnotation() throws Exception {
    Product p = new Product();
    p.setNumber(66);
    p.setDescription("MOTO");
    p.setFamilyNumber(1);
    p.setSubfamilyNumber(1);
    p.setWarehouseKey(new Warehouse());
    p.setUnitPrice(new BigDecimal("900"));

    XPersistence.getManager().persist(p);
    try {
      XPersistence.commit();
    } catch (RollbackException ex) {
      if (ex.getCause() instanceof ConstraintViolationException) {
        ConstraintViolationException cex = (ConstraintViolationException) ex.getCause();
        assertEquals("1 constraint violation expected", 1, cex.getConstraintViolations().size());
        ConstraintViolation v = cex.getConstraintViolations().iterator().next();
        assertEquals("Property", "description", v.getPropertyPath().toString());
        assertEquals("Message text", "", v.getMessage());
        return;
      }
    }
    fail("A constraint violation exception should be thrown");
  }
  public void testEntityValidatorsAsHibernateAnnotation() throws Exception {
    Product p = new Product();
    p.setNumber(66);
    p.setDescription("BUENO, BONITO, BARATO"); // It's cheap ('BARATO') thus...
    p.setFamilyNumber(1);
    p.setSubfamilyNumber(1);
    p.setWarehouseKey(new Warehouse());
    p.setUnitPrice(new BigDecimal("900")); // ... it cannot cost 900 (max 100)

    XPersistence.getManager().persist(p);
    try {
      XPersistence.commit();
    } catch (RollbackException ex) {
      if (ex.getCause() instanceof ConstraintViolationException) {
        ConstraintViolationException cex = (ConstraintViolationException) ex.getCause();
        assertEquals("1 constraint violation expected", 1, cex.getConstraintViolations().size());
        ConstraintViolation v = cex.getConstraintViolations().iterator().next();
        assertEquals("Bean", "Product", v.getRootBean().getClass().getSimpleName());
        assertEquals("Message text", "", v.getMessage());
        return;
      }
    }
    fail("A constraint violation exception should be thrown");
  }
Beispiel #26
0
  public List<UploadLog> uploadInvoice(String fileName) { // upload products to database

    String line;
    List<String> dataHolder =
        pdfExtractorUtility.extractOrder(fileName); // extract data from given fileName
    int lineNum = 1;
    List<VendorInventory> inventory = new ArrayList<VendorInventory>();
    List<VendorInventory> insertionErrors = new ArrayList<VendorInventory>();
    List<UploadLog> errorLogs = new ArrayList<UploadLog>();
    VendorOrder vendorOrder;
    Product product;
    String[] splitLine;
    String vendorId;
    int quantity;
    double weight = 0;
    double price;
    double credit = 0;
    double deliveryFee = 0;
    double totalPrice = 0;
    Date orderDate = null;
    Date deliveryDate = null;
    Date currentDate = null;
    String vendorOrderId = null;
    String weightString;
    SimpleDateFormat dateFormat;
    boolean found = false;
    boolean firstDate = true;
    for (int i = 0; i < dataHolder.size(); i++) { // for each row in sheet
      line = dataHolder.get(i).trim(); // get current row
      log.debug(line);
      splitLine = line.split("^" + lineNum + "\\s{4}");
      if (splitLine.length > 1) { // this is an item line
        lineNum++;
        if (line.contains(" 8338 ")) { // ignore line for Oma's info packet
          continue;
        }

        if (line.contains(" SRVCRG ")) { // add this charge to order charges table
          splitLine = line.split("^.+?(?=\\d+\\.\\d{2}$)");
          deliveryFee = Double.parseDouble(splitLine[1]);
          continue;
        }
        line = splitLine[1]; // set line equal to everything after line number
        splitLine = line.split("(?<=\\d{2,4}\\w{0,2})\\s+", 2);
        vendorId = splitLine[0]; // set vendor id to first piece of split
        line = splitLine[1]; // set line equal to rest of split
        splitLine = line.split("\\d+\\.\\d{2}\\s+", 2);
        line = splitLine[1]; // remove quantity ordered
        splitLine = line.split("(?<=\\d+\\.\\d{2})\\s", 2);
        quantity =
            (int) Double.parseDouble(splitLine[0]); // set quantity received to first piece of split
        line = splitLine[1]; // set line equal to rest of split
        splitLine = line.split("^.+?(?=\\d+\\.?\\d*\\s+-?\\d+\\.\\d{2})", 2);
        line = splitLine[1]; // remove bill by label and product name along with trailing spaces
        splitLine = line.split("\\s+(?=-?\\d+\\.\\d{2}\\s+-?\\d+\\.\\d{2}$)", 2);
        weightString = splitLine[0]; // number representing either quantity or exact weight
        if (weightString.contains(".")) { // this is an exact weight
          weight = Double.parseDouble(weightString);
        } else {
          weight = 0;
        }
        line = splitLine[1];
        splitLine = line.split("(?<=\\d+\\.\\d{2})\\s+", 2);
        price = Double.parseDouble(splitLine[0]); // set price each
        if (price < 0) { // this is a credit, add to credits
          if (weight != 0) {
            credit =
                credit
                    + (new BigDecimal(price * weight)
                        .setScale(2, BigDecimal.ROUND_HALF_UP)
                        .doubleValue());
          } else {
            credit =
                credit
                    + (new BigDecimal(price * quantity)
                        .setScale(2, BigDecimal.ROUND_HALF_UP)
                        .doubleValue());
          }
          continue;
        } else { // this is a billed item, add to total bill
          if (weight != 0) {
            totalPrice =
                totalPrice
                    + (new BigDecimal(price * weight)
                        .setScale(2, BigDecimal.ROUND_HALF_UP)
                        .doubleValue());
            log.debug(
                "item price so far: "
                    + (new BigDecimal(price * weight).setScale(2, BigDecimal.ROUND_HALF_UP)));
          } else {
            totalPrice =
                totalPrice
                    + (new BigDecimal(price * quantity)
                        .setScale(2, BigDecimal.ROUND_HALF_UP)
                        .doubleValue());
            log.debug(
                "item price so far: "
                    + (new BigDecimal(price * quantity).setScale(2, BigDecimal.ROUND_HALF_UP)));
          }
        }
        log.debug("total price so far: " + totalPrice);
        product = new Product();
        product.setVendorId(vendorId);
        inventory.add(new VendorInventory(product, quantity, weight, price, false));
      } else {
        if (line.contains("JPEELE")
            && !found) { // this is line than contains order and delivery dates and order id
          dateFormat = new SimpleDateFormat("M/d/yy");
          found = true;
          splitLine = line.trim().split("\\s+");
          for (String split : splitLine) {
            log.debug(split);
            if (split.contains("/")) {
              try {
                currentDate = dateFormat.parse(split);
              } catch (ParseException pe) {
                log.error("Unable to parse date", pe);
              }
              if (firstDate) {
                firstDate = false;
                orderDate = currentDate;
              } else {
                deliveryDate = currentDate;
              }
            } else if (!firstDate) { // this is order id
              vendorOrderId = split;
            }
          }
          log.debug(
              "Order Date= "
                  + orderDate
                  + "Delivery Date= "
                  + deliveryDate
                  + "Vendor Order Id= "
                  + vendorOrderId);
        }
      }
    }
    String logDescription;
    List<String> headers;
    List<List<String>> logData;
    String orderId;
    log.debug("credit: " + credit);
    log.debug("total price: " + (totalPrice + deliveryFee + credit));
    vendorOrder =
        new VendorOrder(
            credit * -1,
            deliveryFee,
            totalPrice + deliveryFee + credit,
            ProductGroup.OMAS,
            "Received",
            orderDate,
            deliveryDate,
            vendorOrderId);
    if ((vendorOrder = orderUtility.updateVendorOrder(vendorOrder)) == null) {
      logDescription = "Unable to upload vendor order information.";
      headers = Arrays.asList("Credit", "Delivery Fee", "Total Cost", "Status");
      logData = new ArrayList<List<String>>();
      logData.add(
          Arrays.asList(
              String.format("$%.2f", credit),
              String.format("$%.2f", deliveryFee),
              String.format("$%.2f", totalPrice),
              "Received"));
      errorLogs.add(new UploadLog(logDescription, headers, logData));
    } else if (vendorOrder.getId() == null) {
      logDescription = "You are attempting to upload a duplicate order.";
      headers = Arrays.asList("Vendor Order Id");
      logData = new ArrayList<List<String>>();
      logData.add(Arrays.asList(vendorOrderId));
      errorLogs.add(new UploadLog(logDescription, headers, logData));
    } else {
      orderId = vendorOrder.getId();
      for (VendorInventory vendorInventory : inventory) {
        if (productUtility.updateVendorInventoryItems(
                Arrays.asList(vendorInventory),
                Integer.parseInt(orderId),
                null,
                VendorOrder.STATUS.get("Received"))
            == null) {
          insertionErrors.add(vendorInventory);
        }
      }
      if (insertionErrors.size() > 0) {
        logDescription = "Vendor order items that were not uploaded properly.";
        headers = Arrays.asList("Vendor Id", "Quantity", "Weight", "Cost");
        logData = new ArrayList<List<String>>();
        for (VendorInventory vendorInventory : insertionErrors) {
          logData.add(
              Arrays.asList(
                  vendorInventory.getProduct().getVendorId(),
                  Double.toString(vendorInventory.getQuantity()),
                  vendorInventory.getCostFormatted()));
        }
        errorLogs.add(new UploadLog(logDescription, headers, logData));
      }
      log.debug(credit + ", " + deliveryFee);
    }
    return errorLogs; // this should be report of orphaned products/inventory
  }
Beispiel #27
0
  /** upload product data to database from String containing file and return report */
  public List<UploadLog> uploadProducts(String fileName) { // upload products to database
    List<List<String>> dataHolder =
        excelExtractorUtility.extractProducts(fileName); // extract products
    String name = null; // name of current item
    String previousName = null; // name of previous item
    int size; // number of cells in row
    int index; // index of start of white space and extra text
    String msrp = null; // value of msrp for row	
    String id = null; // id for item
    String billBy = null; // unit to bill by
    String orderBy = null; // unit to order by
    String estimatedWeight = null; // estimated weight of item
    String[] estimatedRange = null; // holds the two numbers for estimatedWeight if it's a range
    List<Product> errorProducts = new ArrayList<Product>(); // products that didn't upload
    List<Product> products = new ArrayList<Product>(); // list of products to upload
    Product product = null;
    String defaultWeight = "0";
    String defaultCaseWeight = "0";
    String[] estimatedQuantityWeight;
    String[] nameSplit;
    String remainingName;
    String[] remainingNameSplit;
    String[] fraction;
    boolean mix = false;
    String mixString = null;
    for (int i = 0; i < dataHolder.size(); i++) { // for each row in sheet
      List<String> row = dataHolder.get(i); // get current row
      size = row.size(); // number of cells
      name = row.get(0); // get name from 1st cell
      if (name != null) {
        if (name.contains("Freeze Dried Treats")) {
          defaultWeight = ".25";
          defaultCaseWeight = "3.0";
        }
        if (name.contains("TEMPTINGS")) {
          defaultWeight = ".125";
          defaultCaseWeight = "0";
        }
        if (name.contains("Dr. Harveys Treats")) {
          defaultWeight = "0";
          defaultCaseWeight = "0";
        }
        if (name.contains("MIXES")) {
          mix = true;
        }
        if (name.contains("CHICKEN")) {
          mix = false;
        }
      }
      if (size > 10) { // if row has at least 10 cells
        msrp = row.get(7); // get msrp column
        if (msrp != null
            && (AdminUtilities.isNumeric(msrp.trim())
                || msrp.trim()
                    .contains(
                        "mkt"))) { // check to see if this is a row with an item in it, otherwise
                                   // skip it
          name =
              name.replaceAll(
                  new Character((char) 8237).toString(), ""); // remove weird special character
          name = name.replaceAll(" +", " ");
          index = name.toUpperCase().indexOf("(GREAT");
          if (index >= 0) {
            name = name.substring(0, index);
          }
          index = name.toUpperCase().indexOf("SPECIAL ORDER");
          if (index >= 0) {
            name = name.substring(0, index);
          }
          index = name.toUpperCase().indexOf("ORDER BY THE TUBE");
          if (index >= 0) {
            name = name.substring(0, index);
          }
          index = name.toUpperCase().indexOf("CALL FOR AVAILABILITY");
          if (index >= 0) {
            name = name.substring(0, index);
          }
          if (name.length()
              == 0) { // if name isn't there, this is a duplicate item of the previous row in case
                      // quantity
            name = previousName;
          }
          billBy = AdminUtilities.formatUnit(row.get(6)); // replace unit abbr if necessary
          orderBy =
              AdminUtilities.formatUnit(row.get(5)); // replace unit abbr if necessary       		
          // get estimated weight if applicable
          estimatedWeight = "0";
          if (name.toUpperCase().contains("LB")) {
            if (name.matches("(?i)^.*\\s+\\d+\\s+\\d+/\\d+\\s*lb.*$")) {
              nameSplit = name.split("(?i)\\s*lbs?\\.?"); // remove lb and any leading spaces
              // nameSplit = name.split("\\s*lb(?!.*\\d+\\s*/\\s*\\d)"); //remove lb and any leading
              // spaces
              name = nameSplit[0];
              estimatedWeight =
                  name; // temporarily set estimated weight to name, we will trim off name shortly
              name =
                  name.split("(?i)\\s+\\d+\\s+\\d+/\\d+.*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" +", " "); // remove white space from estimated weight
              estimatedWeight = estimatedWeight.trim();
              estimatedRange = estimatedWeight.split(" ");
              fraction = estimatedRange[1].split("/");
              estimatedWeight =
                  Double.toString(
                      Double.parseDouble(estimatedRange[0])
                          + Double.parseDouble(fraction[0]) / Double.parseDouble(fraction[1]));
            } else if (name.matches("(?i)^.*\\d+\\.?\\d*\\s*/\\s*\\d+\\.?\\d*\\s*lb.*$")) {
              nameSplit =
                  name.split(
                      "(?i)\\s*lbs?\\.?(?!.*\\d+\\s*/\\s*\\d\\.?\\d*)"); // remove lb and any
                                                                         // leading spaces
              // nameSplit = name.split("\\s*lb(?!.*\\d+\\s*/\\s*\\d)"); //remove lb and any leading
              // spaces
              name = nameSplit[0];
              estimatedWeight =
                  name; // temporarily set estimated weight to name, we will trim off name shortly
              name =
                  name.split("(?i)\\s+\\d+\\.?\\d*\\s*/\\s*\\d*\\.?\\d*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" ", ""); // remove white space from estimated weight
              estimatedRange = estimatedWeight.split("/"); // split the two numbers into an array
              estimatedWeight =
                  Double.toString(
                      Double.parseDouble(estimatedRange[0])
                          * Double.parseDouble(
                              estimatedRange[1])); // multiply the two numbers    					
            } else {
              nameSplit = name.split("(?i)\\s*lbs?\\.?"); // remove lb and any leading spaces
              // nameSplit = name.split("\\s*lb"); //remove lb and any leading spaces
              name = nameSplit[0];
              estimatedWeight =
                  name; // temporarily set estimated weight to name, we will trim off name shortly
              name =
                  name.split("(?i)\\s+\\d+\\.?\\d*\\s*-?\\s*\\d*\\.?\\d*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" ", ""); // remove white space from estimated weight
              if (estimatedWeight.contains("-")) { // this is a range, average the two numbers
                estimatedRange = estimatedWeight.split("-"); // split the two numbers into an array
                estimatedWeight =
                    Double.toString(
                        ((Double.parseDouble(estimatedRange[0])
                                + Double.parseDouble(estimatedRange[1])))
                            / 2); // average the two numbers
              }
              if (nameSplit.length > 1) {
                remainingName = nameSplit[1];
              } else {
                remainingName = "";
              }
              if (mix) {
                remainingNameSplit = remainingName.trim().split(" ");
                if (remainingNameSplit.length > 1
                    && remainingNameSplit[0].equals(remainingNameSplit[1])) { // 1lb mix, ignore
                  mixString = "";
                } else if (remainingName.contains("(")
                    && remainingName.contains("-")) { // 2lb mix with list of vegetables
                  mixString = remainingName.trim();
                  product.setProductName(
                      product.getProductName()
                          + "- "
                          + AdminUtilities.toProperCase(
                              mixString)); // set name of 1lb package appropriately
                  name =
                      name + "- "
                          + mixString; // set name of 2lb package
                } else if (remainingName.contains("BOX")) { // 10 lb box
                  name =
                      name
                          + " "
                          + remainingName
                          + " "
                          + mixString.substring(mixString.indexOf(" "));
                } else { // 5 or 10 pound mix
                  name = name + "- " + mixString;
                }
              } else {
                name = name + " " + remainingName.trim();
              }
            }
          } else if (name.contains("#")) {
            nameSplit = name.split("\\s*#"); // remove lb and any leading spaces
            // nameSplit = name.split("\\s*lb(?!.*\\d+\\s*/\\s*\\d)"); //remove lb and any leading
            // spaces
            name = nameSplit[0];
            estimatedWeight =
                name; // temporarily set estimated weight to name, we will trim off name shortly
            if (name.contains("/")) {
              name =
                  name.split("\\s+\\d+\\.?\\d*\\s*/\\s*\\d*\\.?\\d*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" ", ""); // remove white space from estimated weight
              estimatedRange = estimatedWeight.split("/"); // split the two numbers into an array
              estimatedWeight =
                  Integer.toString(
                      Integer.parseInt(estimatedRange[0])
                          * Integer.parseInt(estimatedRange[1])); // multiply the two numbers
            } else {
              name =
                  name.split("\\s+\\d+\\.?\\d*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" ", ""); // remove white space from estimated weight
            }
            if (nameSplit.length > 1) {
              name = name + " " + nameSplit[1].trim();
            }
          } else if (name.toUpperCase().contains(" OZ")) {
            nameSplit = name.split("(?i)\\s*oz\\.?"); // remove lb and any leading spaces
            // nameSplit = name.split("\\s*lb(?!.*\\d+\\s*/\\s*\\d)"); //remove lb and any leading
            // spaces
            name = nameSplit[0];
            estimatedWeight =
                name; // temporarily set estimated weight to name, we will trim off name shortly
            if (name.matches("^.*\\s+\\d+\\.?\\d*\\s*-\\s*\\d*\\.?\\d*$")) {
              name =
                  name.split("\\s+\\d+\\.?\\d*\\s*-\\s*\\d*\\.?\\d*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" ", ""); // remove white space from estimated weight
              estimatedRange = estimatedWeight.split("-"); // split the two numbers into an array
              estimatedWeight =
                  Double.toString(
                      ((double)
                              (Integer.parseInt(estimatedRange[0])
                                  + Integer.parseInt(estimatedRange[1])))
                          / 32); // average two numbers
            } else {
              name =
                  name.split("\\s+\\d+\\.?\\d*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" ", ""); // remove white space from estimated weight
              estimatedWeight = Double.toString(Double.parseDouble(estimatedWeight) / 16);
            }
            if (nameSplit.length > 1) {
              name = name + " " + nameSplit[1].trim();
            }
          } else if (name.contains("mg. ")) {
            nameSplit = name.split("\\s+(?=\\d+-\\d+\\s+mg)"); // remove everything before weight
            estimatedWeight = nameSplit[1];
            name = nameSplit[0];
            estimatedWeight =
                estimatedWeight.split("\\s+mg")[0]; // remove everything after weight       				
            estimatedQuantityWeight = estimatedWeight.split("-");
            estimatedWeight =
                Double.toString(
                    ((double)
                            (Integer.parseInt(estimatedQuantityWeight[0])
                                * Integer.parseInt(estimatedQuantityWeight[1])
                                / 4480))
                        / 100);
          } else if (name.contains("gm. ")) {
            nameSplit = name.split("\\s+(?=\\d+\\s+gm)");
            estimatedWeight = nameSplit[1]; // remove everything before weight
            name = nameSplit[0];
            estimatedWeight =
                estimatedWeight.split("\\s+gm")[0]; // remove everything after weight     				
          } else if (!defaultWeight.equals("0")
              && billBy != "Case"
              && estimatedWeight.equals(
                  "0")) { // this is a set weight for items sold individually for the whole group of
                          // products
            estimatedWeight = defaultWeight;
          } else if (!defaultCaseWeight.equals("0")
              && billBy == "Case"
              && estimatedWeight.equals(
                  "0")) { // this is a set weight for items sold by the case for the whole group of
                          // products
            estimatedWeight = defaultCaseWeight;
          }
          id = row.get(4);
          try {
            id =
                Integer.toString(
                    (int)
                        Double.parseDouble(
                            id)); // if this has an extraneous .0 because of import from excel
                                  // sheet, remove
          } catch (NumberFormatException nfe) {
          }
          double msrpDouble = 0;
          if (!msrp.contains("mkt")) {
            msrpDouble = Double.parseDouble(msrp);
          }
          try {
            product =
                new Product(
                    AdminUtilities.toProperCase(name),
                    msrpDouble,
                    orderBy,
                    billBy,
                    Double.parseDouble(estimatedWeight),
                    "",
                    id);
          } catch (Exception e) {
            log.error("Unable to add product " + name, e);
          }
          products.add(product);
          previousName = name;
        }
      }
    }
    for (Product uploadProduct : products) {
      if (productUtility.updateProduct(uploadProduct) == null) { // update product in database
        errorProducts.add(uploadProduct);
      }
    }
    List<UploadLog> uploadLogs =
        productUtility
            .generateProductErrorReport(); // report of items that don't have uploaded info from
                                           // Excel file
    if (errorProducts.size() != 0) {
      String logDescription = "Products that failed in upload to Database";
      List<String> headings =
          Arrays.asList(
              "Vendor Id", "Name", "price", "Order By", "Bill By", "Estimated Weight", "Vendor");
      List<List<String>> logRows = new ArrayList<List<String>>();
      for (Product errorProduct : errorProducts) {

        logRows.add(
            Arrays.asList(
                errorProduct.getVendorId(),
                errorProduct.getProductName(),
                Double.toString(errorProduct.getPrice()),
                errorProduct.getOrderBy(),
                errorProduct.getBillBy(),
                Double.toString(errorProduct.getEstimatedWeight()),
                ProductGroup.OMAS)); // add information about each product with error to log
      }
      uploadLogs.add(new UploadLog(logDescription, headings, logRows));
    }
    return uploadLogs;
  }
 private boolean canUseGeoCoordinates(Product product) {
   final GeoCoding geoCoding = product.getGeoCoding();
   return geoCoding != null && geoCoding.canGetPixelPos() && geoCoding.canGetGeoPos();
 }
 public static Call getProductUrl(Product product, Variant variant, Category category) {
   return routes.Products.select(product.getSlug(), String.valueOf(variant.getId()));
 }
  public void addProductsServicesToSale(
      boolean isDraft, Sale saleFromDB, List<SaleProductService> productsServices)
      throws IabakoStockException {

    Enterprise enterprise = getEnterpriseFromSessionUser();
    String productsServicesAsString = "";

    Map<Product, Double> stockReductionMap = new HashMap<Product, Double>();

    // 1. Create productService as String (for table results)
    saleFromDB.setProductsServicesAsString(null);

    saleDAO.cleanProductService(saleFromDB);

    for (SaleProductService productService : productsServices) {

      String quantityString =
          productService.getQuantity() == 0d
                  || productService.getQuantity()
                          / new Double(productService.getQuantity()).intValue()
                      == 1
              ? new Double(productService.getQuantity()).intValue() + ""
              : ServerTools.formatAmount(
                  saleFromDB.getEnterprise().getLanguage(), productService.getQuantity());

      if (productService.getProduct() != null) {

        if (!productService.getProduct().isStockDisabled()) {
          Double quantity = stockReductionMap.get(productService.getProduct());
          stockReductionMap.put(
              productService.getProduct(),
              quantity == null
                  ? productService.getQuantity()
                  : quantity + productService.getQuantity());
        }

        quantityString +=
            productService.getProduct().getPriceUnit() == PriceUnit.unit
                ? ""
                : messages.getLabel(productService.getProduct().getPriceUnit().getLabelKey());

        productsServicesAsString +=
            productService.getProduct().getName() + " (" + quantityString + ")\n";
      } else {
        productsServicesAsString +=
            productService.getService().getName() + " (" + quantityString + ")\n";
      }
    }
    if (!GenericTools.isEmpty(productsServicesAsString)) {
      productsServicesAsString =
          productsServicesAsString.substring(0, productsServicesAsString.lastIndexOf("\n"));
      productsServicesAsString =
          productsServicesAsString.length() > 1000
              ? productsServicesAsString.substring(0, 1000)
              : productsServicesAsString;
      saleFromDB.setProductsServicesAsString(productsServicesAsString);
      saleFromDB.setProductsServices(productsServices);
    }

    // 2. Reset Product/Service Enterprise (and do not change Enterprise!)
    boolean enterpriseHasChildren = enterprise.getAllRelatedEnterprises().size() > 1;
    Product prod;
    Service service;
    for (SaleProductService saleProductService : saleFromDB.getProductsServices()) {
      if ((prod = saleProductService.getProduct()) != null
          && saleProductService.getProduct().getEnterprise() == null) {
        saleProductService
            .getProduct()
            .setEnterprise(
                enterpriseHasChildren
                    ? productDAO.findById(prod.getId()).getEnterprise()
                    : enterprise);

      } else if ((service = saleProductService.getService()) != null
          && saleProductService.getService().getEnterprise() == null) {
        saleProductService
            .getService()
            .setEnterprise(
                enterpriseHasChildren
                    ? serviceDAO.findById(service.getId()).getEnterprise()
                    : enterprise);
      }
    }

    // 3. Stock reduction
    if (isDraft) {
      return;
    }

    if (stockReductionMap.keySet().isEmpty()) {
      return;
    }

    ProductStockModification productStockModification =
        productDAO.persistProductStockModification(false);

    String errorMessage = "";
    for (Product product : stockReductionMap.keySet()) {
      if (product.getQuantity() < stockReductionMap.get(product)) {
        String unit = messages.getLabel(product.getPriceUnit().getLabelKey());
        unit = GenericTools.isEmpty(unit) ? " " + messages.getLabel("stock_unit") : unit;

        String stringQuantity =
            product.getQuantity() == 0d
                    || product.getQuantity() / new Double(product.getQuantity()).intValue() == 1
                ? new Double(product.getQuantity()).intValue() + ""
                : ServerTools.formatAmount(
                    saleFromDB.getEnterprise().getLanguage(), product.getQuantity());

        errorMessage +=
            "\n"
                + messages.getLabel(
                    "stock_sale_not_enough_text", product.getName(), stringQuantity, unit);
      }

      product.setQuantity(
          ServerTools.round(product.getQuantity() - stockReductionMap.get(product)));
      productDAO.merge(product);

      productDAO.trackStockModification(
          product,
          product.getQuantity(),
          stockReductionMap.get(product) * -1,
          productStockModification);
    }
    if (!GenericTools.isEmpty(errorMessage)) {
      errorMessage += messages.getLabel("stock_sale_not_enough_resolve_text");
      throw new IabakoStockException("stock_sale_not_enough_title", errorMessage, true);
    }

    // 4. Tag management
    for (SaleProductService saleProductService : saleFromDB.getProductsServices()) {
      if ((prod = saleProductService.getProduct()) != null
          && saleProductService.getProduct().getBusinessTag() != null) {
        BusinessTagSale businessTagSale = new BusinessTagSale();
        businessTagSale.setBusinessTag(prod.getBusinessTag());
        businessTagSale.setProduct(prod);
        businessTagSale.setSale(saleFromDB);
        saleFromDB.getBusinessTagList().add(businessTagSale);

      } else if ((service = saleProductService.getService()) != null
          && saleProductService.getService().getBusinessTag() != null) {
        BusinessTagSale businessTagSale = new BusinessTagSale();
        businessTagSale.setBusinessTag(service.getBusinessTag());
        businessTagSale.setService(service);
        businessTagSale.setSale(saleFromDB);
        saleFromDB.getBusinessTagList().add(businessTagSale);
      }
    }
  }