Confirm Sale and skip Payment - net_amount is getting added to prev_outstanding_balance - odoo

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.

Related

Generic function to unwind portfolio

I have following sample portfolio p of positions (signed_qty) acquired daily:
p:([]date:(2013.07.01+1000#til 200);bb_code:((200#`TSLA),(200#`MSFT),(200#`GOOG),(200#`GS),(200#`AAPL));fill_px:1000?10e; signed_qty:(1000?(-1, 1)) * 1000?10000);
I want to estimate daily trades and position for different unwind strategies. Some of the different strategies that I want to back-test are as follows:
Hold for 2 days and then trade out in next 3 days. (n=2, m=3)
Hold for 1 day and then trade out in next 4 days. (n=1, m=4)
Trade evenly in next 4 days. (n=0, m=4)
... so on.
Below is the verbose code to do so for n=3, m=4. Can someone suggest a more elegant and generic way to get output for various n and m.?
/Adding prev_bb_code column to facilitate computation
p:update prev_bb_code: prev bb_code from p;
/No trading t+1.
p:update qty:prev signed_qty from p;
p:update signed_qty_p1:qty from p where bb_code = prev_bb_code;
p:update traded_qty_p1:(signed_qty_p1 - qty) from p;
/No trading t+2.
p:update qty:prev signed_qty_p1 from p;
p:update signed_qty_p2:qty from p where bb_code = prev_bb_code;
p:update traded_qty_p2:(signed_qty_p2 - qty) from p;
/1st trade (=1/4th position acquired on t) generated on t+3 with carry forward position = 3/4.
p:update qty:prev signed_qty_p2 from p;
p:update signed_qty_p3:"f"${$[x<0; ceiling((3%4.0)*x); floor((3%4.0)*x)]} each qty from p where bb_code = prev_bb_code;
p:update traded_qty_p3:(signed_qty_p3 - qty) from p;
/2nd trade (=1/4th position acquired on t) generated on t+4 with carry forward position = 2/4.
p:update qty:prev qty, prev_qty:prev signed_qty_p3 from p;
p:update signed_qty_p4:"f"${$[y=0n;0n;$[x<0; max((ceiling((2%4.0)*x)),y); min((floor((2%4.0)*x)),y)]]}'[qty; prev_qty] from p where bb_code=prev_bb_code;
p:update traded_qty_p4:(signed_qty_p4 - prev_qty) from p;
/3rd trade (=1/4th position acquired on t) generated on t+5 with carry forward position = 1/4.
p:update qty:prev qty, prev_qty:prev signed_qty_p4 from p;
p:update signed_qty_p5:"f"${$[y=0n;0n;$[x<0; max((ceiling((1%4.0)*x)),y); min((floor((1%4.0)*x)),y)]]}'[qty; prev_qty] from p where bb_code=prev_bb_code;
p:update traded_qty_p5:(signed_qty_p5 - prev_qty) from p;
/4th trade (=1/4th position acquired on t) generated on t+6 with carry forward position = 0. This abso
p:update qty:prev qty, prev_qty:prev signed_qty_p5 from p;
p:update signed_qty_p6:"f"${$[y=0n;0n;$[x<0; max((ceiling((0%4.0)*x)),y); min((floor((0%4.0)*x)),y)]]}'[qty; prev_qty] from p where bb_code=prev_bb_code;
p:update traded_qty_p6:(signed_qty_p6 - prev_qty) from p;
/Aggregate trades and positions.
p:update unwind_qty:((0^traded_qty_p1) + (0^traded_qty_p2) + (0^traded_qty_p3) + (0^traded_qty_p4) + (0^traded_qty_p5) + (0^traded_qty_p6)) from p;
p:update net_position:((0^signed_qty) + (0^signed_qty_p1) + (0^signed_qty_p2) + (0^signed_qty_p3) + (0^signed_qty_p4) + (0^signed_qty_p5) + (0^signed_qty_p6)) from p;
/ Finally only retain the columns of interest.
p: select date, bb_code, fill_px, signed_qty, unwind_qty, net_position from p;
This can be achieved with xprev and functional form.
https://code.kx.com/q/ref/next/#xprev
https://code.kx.com/q/basics/funsql/
Edit: This can actually be achieved without functional form:
g:{[n;m;x] sums[x]+sums sum each neg (flip xprev[;x] each n + til m)%m}
update net_position:g[3;4;signed_qty] by bb_code from t
Original Answer:
f:{[t;n;m]
//[table;where;by;cols]
![t;();(enlist `bb_code)!(enlist `bb_code);
(enlist `net_position)!enlist
// cumulative position change
(+;(sums;`signed_qty);
// cumulative unwind position change
// neg to invert the sign to unwind in opposite direction to original position
(sums;(each;sum;(neg;
// this part dynamically builds the number of xprev's required
// n being the start / hold period
// m for the number of unwind periods
(%;(flip;(enlist),(xprev),/:(n + til m),'`signed_qty);m)))))]
}
// No Comments
f:{[t;n;m]
![t;();(enlist `bb_code)!(enlist `bb_code);(enlist `net_position)!enlist (+;(sums;`signed_qty);(sums;(each;sum;(neg;(%;(flip;(enlist),(xprev),/:(n + til m),'`signed_qty);m)))))]
};
q)f[p;3;4]
date bb_code fill_px signed_qty net_position
-----------------------------------------------------
2013.07.01 TSLA 4.695818 8159 8159
2013.07.02 TSLA 0.747672 2203 10362
2013.07.03 TSLA 8.014479 -566 9796
2013.07.04 TSLA 3.805866 -831 8965
2013.07.05 TSLA 2.884907 -7792 -866.75
2013.07.06 TSLA 1.303814 9188 5730.75
2013.07.07 TSLA 8.517136 2267 5548.75
2013.07.08 TSLA 5.645172 5352 8659.5
2013.07.09 TSLA 0.04426234 7867 18273

Need to know what is the table that contains the Qty On Hand in Odoo

I need to build a report collect the QtyOnHand in the store groped based on Vendor => Shipment
I am trying to build sql query
this code is not working:
CREATE or REPLACE VIEW purchase_custom_report as (
WITH currency_rate as (
SELECT
r.currency_id,
COALESCE(r.company_id, c.id) as company_id,
r.rate,
r.name AS date_start,
(SELECT name FROM res_currency_rate r2
WHERE r2.name > r.name AND
r2.currency_id = r.currency_id AND
(r2.company_id is null or r2.company_id = c.id)
ORDER BY r2.name ASC
LIMIT 1) AS date_end
FROM res_currency_rate r
JOIN res_company c ON (r.company_id is null or r.company_id = c.id)
)
SELECT
min(l.id) as id,
s.date_order as date_order,
s.partner_id as partner_id,
s.user_id as user_id,
s.company_id as company_id,
t.list_price as std_price,
l.product_id,
p.temp_qty as available_in_store,
p.product_tmpl_id,
t.categ_id as category_id,
s.currency_id,
case when invoice_status='invoiced' then True else False end as po_paid_flag,
t.uom_id as product_uom,
t.standard_price as cost,
l.price_subtotal/l.product_qty as real_price,
l.price_subtotal/l.product_qty - t.standard_price as profit_val,
s.date_order as purchase_id_date,
-- ((l.price_subtotal/COALESCE(NULLIF(l.product_qty, 0), 1.0)) - t.standard_price) * 100/ COALESCE(NULLIF(t.standard_price, 0), 1.0) as profit_percentage,
p.temp_qty * t.standard_price as stock_value,
sum(l.product_qty/u.factor*u2.factor) as unit_quantity,
sum(l.price_unit / COALESCE(NULLIF(cr.rate, 0), 1.0) * l.product_qty)::decimal(16,2) as price_total,
(sum(l.product_qty * l.price_unit / COALESCE(NULLIF(cr.rate, 0), 1.0))/NULLIF(sum(l.product_qty/u.factor*u2.factor),0.0))::decimal(16,2) as price_average
FROM (
purchase_order_line l
join purchase_order s on (l.order_id=s.id)
join res_partner partner on s.partner_id = partner.id
left join product_product p on (l.product_id=p.id)
left join product_template t on (p.product_tmpl_id=t.id)
LEFT JOIN ir_property ip ON (ip.name='standard_price' AND ip.res_id=CONCAT('product.product,',p.id) AND ip.company_id=s.company_id)
left join uom_uom u on (u.id=l.product_uom)
left join uom_uom u2 on (u2.id=t.uom_id)
left join stock_quant sq on (sq.product_id = p.id)
left join currency_rate cr on (cr.currency_id = s.currency_id and
cr.company_id = s.company_id and
cr.date_start <= coalesce(s.date_order, now()) and
(cr.date_end is null or cr.date_end > coalesce(s.date_order, now())))
)
GROUP BY
s.company_id,
s.user_id,
s.partner_id,
s.currency_id,
l.price_unit,
l.price_subtotal,
l.date_planned,
l.product_uom,
l.product_id,
p.product_tmpl_id,
t.categ_id,
s.date_order,
u.uom_type,
u.category_id,
t.uom_id,
u.id,
t.list_price,
p.temp_qty,
t.standard_price,
l.product_qty,
s.invoice_status,
s.date_order
)
What I am expecting to have is the table & field name and I will do the rest
It's nowhere on the database as it is a computed field.
See <path_to_v12>/addons/stock/models/product.py
21 class Product(models.Model):
22 _inherit = "product.product"
...
26 qty_available = fields.Float(
27 'Quantity On Hand', compute='_compute_quantities', search='_search_qty_available',
28 digits=dp.get_precision('Product Unit of Measure'),
29 help="Current quantity of products.\n"
30 "In a context with a single Stock Location, this includes "
31 "goods stored at this Location, or any of its children.\n"
32 "In a context with a single Warehouse, this includes "
33 "goods stored in the Stock Location of this Warehouse, or any "
34 "of its children.\n"
35 "stored in the Stock Location of the Warehouse of this Shop, "
36 "or any of its children.\n"
37 "Otherwise, this includes goods stored in any Stock Location "
38 "with 'internal' type.")
...
489 def _compute_quantities(self):
490 res = self._compute_quantities_dict()
491 for template in self:
492 template.qty_available = res[template.id]['qty_available']
493 template.virtual_available = res[template.id]['virtual_available']
494 template.incoming_qty = res[template.id]['incoming_qty']
495 template.outgoing_qty = res[template.id]['outgoing_qty']
496
497 def _product_available(self, name, arg):
498 return self._compute_quantities_dict()
499
500 def _compute_quantities_dict(self):
501 # TDE FIXME: why not using directly the function fields ?
502 variants_available = self.mapped('product_variant_ids')._product_available()
503 prod_available = {}
504 for template in self:
505 qty_available = 0
506 virtual_available = 0
507 incoming_qty = 0
508 outgoing_qty = 0
509 for p in template.product_variant_ids:
510 qty_available += variants_available[p.id]["qty_available"]
511 virtual_available += variants_available[p.id]["virtual_available"]
512 incoming_qty += variants_available[p.id]["incoming_qty"]
513 outgoing_qty += variants_available[p.id]["outgoing_qty"]
514 prod_available[template.id] = {
515 "qty_available": qty_available,
516 "virtual_available": virtual_available,
517 "incoming_qty": incoming_qty,
518 "outgoing_qty": outgoing_qty,
519 }
520 return prod_available

Show different taxes as columns in Invoices Tree View in OpenERP/Odoo

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()

SQL: computation of depth inside stock's glass

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 ?

I am stuck on my programming project

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.