public boolean price(CommandSender sender, String item, int amt) { // retrieve the commodity in question Commodities commodity = plugin.getDatabase().find(Commodities.class).where().ieq("name", item).findUnique(); if (commodity == null) { sender.sendMessage(ChatColor.RED + "Invalit commodity name."); return false; } // get the buy and sell price of the item Invoice sellPrice = generateInvoice(0, commodity, amt); Invoice buyPrice = generateInvoice(1, commodity, amt); // send output sender.sendMessage( ChatColor.GRAY + item + ChatColor.GREEN + " If sold: " + ChatColor.WHITE + BigDecimal.valueOf(sellPrice.getTotal()).setScale(2, RoundingMode.HALF_UP)); sender.sendMessage( ChatColor.GRAY + item + ChatColor.GREEN + " If bought: " + ChatColor.WHITE + BigDecimal.valueOf(buyPrice.getTotal()).setScale(2, RoundingMode.HALF_UP)); return true; }
@Test public void testTableIdentifiers() { Session session = getNewSession("jboss"); session.beginTransaction(); Invoice orderJboss = new Invoice(); session.save(orderJboss); Assert.assertEquals(Long.valueOf(1), orderJboss.getId()); session.getTransaction().commit(); session.close(); session = getNewSession("acme"); session.beginTransaction(); Invoice orderAcme = new Invoice(); session.save(orderAcme); Assert.assertEquals(Long.valueOf(1), orderAcme.getId()); session.getTransaction().commit(); session.close(); session = getNewSession("jboss"); session.beginTransaction(); session.delete(orderJboss); session.getTransaction().commit(); session.close(); session = getNewSession("acme"); session.beginTransaction(); session.delete(orderAcme); session.getTransaction().commit(); session.close(); sessionFactory.getStatisticsImplementor().clear(); }
private void consolidateInvoices() { for (Invoice i : invoices) { for (LineItem l : i.getInvoice()) { String code = l.getProduct().getCode(); int quant = l.getQuantity(); double total = l.getTotal(); double price = l.getProduct().getPrice(); double[] sale = new double[3]; if (salesOrder.containsKey(code)) { sale = salesOrder.get(code); sale[0] += quant; sale[1] += total; } else { sale[0] = quant; sale[1] = total; } sale[2] = 0; salesOrder.put(code, sale); } } Iterator<Map.Entry<String, double[]>> entries = salesOrder.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, double[]> entry = entries.next(); String code = entry.getKey(); double[] sale = entry.getValue(); sale[2] = sale[1] / sale[0]; salesOrder.put(code, sale); } }
@Test public void setGetPurchaseOrder() { testInvoice = new Invoice(); String po = UUID.randomUUID().toString(); testInvoice.setPurchaseOrder(po); String returnedPo = testInvoice.getPurchaseOrder(); Assert.assertEquals(po, returnedPo); }
public InvoiceLocal(Invoice invoice) { this.organisationID = invoice.getOrganisationID(); this.invoiceIDPrefix = invoice.getInvoiceIDPrefix(); this.invoiceID = invoice.getInvoiceID(); this.invoice = invoice; this.invoiceActionHandlers = new HashSet<InvoiceActionHandler>(); invoice.setInvoiceLocal(this); }
@Test public void ubl_can_be_converted_to_invoice() throws IOException { byte[] xml = IOUtils.getResourceAsByteArray(RESOURCES_PATH + "/" + TEST_UBL_FILE_NAME); assertNotNull(xml); Invoice invoice = documentService.convertToInvoice(xml); assertNotNull(invoice); assertNotNull(invoice.getContent()); }
/** * Create an adjustment for a given invoice item. This just creates the object in memory, it * doesn't write it to disk. * * @param invoiceToBeAdjusted the invoice * @param invoiceItemId the invoice item id to adjust * @param positiveAdjAmount the amount to adjust. Pass null to adjust the full amount of the * original item * @param currency the currency of the amount. Pass null to default to the original currency used * @param effectiveDate adjustment effective date, in the account timezone * @return the adjustment item */ public InvoiceItem createAdjustmentItem( final Invoice invoiceToBeAdjusted, final UUID invoiceItemId, @Nullable final BigDecimal positiveAdjAmount, @Nullable final Currency currency, final LocalDate effectiveDate, final InternalCallContext context) throws InvoiceApiException { final InvoiceItem invoiceItemToBeAdjusted = Iterables.<InvoiceItem>tryFind( invoiceToBeAdjusted.getInvoiceItems(), new Predicate<InvoiceItem>() { @Override public boolean apply(final InvoiceItem input) { return input.getId().equals(invoiceItemId); } }) .orNull(); if (invoiceItemToBeAdjusted == null) { throw new InvoiceApiException(ErrorCode.INVOICE_ITEM_NOT_FOUND, invoiceItemId); } // Check the specified currency matches the one of the existing invoice final Currency currencyForAdjustment = Objects.firstNonNull(currency, invoiceItemToBeAdjusted.getCurrency()); if (invoiceItemToBeAdjusted.getCurrency() != currencyForAdjustment) { throw new InvoiceApiException( ErrorCode.CURRENCY_INVALID, currency, invoiceItemToBeAdjusted.getCurrency()); } // Reuse the same logic we have for refund with item adjustment final Map<UUID, BigDecimal> input = new HashMap<UUID, BigDecimal>(); input.put(invoiceItemId, positiveAdjAmount); final Map<UUID, BigDecimal> output = dao.computeItemAdjustments(invoiceToBeAdjusted.getId().toString(), input, context); // If we pass that stage, it means the validation succeeded so we just need to extract resulting // amount and negate the result. final BigDecimal amountToAdjust = output.get(invoiceItemId).negate(); // Finally, create the adjustment return new ItemAdjInvoiceItem( UUIDs.randomUUID(), context.getCreatedDate(), invoiceItemToBeAdjusted.getInvoiceId(), invoiceItemToBeAdjusted.getAccountId(), effectiveDate, null, amountToAdjust, currencyForAdjustment, invoiceItemToBeAdjusted.getId()); }
public Invoice issuance(InvoiceRequest invoiceRequest, TaxPolicy taxPolicy) { Invoice invoice = invoiceFactory.create(invoiceRequest.getClientData()); for (RequestItem item : invoiceRequest.getItems()) { Money net = item.getTotalCost(); Tax tax = taxPolicy.calculateTax(item.getProductData().getType(), net); InvoiceLine invoiceLine = new InvoiceLine(item.getProductData(), item.getQuantity(), net, tax); invoice.addItem(invoiceLine); } return invoice; }
@Before public void setUpParentInvoices() throws Exception { inv1 = new Invoice(); inv2 = new Invoice(); inv1.setInvoiceNumber("000001"); inv2.setInvoiceNumber("000002"); chg1 = new Charge(); chg2 = new Charge(); chg1.setReference("ABC"); chg2.setReference("DEF"); }
private void finishBtnActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_finishBtnActionPerformed if (mileageField.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "Mileage must be filled in"); return; } Invoice invoice = new Invoice(); invoice.setCustomerID(currentCustomer); Integer mileage = 0; try { mileage = Integer.parseInt(mileageField.getText()); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(this, "Incorrect format for mileage"); return; } invoice.setMileageOut(mileage); invoice.setPayment(false); Date date = new Date( datePicker.getModel().getYear() - 1900, datePicker.getModel().getMonth(), datePicker.getModel().getDay()); ArrayList<WorkOrder> temp = new ArrayList<>(); for (WorkOrder w : customersWos) { if (((Integer) woComboBox1.getSelectedItem()).equals(w.getOrderNo())) { w.setEndTime(date); temp.add(w); invoice.setWorkOrderList(temp); } } MainWindow.em.getTransaction().begin(); MainWindow.em.persist(invoice); MainWindow.em.flush(); MainWindow.em.refresh(invoice); for (WorkOrder wo : temp) { wo.setInvoiceNo(invoice); MainWindow.em.persist(wo); MainWindow.em.flush(); MainWindow.em.refresh(wo); } MainWindow.em.getTransaction().commit(); JOptionPane.showMessageDialog( this, "Invoice successfully created.", "Success", JOptionPane.INFORMATION_MESSAGE); this.setVisible(false); parent.setInvoiceTable(); } // GEN-LAST:event_finishBtnActionPerformed
public List<InvoiceItem> dispatchToInvoicePluginsAndInsertItems( final UUID accountId, final boolean isDryRun, final WithAccountLock withAccountLock, final CallContext context) throws InvoiceApiException { GlobalLock lock = null; try { lock = locker.lockWithNumberOfTries( LockerType.ACCNT_INV_PAY.toString(), accountId.toString(), invoiceConfig.getMaxGlobalLockRetries()); final Iterable<Invoice> invoicesForPlugins = withAccountLock.prepareInvoices(); final List<InvoiceModelDao> invoiceModelDaos = new LinkedList<InvoiceModelDao>(); for (final Invoice invoiceForPlugin : invoicesForPlugins) { // Call plugin final List<InvoiceItem> additionalInvoiceItems = invoicePluginDispatcher.getAdditionalInvoiceItems(invoiceForPlugin, isDryRun, context); invoiceForPlugin.addInvoiceItems(additionalInvoiceItems); // Transformation to InvoiceModelDao final InvoiceModelDao invoiceModelDao = new InvoiceModelDao(invoiceForPlugin); final List<InvoiceItem> invoiceItems = invoiceForPlugin.getInvoiceItems(); final List<InvoiceItemModelDao> invoiceItemModelDaos = toInvoiceItemModelDao(invoiceItems); invoiceModelDao.addInvoiceItems(invoiceItemModelDaos); // Keep track of modified invoices invoiceModelDaos.add(invoiceModelDao); } final InternalCallContext internalCallContext = internalCallContextFactory.createInternalCallContext(accountId, context); final List<InvoiceItemModelDao> createdInvoiceItems = dao.createInvoices(invoiceModelDaos, internalCallContext); return fromInvoiceItemModelDao(createdInvoiceItems); } catch (final LockFailedException e) { log.error( String.format("Failed to process invoice items for account %s", accountId.toString()), e); return ImmutableList.<InvoiceItem>of(); } finally { if (lock != null) { lock.release(); } } }
@Override public int compareTo(Object o) { int val = 0; if (o instanceof InvoiceItems) { InvoiceItems that = (InvoiceItems) o; if (this.invoiceItemId != null && that.invoiceItemId != null) { val = that.invoiceItemId.compareTo(invoiceItemId); } else if (this.amount != null && that.amount != null) { val = that.amount.compareTo(amount); } else if (this.description != null && that.description != null) { val = that.description.compareTo(description); } else if (this.discount != null && that.amount != null) { val = that.amount.compareTo(amount); } else if (this.quantity != null && that.quantity != null) { val = that.quantity.compareTo(quantity); } else if (this.unitPrice != null && that.unitPrice != null) { val = that.unitPrice.compareTo(unitPrice); } else if (this.invoice != null && this.invoice.getInvoiceId() != null && that.invoice != null && that.invoice.getInvoiceId() != null) { val = that.invoice.getInvoiceId().compareTo(invoice.getInvoiceId()); } } return val; }
@Test public void constructor() { Long id = new Random().nextLong(); testInvoice = new Invoice(id); Long returnedId = testInvoice.getId(); Assert.assertEquals(id, returnedId); }
public void testRemoveValidator_postcreateCalculator_postmodifyCalculator() throws Exception { execute("CRUD.new"); setValue("number", "66"); setValue("description", "JUNIT"); execute("CRUD.save"); assertValue("number", ""); assertValue("description", ""); assertNoErrors(); assertMessage("Delivery type created successfully"); setValue("number", "66"); execute("CRUD.refresh"); assertValue("number", "66"); assertValue("description", "JUNIT CREATED"); // 'CREATED' is added in postcreate setValue("description", "JUNIT"); execute("CRUD.save"); assertValue("number", ""); assertValue("description", ""); assertNoErrors(); assertMessage("Delivery type modified successfully"); setValue("number", "66"); execute("CRUD.refresh"); assertValue("number", "66"); assertValue("description", "JUNIT MODIFIED"); // 'MODIFIED' is added in postmodify Delivery delivery = new Delivery(); Invoice invoice = Invoice.findByYearNumber(2002, 1); delivery.setInvoice(invoice); DeliveryType deliveryType = XPersistence.getManager().find(DeliveryType.class, 66); delivery.setType(deliveryType); delivery.setNumber(66); delivery.setDescription("JUNIT FOR DELIVERY TYPE"); delivery.setDate(new java.util.Date()); setDeliveryAdvice(delivery, "JUNIT ADVICE"); XPersistence.getManager().persist(delivery); XPersistence.commit(); execute("CRUD.delete"); assertError("Delivery type 66 can not delete because it is used in deliveries"); assertEditable("description"); // because return to main view (and controllers) delivery = XPersistence.getManager().merge(delivery); XPersistence.getManager().remove(delivery); XPersistence.commit(); execute("CRUD.delete"); assertNoErrors(); assertMessage("Delivery type deleted successfully"); }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { int clientReference = new Integer(request.getParameter("clientReference")); OnlineClient onlineClient = OnlineClients.instance().get(clientReference); response.setCharacterEncoding("utf-8"); response.setContentType("application/json"); if (!onlineClient.isAuthenticated(request) && !(onlineClient.hasAccess(AccessPermission.INVOICE_CANCEL) || onlineClient.hasAccess(AccessPermission.ADMIN))) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getWriter().write("acceso denegado"); } String argsParam = request.getParameter("args"); String args = URLDecoder.decode(argsParam, "utf-8").toUpperCase(); String invoiceREF = null; org.bson.Document oInvoice = null; Invoice invoice = null; String[] argsspl = null; if (!args.equals("")) { argsspl = args.split(" "); if (argsspl.length == 1) { invoiceREF = argsspl[0].toUpperCase(); oInvoice = new Mongoi().doFindOne(Mongoi.INVOICES, "{ \"reference\" : \"" + invoiceREF + "\" }"); if (oInvoice == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write("error: referencia no encontrada '" + argsspl[0] + "'"); return; } invoice = new Gson().fromJson(oInvoice.toJson(), InvoiceFM01.class); if (invoice.attemptToLog(LogKind.CANCEL).isAllowed()) { if (invoice.hasElectronicVersion()) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; Document document = null; try { builder = factory.newDocumentBuilder(); document = builder.parse( new InputSource(new StringReader(invoice.getElectronicVersion().getXml()))); } catch (Exception e) { e.printStackTrace(); } Node node = document.getElementsByTagName("tfd:TimbreFiscalDigital").item(0); Element e = (Element) node; String uuid = e.getAttribute("UUID"); System.out.println("UUID:" + uuid); GSettings g = GSettings.instance(); Rhino rhino = new Rhino( g.getKey("CERTIFICATE"), g.getKey("PRIVATE_KEY"), g.getKey("PRIVATE_KEY_PASS")); rhino.setOpenSSL(g.getKey("SSL")); String cancel = rhino.cancelar( g.getKey("INVOICE_CERTIFICATE_AUTHORITY_USER"), g.getKey("INVOICE_CERTIFICATE_AUTHORITY_PASS"), g.getKey("INVOICE_SENDER_TAX_CODE"), uuid); document = builder.parse(new ByteArrayInputStream(cancel.getBytes())); NodeList nlist = document.getElementsByTagName("codigo"); System.out.println("CANCEL RESPONSE: " + cancel); if (nlist.item(0).getTextContent().equals("0") || nlist.item(0).getTextContent().equals("-5")) { String xml = document.getElementsByTagName("xmlretorno").item(0).getTextContent(); new Mongoi() .doUpdate( Mongoi.INVOICES, "{ \"reference\" : \"" + invoiceREF + "\"}", "{ \"electronicVersion.cancelXml\" : \"" + StringEscapeUtils.unescapeXml(xml) + "\"}"); new Mongoi() .doUpdate( Mongoi.INVOICES, "{ \"reference\" : \"" + invoiceREF + "\"}", "{ \"electronicVersion.active\" : false }"); JGet.stringTofile( StringEscapeUtils.unescapeXml(xml), GSettings.get("TMP_FOLDER") + invoice.getReference() + "-CANCELADO.xml"); if (!invoice.getClient().getEmail().equals("")) { HotmailSend.send( "factura CANCELADA " + invoice.getReference(), "la factura con folio fiscal \n" + uuid + "\nha sido cancelada.\n" + GSettings.get("EMAIL_BODY"), invoice.getClient().getEmail().split(" ") /*, new String[]{ GSettings.get("TMP_FOLDER")+invoice.getReference()+"-CANCELADO.xml"}, new String[]{invoice.getReference()+"-CANCELADO.xml"} */); } if (!invoice.getAgent().getEmail().equals("")) { HotmailSend.send( "factura CANCELADA " + invoice.getReference(), "la factura con folio fiscal \n" + uuid + "\nha sido cancelada.\n" + GSettings.get("EMAIL_BODY"), invoice.getAgent().getEmail().split(" ") /*, new String[]{ GSettings.get("TMP_FOLDER")+invoice.getReference()+"-CANCELADO.xml"}, new String[]{invoice.getReference()+"-CANCELADO.xml"} */); } } else { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); response .getWriter() .write( "ERROR: " + document.getElementsByTagName("mensaje").item(0).getTextContent()); return; } } InvoiceLog log = new InvoiceLog( InvoiceLog.LogKind.CANCEL, true, onlineClient.getShopman().getLogin()); InvoiceLog closeLog = new InvoiceLog( InvoiceLog.LogKind.CLOSE, true, onlineClient.getShopman().getLogin()); new Mongoi() .doPush( Mongoi.INVOICES, "{ \"reference\" : \"" + invoiceREF + "\"}", "{\"logs\" : " + new Gson().toJson(log) + " }"); new Mongoi() .doPush( Mongoi.INVOICES, "{ \"reference\" : \"" + invoiceREF + "\"}", "{\"logs\" : " + new Gson().toJson(closeLog) + " }"); new Mongoi() .doUpdate( Mongoi.INVOICES, "{ \"reference\" : \"" + invoiceREF + "\"}", "{\"updated\" : " + closeLog.getDate() + " }"); float cashIn = 0; if (invoice.hasLog(LogKind.AGENT_PAYMENT)) cashIn = invoice.getAgentPayment(); float cashOut = invoice.getTotal() - invoice.getDebt(); TheBox.instance().plus(cashIn - cashOut); TheBox.instance() .addLog( new TheBoxLog( cashOut - cashIn, log.getDate(), invoice.getReference(), LogKind.CANCEL.toString(), onlineClient.getShopman().getLogin())); List<InvoiceItem> invoiceItems = invoice.getItems(); for (int i = 0; i < invoiceItems.size(); i++) { InvoiceItem item = invoiceItems.get(i); if (Inventory.exists(item) && !item.isDisabled()) Inventory.incrementStored(item); } String successResponse = "CANCELADO " + invoice.getReference() + ": se realizó entrada-salida en caja $" + cashIn + "-$" + cashOut + " --> $" + (cashIn - cashOut); response.getWriter().write("{ \"message\":\"" + successResponse + "\" }"); return; } else { System.out.println("error al intentar cancelar documento"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getWriter().write(invoice.attemptToLog(LogKind.CANCEL).getMessage()); return; } } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response .getWriter() .write( "numero de parametros incorrecto, especifica la referencia de un solo documento"); return; } } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write("error: define una referencia"); return; } } catch (Exception e) { e.printStackTrace(); } }
/** * Determine the cost of a given number of an item and calculate a new value for the item * accordingly. * * @param oper 1 for buying, 0 for selling. * @param commodity the commodity in question * @param amount the desired amount of the item in question * @return the total cost and the calculated new value as an Invoice */ public Invoice generateInvoice(int oper, Commodities commodity, int amount) { // get the initial value of the item, 0 for not found Invoice inv = new Invoice(0.0, 0.0); inv.value = commodity.getValue(); // get the spread so we can do one initial decrement of the value if we are selling BigDecimal spread = BigDecimal.valueOf(commodity.getSpread()); // determine the total cost inv.total = 0.0; for (int x = 1; x <= amount; x++) { BigDecimal minValue = BigDecimal.valueOf(commodity.getMinValue()); BigDecimal maxValue = BigDecimal.valueOf(commodity.getMaxValue()); BigDecimal changeRate = BigDecimal.valueOf(commodity.getChangeRate()); // work the spread on the first one. if ((oper == 0) && (x == 1)) { inv.subtractValue(spread.doubleValue()); } else if ((oper == 0) && (x > 1)) { // otherwise, do the usual decriment. inv.subtractValue(changeRate.doubleValue()); } // check the current value if (inv.getValue() >= minValue.doubleValue()) { // current value is @ or above minValue // be sure value is not above maxValue if (inv.getValue() < maxValue.doubleValue()) { // current value is "just right" inv.addTotal(inv.getValue()); // add current value to total } else { // current value is above the max inv.addTotal(maxValue.doubleValue()); // add maxValue to total } } else { // current value is below the minimum inv.addTotal(minValue.doubleValue()); // add the minimum to total if ((oper == 0) && (x == 1)) { inv.subtractTotal( spread .doubleValue()); // subtract the spread if we're selling and this is the first run } } // Change our stored value for the item // we don't care about min/maxValue here because we don't want the value to 'bounce' off of // them. if (oper == 1) { inv.addValue(changeRate.doubleValue()); } } return inv; }
/** * Buy a specified amount of an item for the player. * * @param player The player on behalf of which these actions will be carried out. * @param item The desired item in the form of the item name. * @param amount The desired amount of the item to purchase. * @return true on success, false on failure. */ public boolean buy(Player player, String item, int amount) { // Be sure we have a positive amount if (amount < 1) { player.sendMessage(ChatColor.RED + "Invalid amount."); player.sendMessage("No negative numbers or zero, please."); return false; } // retrieve the commodity in question Commodities commodity = plugin.getDatabase().find(Commodities.class).where().ieq("name", item).findUnique(); // check that we found something if (commodity == null) { player.sendMessage(ChatColor.RED + "Not allowed to buy that item."); player.sendMessage("Be sure you typed the correct name"); return false; } // determine what it will cost Invoice invoice = generateInvoice(1, commodity, amount); // check the player's wallet if (economy.has(player.getName(), invoice.getTotal())) { // give 'em the items and drop any extra Byte byteData = Byte.valueOf(String.valueOf(commodity.getData())); int id = commodity.getNumber(); HashMap<Integer, ItemStack> overflow = player.getInventory().addItem(new ItemStack(id, amount, (short) 0, byteData)); for (int a : overflow.keySet()) { player.getWorld().dropItem(player.getLocation(), overflow.get(a)); } // save the new value commodity.setValue(invoice.getValue()); getDatabase().save(commodity); // use BigDecimal to format value for output double v = commodity.getValue(); double max = commodity.getMaxValue(); double min = commodity.getMinValue(); BigDecimal value; if (v < max && v > min) { value = BigDecimal.valueOf(v).setScale(2, RoundingMode.HALF_UP); } else if (v <= min) { value = BigDecimal.valueOf(min).setScale(2, RoundingMode.HALF_UP); } else { value = BigDecimal.valueOf(max).setScale(2, RoundingMode.HALF_UP); } // Give some nice output. player.sendMessage(ChatColor.GREEN + "--------------------------------"); player.sendMessage( ChatColor.GREEN + "Old Balance: " + ChatColor.WHITE + BigDecimal.valueOf(economy.getBalance(player.getName())) .setScale(2, RoundingMode.HALF_UP)); // Subtract the invoice (this is an efficient place to do this) economy.withdrawPlayer(player.getName(), invoice.getTotal()); player.sendMessage( ChatColor.GREEN + "Cost: " + ChatColor.WHITE + BigDecimal.valueOf(invoice.getTotal()).setScale(2, RoundingMode.HALF_UP)); player.sendMessage( ChatColor.GREEN + "New Balance: " + ChatColor.WHITE + BigDecimal.valueOf(economy.getBalance(player.getName())) .setScale(2, RoundingMode.HALF_UP)); player.sendMessage(ChatColor.GREEN + "--------------------------------"); player.sendMessage( ChatColor.GRAY + item + ChatColor.GREEN + " New Price: " + ChatColor.WHITE + value); return true; } else { // Otherwise, give nice output anyway ;) // The idea here is to show how much more money is needed. BigDecimal difference = BigDecimal.valueOf(economy.getBalance(player.getName()) - invoice.getTotal()) .setScale(2, RoundingMode.HALF_UP); player.sendMessage(ChatColor.RED + "You don't have enough money"); player.sendMessage( ChatColor.GREEN + "Balance: " + ChatColor.WHITE + BigDecimal.valueOf(economy.getBalance(player.getName())) .setScale(2, RoundingMode.HALF_UP)); player.sendMessage( ChatColor.GREEN + "Cost: " + ChatColor.WHITE + BigDecimal.valueOf(invoice.getTotal()).setScale(2, RoundingMode.HALF_UP)); player.sendMessage(ChatColor.GREEN + "Difference: " + ChatColor.RED + difference); return true; } }
@Test public void getType() { testInvoice = new Invoice(); Assert.assertEquals("Invoice", testInvoice.getType()); }
/** * Sell a specified amount of an item for the player. * * @param player The player on behalf of which these actions will be carried out. * @param item The desired item in the form of the item name. * @param amount The desired amount of the item to sell. * @return true on success, false on failure. */ public boolean sell(Player player, String item, int amount) { // Be sure we have a positive amount if (amount < 1) { player.sendMessage(ChatColor.RED + "Invalid amount."); player.sendMessage("No negative numbers or zero, please."); return false; } // retrieve the commodity in question Commodities commodity = plugin.getDatabase().find(Commodities.class).where().ieq("name", item).findUnique(); if (commodity == null) { player.sendMessage(ChatColor.RED + "Not allowed to buy that item."); player.sendMessage("Be sure you typed the correct name"); return false; } // determine what it will pay Invoice invoice = generateInvoice(0, commodity, amount); // If the player has enough of the item, perform the transaction. int id = commodity.getNumber(); Byte byteData = Byte.valueOf(String.valueOf(commodity.getData())); ItemStack its = new ItemStack(id, amount, (short) 0, byteData); if (player.getInventory().contains(id)) { // Figure out how much is left over int left = getAmountInInventory(player, its) - amount; if (left < 0) { // this indicates the correct id, but the wrong bytedata value // give nice output even if they gave a bad name. player.sendMessage(ChatColor.RED + "You don't have enough " + item); player.sendMessage( ChatColor.GREEN + "In Inventory: " + ChatColor.WHITE + getAmountInInventory(player, its)); player.sendMessage(ChatColor.GREEN + "Attempted Amount: " + ChatColor.WHITE + amount); return false; } // Take out all of the item int x = 0; for (@SuppressWarnings("unused") ItemStack stack : player .getInventory() .getContents()) { // we do it this way incase a user has an expanded inventory via // another plugin ItemStack slot = player.getInventory().getItem(x); if (slot != null) { Byte slotData = Byte.valueOf("0"); try { slotData = slot.getData().getData(); } catch (NullPointerException e) { } if ((slot.getTypeId() == id) && (slotData.compareTo(byteData) == 0)) { player.getInventory().clear(x); } } x++; } // put back what was left over if (left > 0) { ItemStack itsLeft = its; itsLeft.setAmount(left); player.getInventory().addItem(itsLeft); } // record the change in value commodity.setValue(invoice.getValue()); plugin.getDatabase().save(commodity); // use BigDecimal to format value for output double v = commodity.getValue(); double max = commodity.getMaxValue(); double min = commodity.getMinValue(); BigDecimal value; if (v < max && v > min) { value = BigDecimal.valueOf(v).setScale(2, RoundingMode.HALF_UP); } else if (v <= min) { value = BigDecimal.valueOf(min).setScale(2, RoundingMode.HALF_UP); } else { value = BigDecimal.valueOf(max).setScale(2, RoundingMode.HALF_UP); } BigDecimal spread = BigDecimal.valueOf(commodity.getSpread()); // give some nice output BigDecimal sale = BigDecimal.valueOf((invoice.getTotal() + spread.doubleValue())) .setScale(2, RoundingMode.HALF_UP); player.sendMessage(ChatColor.GREEN + "--------------------------------"); player.sendMessage( ChatColor.GREEN + "Old Balance: " + ChatColor.WHITE + BigDecimal.valueOf(economy.getBalance(player.getName())) .setScale(2, RoundingMode.HALF_UP)); // deposit the money economy.depositPlayer(player.getName(), invoice.getTotal()); player.sendMessage(ChatColor.GREEN + "Sale: " + ChatColor.WHITE + sale); player.sendMessage(ChatColor.GREEN + "Selling Fee: " + ChatColor.WHITE + spread); player.sendMessage(ChatColor.GREEN + "--------------------------------"); player.sendMessage( ChatColor.GREEN + "Net Gain: " + ChatColor.WHITE + BigDecimal.valueOf(invoice.getTotal()).setScale(2, RoundingMode.HALF_UP)); player.sendMessage( ChatColor.GREEN + "New Balance: " + ChatColor.WHITE + BigDecimal.valueOf(economy.getBalance(player.getName())) .setScale(2, RoundingMode.HALF_UP)); player.sendMessage(ChatColor.GREEN + "--------------------------------"); player.sendMessage( ChatColor.GRAY + item + ChatColor.GREEN + " New Price: " + ChatColor.WHITE + value); return true; } else { // give nice output even if they gave a bad number. player.sendMessage(ChatColor.RED + "You don't have enough " + item); player.sendMessage( ChatColor.GREEN + "In Inventory: " + ChatColor.WHITE + getAmountInInventory(player, its)); player.sendMessage(ChatColor.GREEN + "Attempted Amount: " + ChatColor.WHITE + amount); return false; } }
public boolean sellAll(Player player) { // make a list of all commodities List<Commodities> commodities = plugin.getDatabase().find(Commodities.class).findList(); // run thru each slot in the player's inventory for commodities int index = 0; BigDecimal sale = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP); for (@SuppressWarnings("unused") ItemStack stack : player .getInventory() .getContents()) { // we do it this way incase a user has an expanded inventory via // another plugin ItemStack slot = player.getInventory().getItem(index); int slotId = slot.getTypeId(); BigDecimal slotAmount = new BigDecimal(slot.getAmount()).setScale(0, RoundingMode.HALF_UP); Byte slotByteData = Byte.valueOf("0"); try { slotByteData = slot.getData().getData(); } catch (NullPointerException e) { slotByteData = Byte.valueOf("0"); } for (int x = 0; x < commodities.size(); x++) { if ((commodities.get(x).getNumber() == slotId) && (Byte.valueOf(String.valueOf(commodities.get(x).getData())).compareTo(slotByteData) == 0)) { Invoice thisSale = generateInvoice( 0, // perform sale of this slot commodities.get(x), slotAmount.intValue()); sale = sale.add(BigDecimal.valueOf(thisSale.getTotal())); // rack up our total // save the new value commodities.get(x).setValue(thisSale.getValue()); plugin.getDatabase().save(commodities.get(x)); player.getInventory().clear(index); // remove the item(s) economy.depositPlayer( player.getName(), // "pay the man" thisSale.getTotal()); // give nice output player.sendMessage( ChatColor.GREEN + "Sold " + ChatColor.WHITE + slotAmount + " " + ChatColor.GRAY + commodities.get(x).getName() + ChatColor.GREEN + " for " + ChatColor.WHITE + BigDecimal.valueOf(thisSale.getTotal()).setScale(2, RoundingMode.HALF_UP)); break; } } index++; } // give a nice total column if (sale == BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)) player.sendMessage("Nothing to Sell"); player.sendMessage(ChatColor.GREEN + "--------------------------------"); player.sendMessage( ChatColor.GREEN + "Total Sale: " + ChatColor.WHITE + sale.setScale(2, RoundingMode.HALF_UP)); return true; }
@Test public void invoice_can_be_validated() throws IOException { byte[] xml = IOUtils.getResourceAsByteArray(RESOURCES_PATH + "/" + TEST_UBL_FILE_NAME); Invoice invoice = documentService.convertToInvoice(xml); assertNotNull(invoice); assertNotNull(invoice.getContent()); assertNotNull(invoice.getContent().getID()); assertEquals("HSD5", invoice.getContent().getID().getValue()); assertNotNull(invoice.getContent().getAccountingCustomerParty()); assertNotNull(invoice.getContent().getAccountingCustomerParty().getParty()); assertNotNull(invoice.getContent().getAccountingCustomerParty().getParty().getPartyName()); assertTrue( invoice.getContent().getAccountingCustomerParty().getParty().getPartyName().size() > 0); assertNotNull( invoice .getContent() .getAccountingCustomerParty() .getParty() .getPartyName() .get(0) .getName()); assertEquals( "Lemberg", invoice .getContent() .getAccountingCustomerParty() .getParty() .getPartyName() .get(0) .getName() .getValue()); assertNotNull(invoice.getContent().getAccountingCustomerParty().getParty().getPostalAddress()); assertNotNull( invoice .getContent() .getAccountingCustomerParty() .getParty() .getPostalAddress() .getCountry()); assertNotNull( invoice .getContent() .getAccountingCustomerParty() .getParty() .getPostalAddress() .getCountry() .getIdentificationCode()); assertEquals( "UA", invoice .getContent() .getAccountingCustomerParty() .getParty() .getPostalAddress() .getCountry() .getIdentificationCode() .getValue()); assertNotNull(invoice.getContent().getLegalMonetaryTotal()); assertNotNull(invoice.getContent().getLegalMonetaryTotal().getPayableAmount()); assertEquals( new BigDecimal("760.00"), invoice.getContent().getLegalMonetaryTotal().getPayableAmount().getValue()); assertNotNull(invoice.getContent().getDocumentCurrencyCode()); assertEquals("DKK", invoice.getContent().getDocumentCurrencyCode().getValue()); }
@Override public void pay() { master.transitionTo(new PayedStatus(master)); }
@Test public void testCreatePayment() throws PaymentException { Invoice invoice = new Invoice("some-iban", "some-address", null, BigDecimal.TEN); Payment payment = paymentCreator.createPayment(invoice); assertEquals(payment.getReceiverAccount(), invoice.getIban()); }
public void writeToFile(String invID, String carNumber, String carModel, String packName) { String separator = System.getProperty("line.separator"); // variable declarations for storing the data from the database. String bookedBy = new String(); String usedBy = new String(); String branch = new String(); int dd = 0, mm = 0, yyyy = 0, usedKms = 0, usedHours = 0, packKms = 0, packHours = 0; Double eKmsCharge = 0.0; Double eHoursCharge = 0.0; Double osaDays = 0.0; Double osaNights = 0.0; Double parking = 0.0; Double others = 0.0; Double subTotalA = 0.0; Double subTotalB = 0.0; Double serviceTax = 0.0; Double bookingAmount = 0.0; Double finalAmount = 0.0; String compName = new String(); String compAddr = new String(); String compPAN = new String(); String compDD = new String(); try { Connection con = db.createConnection(); Connection con2 = db.createConnection(); String retrieveStatement = "select * from invoices where invoiceno=?"; String retrieveCompanyInfo = "select * from company"; PreparedStatement ps = con.prepareStatement(retrieveStatement); Statement st = con2.createStatement(); ps.setString(1, invID); ResultSet rs = ps.executeQuery(); ResultSet rs2 = st.executeQuery(retrieveCompanyInfo); while (rs.next()) { bookedBy = rs.getString(2); usedBy = rs.getString(3); branch = rs.getString(4); dd = rs.getInt(5); mm = rs.getInt(6); yyyy = rs.getInt(7); usedKms = rs.getInt(8); usedHours = rs.getInt(9); packKms = rs.getInt(10); packHours = rs.getInt(11); eKmsCharge = rs.getDouble(13); eHoursCharge = rs.getDouble(14); osaDays = rs.getDouble(15); osaNights = rs.getDouble(16); parking = rs.getDouble(17); others = rs.getDouble(18); subTotalA = rs.getDouble(19); subTotalB = rs.getDouble(20); serviceTax = rs.getDouble(21); bookingAmount = rs.getDouble(22); finalAmount = rs.getDouble(23); } while (rs2.next()) { compName = rs2.getString(1); compAddr = rs2.getString(2); compPAN = rs2.getString(3); compDD = rs2.getString(4); } File file = new File("temp.txt"); Writer writer = new BufferedWriter(new FileWriter(file)); writer.write(separator + " Invoice ID: " + invID); writer.write(separator + " Company Name: " + compName); writer.write( separator + " Used By: " + usedBy + separator + " Booked By: " + bookedBy + " Branch Requested: " + branch); writer.write( separator + "------------------------------------------------------------------------------------------------------------------"); writer.write(separator + " Car No.: " + carNumber + "\t\tCar Alotted: " + carModel); writer.write(separator + " Package: " + packName); writer.write( separator + " Kms Used: " + usedKms + " Extra Kms: " + (usedKms - packKms) + " Extra Kms Charge(@10% extra rate): " + eKmsCharge); writer.write( separator + " Hours Used: " + usedHours + " Extra Hours: " + (usedHours - packHours) + " Extra Hours Charge(@Rs.50/hr): " + eHoursCharge); writer.write( separator + " Car Used On: " + dd + "-" + mm + "-" + yyyy + " Sub Total (A): " + subTotalA); writer.write( separator + "------------------------------------------------------------------------------------------------------------------"); writer.write( separator + " Parking & Toll: " + parking + " Others: " + others); writer.write( separator + " Out Station Allowance (in Rs.) for \t Days: " + osaDays + " Nights: " + osaNights); writer.write( separator + " Sub Total (B): " + subTotalB); writer.write( separator + "------------------------------------------------------------------------------------------------------------------"); writer.write( separator + " Total (A+B): " + (subTotalA + subTotalB)); writer.write( separator + separator + " PAN: " + compPAN + " Service Tax: " + serviceTax); writer.write(separator + " Service Tax Category: Rent-a-Cab\t\tTotal: " + finalAmount); writer.write( separator + " All Cheques/Drafts to be drawn in favor of\t\tBooking Amount: " + bookingAmount + separator + " " + compDD + "\t\tNet Payable: " + (finalAmount - bookingAmount)); writer.write(separator + separator + " Billing Address" + separator + " " + compAddr); writer.flush(); con.close(); con2.close(); Invoice i = new Invoice(); i.setVisible(true); } catch (Exception ee) { ee.printStackTrace(); } }
private static List<Invoice> parser(String text) { JsArray<InvoiceJavaScript> modulosJS = InvoiceJavaScript.eval(text); List<Invoice> invoices = new ArrayList<Invoice>(); for (int i = 0, j = modulosJS.length(); i < j; i++) { InvoiceJavaScript invoiceJavaScript = modulosJS.get(i); Invoice invoice = new Invoice(); invoice.setCode(invoiceJavaScript.getCode()); invoice.setContractId(invoiceJavaScript.getContractId()); invoice.setContractName(invoiceJavaScript.getContractName()); invoice.setId(invoiceJavaScript.getId()); invoice.setInvoiceStatusId(invoiceJavaScript.getInvoiceStatusId()); invoice.setInvoiceStatusName(invoiceJavaScript.getInvoiceStatusName()); invoice.setClientId(invoiceJavaScript.getClientId()); invoice.setClientName(invoiceJavaScript.getClientName()); invoice.setAmount(invoiceJavaScript.getAmount()); try { invoice.setDate(invoiceJavaScript.getDate()); } catch (IllegalValueException e) { Window.alert("Error con las fechas de contrato: " + e.getMessage()); } invoices.add(invoice); } return invoices; }
public static void main(String[] args) { // Prepare the Xero Client XeroClient xeroClient = null; try { XeroClientProperties clientProperties = new XeroClientProperties(); clientProperties.load(new FileInputStream("./xeroApi.properties")); xeroClient = new XeroClient(clientProperties); } catch (IOException ex) { ex.printStackTrace(); } // Retrieve a list of Invoices try { ArrayOfInvoice arrayOfExistingInvoices = xeroClient.getInvoices(); if (arrayOfExistingInvoices != null && arrayOfExistingInvoices.getInvoice() != null) { for (Invoice invoice : arrayOfExistingInvoices.getInvoice()) { System.out.println("Invoice: " + invoice.getInvoiceID()); } // Retrieve an invoice as a PDF // (can be used to retrieve json too, just change application/pdf to application/json) if (!arrayOfExistingInvoices.getInvoice().isEmpty()) { xeroClient.getInvoiceAsPdf(arrayOfExistingInvoices.getInvoice().get(0).getInvoiceID()); } } } catch (XeroClientException ex) { ex.printDetails(); } catch (XeroClientUnexpectedException ex) { ex.printStackTrace(); } // Create an Invoice Invoice invoice = null; try { ArrayOfInvoice arrayOfInvoice = new ArrayOfInvoice(); List<Invoice> invoices = arrayOfInvoice.getInvoice(); invoice = new Invoice(); Contact contact = new Contact(); contact.setName("Jane Smith"); contact.setEmailAddress("*****@*****.**"); invoice.setContact(contact); ArrayOfLineItem arrayOfLineItem = new ArrayOfLineItem(); List<LineItem> lineItems = arrayOfLineItem.getLineItem(); LineItem lineItem = new LineItem(); lineItem.setAccountCode("200"); BigDecimal qty = new BigDecimal("2"); lineItem.setQuantity(qty); BigDecimal amnt = new BigDecimal("50.00"); lineItem.setUnitAmount(amnt); lineItem.setDescription("Programming books"); lineItem.setLineAmount(qty.multiply(amnt)); lineItems.add(lineItem); invoice.setLineItems(arrayOfLineItem); invoice.setDate(Calendar.getInstance()); Calendar due = Calendar.getInstance(); due.set(due.get(Calendar.YEAR), due.get(Calendar.MONTH) + 1, 20); invoice.getLineAmountTypes().add("Inclusive"); invoice.setDueDate(due); invoice.setInvoiceNumber("INV-API-001"); invoice.setType(InvoiceType.ACCREC); invoice.setStatus(InvoiceStatus.AUTHORISED); invoices.add(invoice); xeroClient.postInvoices(arrayOfInvoice); } catch (XeroClientException ex) { ex.printDetails(); } catch (XeroClientUnexpectedException ex) { ex.printStackTrace(); } // Create a new Contact try { ArrayOfContact arrayOfContact = new ArrayOfContact(); List<Contact> contacts = arrayOfContact.getContact(); Contact contact1 = new Contact(); contact1.setName("John Smith"); contact1.setEmailAddress("*****@*****.**"); contacts.add(contact1); xeroClient.postContacts(arrayOfContact); } catch (XeroClientException ex) { ex.printDetails(); } catch (XeroClientUnexpectedException ex) { ex.printStackTrace(); } // Add a payment to an exisiting Invoice try { Invoice invoice1 = new Invoice(); invoice1.setInvoiceNumber("INV-0038"); Account account = new Account(); account.setCode("090"); Payment payment = new Payment(); payment.setAccount(account); payment.setInvoice(invoice); payment.setAmount(new BigDecimal("20.00")); payment.setDate(Calendar.getInstance()); ArrayOfPayment arrayOfPayment = new ArrayOfPayment(); List<Payment> payments = arrayOfPayment.getPayment(); payments.add(payment); xeroClient.postPayments(arrayOfPayment); } catch (XeroClientException ex) { ex.printDetails(); } catch (XeroClientUnexpectedException ex) { ex.printStackTrace(); } }
// TODO: clean this mess // TODO: split this huge test // TODO: add assertions @Test public void shouldIfDbIsWorkingAsExpected() { IntegrationTests t = new IntegrationTests(); InvoicesDAO dao = new InvoicesDAO(new EmbeddedDatabaseConnection()); Invoice i = new Invoice(); Invoice i2 = new Invoice(); i.setProductName("Sluchawki"); i.setGuaranteePeriod(2); i.setProductPrice(PRICE); i.setPurchaseDate("2015-01-10"); i.addInvoiceImage(INVOICE_IMAGE_PATH); i2.setProductName("Kebab"); i2.setGuaranteePeriod(1); i2.setProductPrice(PRICE); i2.setPurchaseDate("2016-03-10"); i2.addInvoiceImage(INVOICE_IMAGE_PATH); try { dao.insertInvoiceToDb(i); dao.insertInvoiceToDb(i2); } catch (SQLException e) { e.printStackTrace(); } try { t.invoices = dao.selectAllInvoicesFormDB(); for (Invoice inv : t.invoices) { System.out.println(inv.getProductName()); System.out.println(inv.getProductPrice()); System.out.println(inv.getGuaranteePeriod()); System.out.println(inv.getPurchaseDateAsString()); // TODO this should be cleaned automatically ImageHandler.writeInvoiceImageToDisk(inv, "src/test/"); } System.out.println("------------------------"); System.out.println("Updating"); System.out.println("------------------------"); // change something t.invoices.get(1).setProductName("Taczki"); // update in db dao.updateInvoiceInDb(t.invoices.get(1)); // reload objects t.invoices = dao.selectAllInvoicesFormDB(); for (Invoice inv1 : t.invoices) { System.out.println(inv1.getProductName()); System.out.println(inv1.getProductPrice()); System.out.println(inv1.getGuaranteePeriod()); System.out.println(inv1.getPurchaseDateAsString()); } } catch (SQLException e) { e.printStackTrace(); } }