Spain an invoice could have different taxes: IVA 0%, IVA 4%, IVA 10%, IVA 21%. I need to show in a tree view all these taxes as columns, no matter if they are all present in the same invoice. For example:
num invoice | client | base 0 | base 4 | base 10 | base 21 | iva 0 | iva 4 | iva 10 | iva 21 | total amount
What should I do to get the list of available taxes and bases and put them as columns in the tree view and show the respective amount in each row
(if tax applies)?
I'm using OpenERP 7, but I hope you can help me no matter what version you use.
The following code was my solution:
# -*- coding: utf-8 -*-
from openerp import models, fields, api, _
# mapping payment method with its human descriptions
PAYMENT_METHODS = [
('bank_transfer', 'Bank transfer'),
('commerce_cod', 'Bank debit'),
('commerce_sermepa', 'Credit card (POS)'),
('commerce_stripe', 'Credit card'),
('pagamastarde', 'Funded payment'),
('paypal_wps', 'PayPal'),
]
class account_invoice_resume(models.Model):
_name = 'account.invoice.resume'
_inherit = 'account.invoice'
_order = 'date_invoice asc, id asc'
_table = 'account_invoice'
#api.depends('partner_id','partner_id.parent_id')
def _get_partner_parent_name(self):
for invoice in self:
if invoice.partner_id.parent_id:
name = invoice.partner_id.parent_id.name
else:
name = invoice.partner_id.name
invoice.display_name = name
# Sum products amount for each type of tax and base
#api.depends('tax_line.name','tax_line.amount','tax_line.base')
def _specific_tax_amount(self):
for invoice in self:
invoice.tax_base_0 = invoice.tax_base_4 = invoice.tax_base_10 = invoice.tax_base_21 = invoice.tax_iva_4 = invoice.tax_iva_10 = invoice.tax_iva_21 = 0.0
amount_without_taxes = invoice.amount_total # Final total of products without taxes or with tax 0%
if len(invoice.tax_line) > 0:
for line in invoice.tax_line:
_tax = line.name.strip()
amount = line.amount
base = line.base
if _tax in ['21% IVA soportado (bienes corrientes)','IVA 21% (Bienes)','IVA 21% (Servicios)']: # If tax is IVA 21%
invoice.tax_iva_21 += amount
invoice.tax_base_21 += base
amount_without_taxes -= amount + base
elif _tax in ['10% IVA soportado (bienes corrientes)','IVA 10% (Bienes)','IVA 10% (Servicios)']: # If tax is IVA 10%
invoice.tax_iva_10 += amount
invoice.tax_base_10 += base
amount_without_taxes -= amount + base
elif _tax in ['4% IVA soportado (bienes corrientes)','IVA 4% (Bienes)']: # If tax is IVA 4%
invoice.tax_iva_4 += amount
invoice.tax_base_4 += base
amount_without_taxes -= amount + base
elif _tax is None or _tax in ['','IVA 0% Entregas Intracomunitarias exentas','IVA 0% Exportaciones','IVA Soportado exento (operaciones corrientes)']: # If tax is IVA 0%
invoice.tax_base_0 += base
amount_without_taxes -= base
# Sum residual amount of prices without 4%, 10% o r21% taxes to base 0
invoice.tax_base_0 += amount_without_taxes
else:
invoice.tax_base_0 = invoice.amount_total
account_invoices_resume()
Related
I'm using (Bahmni with) Odoo-10 and when I press Confirm button in the Sale Order and skip/cancel the Register Payment step, the Total Outstanding amount is displayed as double the actual amount.
Here, the Previous Balance field is taking the amount in the current sale order, and then this value is also getting added with the Net Amount.
When I check the bahmni-erp/bahmni-addons/bahmni_sale/models/sale_order.py, I observe this code under SaleOrder class
prev_outstanding_balance = fields.Monetary(string="Previous Outstanding Balance",
compute=_calculate_balance)
total_outstanding_balance = fields.Monetary(string="Total Outstanding Balance",
compute=_amount_all)
def _calculate_balance(self):
for order in self:
order.prev_outstanding_balance = 0.0
order.total_outstanding_balance = 0.0
total_receivable = order._total_receivable()
order.prev_outstanding_balance = total_receivable
def _amount_all(self):
"""
Compute the total amounts of the SO.
"""
for order in self:
...
order.update({
'amount_untaxed': order.pricelist_id.currency_id.round(amount_untaxed),
'amount_tax': order.pricelist_id.currency_id.round(amount_tax),
'amount_total': amount_total + round_off_amount,
'round_off_amount': round_off_amount,
'total_outstanding_balance': order.prev_outstanding_balance + amount_total + round_off_amount
})
def _total_receivable(self):
receivable = 0.0
if self.partner_id:
self._cr.execute("""SELECT l.partner_id, at.type, SUM(l.debit-l.credit)
FROM account_move_line l
LEFT JOIN account_account a ON (l.account_id=a.id)
LEFT JOIN account_account_type at ON (a.user_type_id=at.id)
WHERE at.type IN ('receivable','payable')
AND l.partner_id = %s
AND l.full_reconcile_id IS NULL
GROUP BY l.partner_id, at.type
""", (self.partner_id.id,))
for pid, type, val in self._cr.fetchall():
if val is None:
val=0
receivable = (type == 'receivable') and val or -val
return receivable
Why it's adding the Net Amount in the current Sale Order to the prev_outstanding_balance?
Please help.
Thanks.
I'd like to find the optimal solution for buying goods from suppliers where the shipping cost is dependent on the cost of goods bought from given supplier. I'm using Pyomo. My code so far is:
model = ConcreteModel(name="(MN_2)")
# products
N = ['prod1', 'prod2', 'prod3']
# suppliers
M = ['A', 'B']
# price
p = {('prod1', 'A'): 10,
('prod2', 'A'): 9,
('prod3', 'A'): 50,
('prod1', 'B'): 16,
('prod2', 'B'): 20,
('prod3', 'B'): 35}
# user quantity contraint
q_u = {('prod1', 'A'): 2,
('prod2', 'A'): 1,
('prod3', 'A'): 1,
('prod1', 'B'): 1,
('prod2', 'B'): 1,
('prod3', 'B'): 1}
# seller quantity contraint
q_s = {('prod1', 'A'): 20,
('prod2', 'A'): 10,
('prod3', 'A'): 10,
('prod1', 'B'): 10,
('prod2', 'B'): 10,
('prod3', 'B'): 10}
# quantity of product n bough in shop m
model.x = Var(N, M, bounds=(0,10))
def obj_rule(model):
return sum(p[n,m]*model.x[n,m] for n in N for m in M)
model.obj = Objective(rule=obj_rule)
def user_quantity(model, n, m):
return model.x[n,m] >= q_u[n,m]
model.user_quantity = Constraint(N, M, rule=user_quantity)
def seller_quantity(model, n, m):
return model.x[n,m] <= q_s[n,m]
model.seller_quantity = Constraint(N, M, rule=seller_quantity)
solver = SolverFactory('glpk')
solver.solve(model)
model.x.pprint()
What I'm struggling with is how to include the shipping cost that is dependent on the cost of goods bought from given supplier. For example:
For supplier A: shipping cost is =
10 if the sum of costs of products bought from them is <= 100,
0 if the sum of costs of products bought from them is > 100
For supplier B: shipping cost is =
8 if the sum of costs of products bought from them is <= 150,
0 if the sum of costs of products bought from them is > 150
The constraints you're describing are an implementation of if-then condition which is described here. The quirk is that your conditions require the binary variable to be 1 if your procurement costs are less than or equal to some threshold rather than strictly less than the threshold. We can add a very small number (0.0001) to the threshold that doesn't affect adherence to the condition and allow us to use the new value in a strictly less than inequality.
To your initial model, you can add one new binary variable per seller (model.shipping_bin) and one constraint per binary variable that forces the binary variable to be 1 if the cost is less than the threshold and 0 otherwise. We can then multiply by the shipping cost in the objective function by these variables.
# add new binary variables to track costs per supplier
model.shipping_bin = Var(M,within = Binary)
shipping_costs = {'A':10,'B':8}
shipping_thresholds = {'A':100,'B':150} # threshold to meet to not incur shipping
# We need big M values to multiply the binaries to enforce the constraint without constraining the procurement cost incurred.
# We can set to the maximum amount we expect to procure from the seller
# The largest cost you could incur from each seller is
# the price times the max quantity
shipping_big_m = {seller: sum([p[(prod,seller)] * q_s[(prod,seller)] for prod in N])
for seller in M}
# add constraints
def shipping_bin_rule(model,seller):
# Sets shipping binary var to 1 if threshold not met
# Allows it to be 0 otherwise
# 790 * (model.shipping_bin['A']) >= 100.0001 + cost of products from seller 'A'
# if cost of products from 'A' < 100.0001 then binary variable = 1
# 710 * (model.shipping_bin['B']) >= 150.0001 + cost of products from seller 'B'
# if cost of products from 'B' < 150.0001 then binary variable = 1
epsilon = .0001 # to make sure case where cost == threshold is still accounted for
return(shipping_big_m[seller] * model.shipping_bin[seller] >= shipping_thresholds[seller] + epsilon - sum([p[(product,seller)] * model.x[product,seller]
for product in N]))
model.shipping_bin_con = Constraint(M,rule = shipping_bin_rule)
# new objective function adding the shipping cost
def obj_with_shipping_rule(model):
orig_cost = obj_rule(model) # call the original function, but can combine into one function if desired
# apply the shipping cost if cost of products is less than threshold (binary is 0)
shipping_cost = sum([shipping_costs[seller] * model.shipping_bin[seller]
for seller in M])
return(orig_cost + shipping_cost)
# deactivate the original objective to apply the new one
model.obj.deactivate()
model.obj_with_shipping = Objective(rule = obj_with_shipping_rule)
# solve the model with new obj
solver.solve(model)
model.x.pprint() # x values remain unchanged
# x : Size=6, Index=x_index
# Key : Lower : Value : Upper : Fixed : Stale : Domain
# ('prod1', 'A') : 0 : 2.0 : 10 : False : False : Reals
# ('prod1', 'B') : 0 : 1.0 : 10 : False : False : Reals
# ('prod2', 'A') : 0 : 1.0 : 10 : False : False : Reals
# ('prod2', 'B') : 0 : 1.0 : 10 : False : False : Reals
# ('prod3', 'A') : 0 : 1.0 : 10 : False : False : Reals
# ('prod3', 'B') : 0 : 1.0 : 10 : False : False : Reals
# cost from A = 2 * 10 + 1 * 9 + 1 * 50 = 79 < 100 so model.shipping_bin['A'] = 1
# cost from B = 1 * 16 + 1 * 20 + 1 * 35 = 71 < 150 so model.shipping_bin['B'] = 1
model.shipping_bin.pprint()
# shipping_bin : Size=2, Index=shipping_bin_index
# Key : Lower : Value : Upper : Fixed : Stale : Domain
# A : 0 : 1.0 : 1 : False : False : Binary
# B : 0 : 1.0 : 1 : False : False : Binary
value(model.obj_with_shipping) # 168 (18 units larger than original because of shipping)
Let's say I have a .CSV which has three columns: tidytext, location, vader_senti
I was already able to get the amount of *positive, neutral and negative text instead of word* pero country using the following code:
data_vis = pd.read_csv(r"csviamcrpreprocessed.csv", usecols=fields)
def print_sentiment_scores(text):
vadersenti = analyser.polarity_scores(str(text))
return pd.Series([vadersenti['pos'], vadersenti['neg'], vadersenti['neu'], vadersenti['compound']])
data_vis[['vadersenti_pos', 'vadersenti_neg', 'vadersenti_neu', 'vadersenti_compound']] = data_vis['tidytext'].apply(print_sentiment_scores)
data_vis['vader_senti'] = 'neutral'
data_vis.loc[data_vis['vadersenti_compound'] > 0.3 , 'vader_senti'] = 'positive'
data_vis.loc[data_vis['vadersenti_compound'] < 0.23 , 'vader_senti'] = 'negative'
data_vis['vader_possentiment'] = 0
data_vis.loc[data_vis['vadersenti_compound'] > 0.3 , 'vader_possentiment'] = 1
data_vis['vader_negsentiment'] = 0
data_vis.loc[data_vis['vadersenti_compound'] <0.23 , 'vader_negsentiment'] = 1
data_vis['vader_neusentiment'] = 0
data_vis.loc[(data_vis['vadersenti_compound'] <=0.3) & (data_vis['vadersenti_compound'] >=0.23) , 'vader_neusentiment'] = 1
sentimentbylocation = data_vis.groupby(["Location"])['vader_senti'].value_counts()
sentimentbylocation
sentimentbylocation gives me the following results:
Location vader_senti
Afghanistan negative 151
positive 25
neutral 2
Albania negative 6
positive 1
Algeria negative 116
positive 13
neutral 4
TO GET THE MOST COMMON POSITIVE WORDS, I USED THIS CODE:
def process_text(text):
tokens = []
for line in text:
toks = tokenizer.tokenize(line)
toks = [t.lower() for t in toks if t.lower() not in stopwords_list]
tokens.extend(toks)
return tokens
tokenizer=TweetTokenizer()
punct = list(string.punctuation)
stopwords_list = stopwords.words('english') + punct + ['rt','via','...','…','’','—','—:',"‚","â"]
pos_lines = list(data_vis[data_vis.vader_senti == 'positive'].tidytext)
pos_tokens = process_text(pos_lines)
pos_freq = nltk.FreqDist(pos_tokens)
pos_freq.most_common()
Running this will give me the most common words and the number of times they appeared, such as
[(good, 1212),
(amazing, 123)
However, what I want to see is how many of these positive words appeared in a country.
For example:
I have a sample CSV here: https://drive.google.com/file/d/112k-6VLB3UyljFFUbeo7KhulcrMedR-l/view?usp=sharing
Create a column for each most_common word, then do a groupby location and use agg to apply a sum for each count:
words = [i[0] for i in pos_freq.most_common()]
# lowering all cases in tidytext
data_vis.tidytext = data_vis.tidytext.str.lower()
for i in words:
data_vis[i] = data_vis.tidytext.str.count(i)
funs = {i: 'sum' for i in words}
grouped = data_vis.groupby('Location').agg(funs)
Based on the example from the CSV and using most_common as ['good', 'amazing'] the result would be:
grouped
# good amazing
# Location
# Australia 0 1
# Belgium 6 4
# Japan 2 1
# Thailand 2 0
# United States 1 0
Little description of task:
Need to get total of base if we will selling coin_quantity of coin to the market.
By default, this example means, that market is coin+"_"+base. No flip case.
For simplification, there is only one case(action): selling / ask.
python:
def get_depth_price( db_cursor, coin_quantity, coin, market ):
sql_command = "SELECT * FROM '" + market + "' WHERE type=1"
db_cursor.execute( sql_command )
bids = sorted([ i for i in db_cursor.fetchall() ], \
key = lambda k: k[3], reverse = True )
tmp_quantity = float( coin_quantity )
tmp_total = 0
for bid in bids:
if tmp_quantity > bid[4]:
tmp_total += bid[4] * bid[3]
tmp_quantity -= bid[4]
else:
tmp_total += tmp_quantity * bid[3]
tmp_quantity = 0
break
return tmp_total
Where market data looks like:
# echo "SELECT * from 'DOGE_BTC' WHERE type=1
ORDER BY price DESC;" | sqlite3 big.db
6f827564d88ddd0d99a9f976ac384a3f|0|1|5.0e-07|374365.08
1f696fea1270c07d9d4217e47ad40d3c|0|1|4.9e-07|1337443.42857
b9bee0a3bc2d4b241383062f06569b54|0|1|4.8e-07|465618.375
716cb29e0f5fe4742de73302e5b88250|0|1|4.7e-07|197560.659574
3189ed55c60530014892c6a3fce673e8|0|1|4.6e-07|115757.521739
cf19858241fb25de9095160b1704ef44|0|1|4.5e-07|237807.133333
f53642c0e7d5074daaa2b324e82483c5|0|1|4.4e-07|16112.6818182
ee8fb3f5255fb0ef8c157becb6a8c539|0|1|4.3e-07|22581.0697674
### (0)id ----^ (1)self---^ ^ ^-(3)price ^
### (2)type(ask=0/bid=1)-------+ (4)quantity--+
Methinks, that python script - is very very slow thing against sql.
However, I can't create similar on the sql language.
How to replace full function of get_depth_price by sql-query?
How to create on sql similar to if tmp_quantity > bid[4] / then / else ?
A large company pays its salespeople on a commission basis. The salespeople receive $200 per week plus 9% of their gross sales for that week. For example, a salesperson who sells $5000 worth of merchandise in a week receives $200 plus 9% of $5000, or a total of $650. Your program will allow the user to enter item numbers for each item sold by the salesperson for that week, print out the total of each item sold by the salesperson, and the total weekly earnings for that salesperson. The items and values are: Item 1 equals to 5.00, Item 2 equals to 10.00, Item 3 equals to 1.00, Item 4 equals to 25.00. Program should use JOptionPane for all input.
I have some programmed but I only get one input.
--- Update ---
//This is what I have so far
import javax.swing.JOptionPane;
public class KingRocker {
public static void main( String[]args )
{
double gross = 0.0, earnings;
int product = 0, number;
String input;
while( product < 4 ){
product++;
input = JOptionPane.showInputDialog("Enter the number of products sold #" + product + " ");
number = Integer.parseInt( input );
if (product == 1)
gross = gross + number * 5.00;
else if (product == 2)
gross = gross + number * 10.00;
else if (product == 3)
gross = gross + number * 1.00;
else if (product == 4)
gross = gross + number * 25.00;
earnings = 0.09 * gross + 200;
String result = "Week earnings: " + earnings;
JOptionPane.showMessageDialog(null, result, "Sales", JOptionPane.INFORMATION_MESSAGE );
System.exit( -1);
}
}
}
From what I can tell, you are calling System.exit( -1); before you run though the rest of your while loop. Try moving System.exit( -1); outside of the loop.
Try closing the loops here
if (product == 1)
gross = gross + number * 5.00;
else if (product == 2)
gross = gross + number * 10.00;
else if (product == 3)
gross = gross + number * 1.00;
else if (product == 4)
gross = gross + number * 25.00;
}
Doing so will allow the loop to run four times. Giving you what you ask for in the comments.