Add a negative price line item or discount - authorize.net

I'm using coupons in a storefront to offer discounts. Some coupons are for a flat dollar amount for orders greater than a specific value. Like, $10 off an order of $40 or more. Other coupons give a discounted rate, say, 20% off your first order this month (storefront is handling the limit, so can ignore). I want to use authorize.net to process the transactions, and send receipts to customers.
My first thought was to modify the unit price of things that are discounted. This would work fine for rate discounts, though doesn't show all the information. The problem would be for flat discounts. Where do you take the $10 off if there are a few kinds of items.
My second thought was to add a line item with a negative value/price to the order receipt. Authorize doesn't seem to accept negative values for anything, so that was a failure.
We're using the AIM transaction libraries for Java.
Order anetOrder = Order.createOrder();
anetOrder.setInvoiceNumber(sanitize(order.getOrderNumber(), 20));
anetOrder.setShippingCharges(shippingCharges);
anetOrder.setTotalAmount(total);
for (OrderProductIf op : order.getOrderProducts()) {
OrderItem item = OrderItem.createOrderItem();
item.setItemTaxable(true);
item.setItemId(sanitize(op.getSku(), 31));
item.setItemName(sanitize(op.getName(), 31));
item.setItemDescription(sanitize(op.getModel(), 255));
item.setItemPrice(op.getPrice());
item.setItemQuantity(new BigDecimal(op.getQuantity()));
anetOrder.addOrderItem(item);
}
sanitize is a function that limits the length of strings.
Transaction transaction = merchant.createAIMTransaction(TransactionType.AUTH_CAPTURE, total);
transaction.setCreditCard(creditCard);
transaction.setCustomer(customer);
transaction.setOrder(anetOrder);
transaction.setShippingAddress(shippingAddress);
transaction.setShippingCharges(shippingCharges);
Result<Transaction> result = (Result<Transaction>) merchant.postTransaction(transaction);
return getPaymentResult(result);
I'm out of ideas here.

One way would be to calculate the total amount with the discount without modifying the line items, for a $60 sale with a $10 discount below:
<transactionRequest>
<transactionType>authCaptureTransaction</transactionType>
<amount>50</amount>
Then add
<userFields>
<userField>
<name>Discount</name>
<value>$10.00</value>
</userField>
The userField value is arbitrary, make it -$10.00, if you like it better.

The line items are not totaled. SO
Add line item for credit in your system.
When you submit to Authorize.net, check for negative numbers and change description to indicate it is a credit, then change value to positive
Make sure the TOTAL you submit is correct. Authorize.net will not check that your line items add up to the correct total

Related

Tableau SUMIF statement

I have a dataset of movies with the amount of views per day, I want to sum total views per movie and I am doing the following:
SUM(IF [Title] = [Title]
THEN [Views]
END)
But is not giving me the right numbers, can anyone please help me?
You don't need to make a calculated field every time you want to see values in Tableau - that's part of the beauty of it.
Assuming that the Views field is a numeric measure by default, and the Movie field is a text dimension by default, then just drag Movie to one shelf (such as Rows) and Views to another (such as Columns).

Opencart - Calculate price by option field value

I looked everywhere.
I have Opencart 2.0.2.0. Some of my products are vegetable. So for them I want to insert 1kg price and give an input field for customers to enter the weight they are after. So 1kg is $29 and if the customer enters "271"g, the price should be "(29/1000)*271 = $7.85. Do you know the easiest way to implement this and pass this dynamic price?
Thanks heaps.
This OpenCart extension should be able to do it.

Inventory design management - FIFO / Weighted Average design which also needs historical inventory value

I have a database with the following details:
Product
Name
SKU
UOM (There is a UOM master, so all purchase and sales are converted to base uom and stored in the db)
Some other details
has_attribute
has_batch
Attributes
Name
Details/Remarks
Product-Attribute
Product (FK)
Attribute(FK)
Value of attribute
Inventory Details
#This is added for every product lot bought & quantity available is updated after every sale
Product (FK)
Warehouse (FK to warehoue model)
Purchase Date
Purchase Price
MRP
Tentative sales price
Quantity_bought
Quantity_available
Other batch details if applicable(batch id, manufactured_date, expiry_date)
Inventory Ledger
#This table records all in & out movement of inventory
Product
Warehouse (FK to warehoue model)
Transaction Type (Purchase/Sales)
Quantity_transacted(i.e. quantity purchased/sold)
Inventory_Purchase_cost(So as to calculate inventory valuation)
Now, my problem is:
I need to find out the historical inventory cost. For example, let's say I need to find out the value of inventory on 10th Feb 2017, what I'll be doing with the current table is not very efficient: I'll find out current inventory and go back through the ledger for all 1000-1500 SKU and about 100 transactions daily (for each sku) for more than 120 days and come to a value. taht's about 1500*100*120. It's Huge. Is there a better DB design to handle this case?
Firstly, have you tested it? 1500*100*120 is not that huge. It may be acceptable performance and there is no problem to be solved!
I'm not 100% clear how you compute the value. Do you sum up the InventoryLedger rows for each Product in each Warehouse? Is so, it's easy to put a value on the purchases, but how do you value the sales? I'm going to assume that you value the sales using the Inventory_Purchase_Cost (so it should maybe be called TransactionValue instead).
If you must optimise it, I suggest you could populate a record each day for the valuation of the product in each warehouse. I suggest the following StockValution table could be populated daily and this would allow quick computation of the valuations for any historical day.
Diagram made using QuickDBD, where I work.

Calculating frequency of occurrence as a percentage of total, in Django queryset

In a Django app, I have a queryset for a data model called Comment. This contains text comments left by users.
Imagine 'n' users commented. What's the fastest way to calculate what % of comments were left by which user?
Right now I'm thinking it's going to be:
Comment.objects.filter(commenter=<username>).count()/Comment.objects.count()
What do you suggest? My objective is to flag people who're commenting too much, in order to screen their accounts for possible spamming. I'd be running this query voluminously, hence the focus on performance.
You should avoid making one query for each user in your database. Instead you can just query the number of comments for each user (or even the top n commenters) with something like:
from django.db.models import Count
total_comments = Comment.objects.count()
# Fetch top 10 commenters, annotated with number of comments, ordered by highest first
User.objects.annotate(num_comments=Count('comment')).order_by('-num_comments')[:10]
for user in users:
percentage = user.num_comments / total_comments
This example assumes you have a User model that your Comment has a foreign key to.
The percentage of total comments doesn't actually matter if you are comparing relative numbers of comments.

Kind of complex query in Django with annotate

I have to classes such that
class JobTitle(models.Model):
name = models.CharField(max_length=500,null=False,blank=False)
class Employer(models.Model):
name = models.CharField(max_length=500,null=False,blank=False)
jobtitle = models.ForeignKey(JobTitle,null=False)
revenue = models.IntegerField(null=False)
First I would like to get first 5 job titles whose number of employers is maximum and secondly I need to evaluate those avarage revenue of employers of those five jobtitles.
I may get first 5 job titles like
jtList = JobTitle.objects.filter(isActive=True).annotate(employer_count=Count('employer')).order_by('employer_count')[:5]
I may go over each jobtitle and their employers and sum their revenues and divide them the total number but of course it's a bad and inefficient solution.
How can I achive such operation in django efficiently ?
Thank you
JobTitle.objects.annotate(jobtitle_count=Count('jobtitle')).order_by('-jobtitle_count')[:5]
Summing Revenues in the same currency
If all the revenue numbers are in the same currency, you can do this using annotate and Avg.
job_titles = JobTitle.objects.filter(isActive=True
).annotate(employer__count=Count('employer'),
average_revenue=Avg('employer__revenue'),
).order_by('employer__count')[:5]
Summing Revenues in different currencies
In the comments you mention you'd like to convert revenues from GBP and EUR then sum in USD. I don't have an elegant solution to this I'm afraid.
One approach is to use values() to get the sums in each currency:
# look at the employers in the top job titles
employers = Employer.objects.filter(job_title=job_titles)
currency_totals = employers.values('job_title', 'currency', Count('revenue'), Sum('revenue'))
This will return a ValuesQuerySet, for example
[{'job_title':1, 'currency': 'GBP', 'revenue__sum': 20.0, 'revenue__count': 1},
{'job_title':1, 'currency': 'EUR', 'revenue__sum': 35.0, 'revenue__count': 2},
{'job_title':2, 'currency': 'USD', 'revenue__sum': 50.0, 'revenue__count': 1},
...
]
You can then loop through the results in the view, converting each revenue__sum to USD and adding to a running total for that job title.
This way, you only need one query to get the revenue sums for a given set of job_titles. However, because we process the results in the view, you can't get the database to filter on, or order by the revenue calculations e.g. "show me job titles with equivalent revenue greater than USD 1000".
I'd be interested to see any other approaches -- we have customers paying us in GBP, EUR and USD, so we need to generate similar reports.