Skip to content

Commit

Permalink
BAH-3410 | Add. Custom Reports, API Payload Format Changed And Fix Mi…
Browse files Browse the repository at this point in the history
…nor Issues

* [Hari | BAH-3410 |Add. ]

* Revert "[Hari | BAH-3410 |Add. ]"

This reverts commit bd1639c.

* [ Hari,Karthi ] | BAH-3410 | Add. Custom Reports was added, API payload format changed and minor issues are fixed.

* [Karthi] | BAH-3410 | Refactor. Logs all undoed

* [Karthi] | BAH-3410 | Refactor. All the print statement has been removed

* [Karthi] | BAH-3410 | CLA Verfication

* [Karthi] | BAH-3410 | Refactor. Menus file position has been changed

* [Karthi] | BAH-3410 | Refactor. sudo access given to stock warehouse

---------

Co-authored-by: karthikeyan <[email protected]>
  • Loading branch information
Hari Prasath A and karthikeyansp91 authored Dec 15, 2023
1 parent 562c0ee commit a287b14
Show file tree
Hide file tree
Showing 30 changed files with 606 additions and 408 deletions.
2 changes: 2 additions & 0 deletions bahmni_account/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
'data': [
'views/account_invoice_view.xml',
'views/company_view.xml',
'views/account_report.xml',
'report/report_invoice_inherit.xml',
],
'demo': [],
'qweb': [],
Expand Down
126 changes: 24 additions & 102 deletions bahmni_account/models/account_invoice.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
from collections import defaultdict
from contextlib import ExitStack, contextmanager

from odoo import fields, models, api, _
from odoo.exceptions import UserError, ValidationError
import logging
_logger = logging.getLogger(__name__)
# mapping invoice type to refund type
TYPE2REFUND = {
'out_invoice': 'out_refund', # Customer Invoice
'in_invoice': 'in_refund', # Vendor Bill
'out_refund': 'out_invoice', # Customer Refund
'in_refund': 'in_invoice', # Vendor Refund
}


class AccountInvoice(models.Model):
_inherit = 'account.move'

order_id = fields.Many2one('sale.order',string="Sale ID")

discount_type = fields.Selection([('none', 'No Discount'),
('fixed', 'Fixed'),
('percentage', 'Percentage')],
Expand All @@ -22,9 +21,18 @@ class AccountInvoice(models.Model):
discount_percentage = fields.Float(string="Discount Percentage")
disc_acc_id = fields.Many2one('account.account',
string="Discount Account Head")
round_off_amount = fields.Monetary(string="Round Off Amount",
)
round_off_amount = fields.Monetary(string="Round Off Amount")

@contextmanager
def _check_balanced(self, container):
''' Assert the move is fully balanced debit = credit.
An error is raised if it's not the case.
'''
with self._disable_recursion(container, 'check_move_validity', default=True, target=False) as disabled:
yield
if disabled:
return
unbalanced_moves = self._get_unbalanced_moves(container)
@api.onchange('invoice_line_ids')
def onchange_invoice_lines(self):
amount_total = self.amount_untaxed + self.amount_tax
Expand All @@ -41,36 +49,7 @@ def onchange_discount(self):
if self.discount_percentage:
self.discount = amount_total * self.discount_percentage / 100

def _find_batch(self, product, qty, location, picking):
_logger.info("\n\n***** Product :%s, Quantity :%s Location :%s\n*****",product,qty,location)
lot_objs = self.env['stock.production.lot'].search([('product_id','=',product.id),('life_date','>=',str(fields.datetime.now()))])
_logger.info('\n *** Searched Lot Objects:%s \n',lot_objs)
if any(lot_objs):
#Sort losts based on the expiry date FEFO(First Expiry First Out)
lot_objs = list(lot_objs)
sorted_lot_list = sorted(lot_objs, key=lambda l: l.life_date)
_logger.info('\n *** Sorted based on FEFO :%s \n',sorted_lot_list)
done_qty = qty
res_lot_ids = []
lot_ids_for_query = tuple([lot.id for lot in sorted_lot_list])
self._cr.execute("SELECT SUM(qty) FROM stock_quant WHERE lot_id IN %s and location_id=%s",(lot_ids_for_query,location.id,))
qry_rslt = self._cr.fetchall()
available_qty = qry_rslt[0] and qry_rslt[0][0] or 0
if available_qty >= qty:
for lot_obj in sorted_lot_list:
quants = lot_obj.quant_ids.filtered(lambda q: q.location_id == location)
for quant in quants:
if done_qty >= 0:
res_lot_ids.append(lot_obj)
done_qty = done_qty - quant.qty
return res_lot_ids
else:
message = ("<b>Auto validation Failed</b> <br/> <b>Reason:</b> There are not enough stock available for <a href=# data-oe-model=product.product data-oe-id=%d>%s</a> product on <a href=# data-oe-model=stock.location data-oe-id=%d>%s</a> Location") % (product.id,product.name,location.id,location.name)
picking.message_post(body=message)
else:
message = ("<b>Auto validation Failed</b> <br/> <b>Reason:</b> There are no Batches/Serial no's available for <a href=# data-oe-model=product.product data-oe-id=%d>%s</a> product") % (product.id,product.name)
picking.message_post(body=message)
return False


def button_dummy(self):
return True
Expand All @@ -81,18 +60,14 @@ def button_dummy(self):
def action_post(self):

for inv in self:
print("inv",inv.discount,inv.round_off_amount,inv.amount_total)

find_val = (inv.amount_total - inv.discount ) + inv.round_off_amount

print("find_val",find_val)
differnece_vals = inv.amount_total - find_val
print("differnece_vals",differnece_vals)


for move_line in inv.line_ids:
update = False
print("move_line",move_line.display_type)
if move_line.display_type =='payment_term':
move_line.debit = move_line.debit - differnece_vals

Expand All @@ -106,63 +81,10 @@ def action_post(self):
other_moves._post(soft=False)
return False

class AccountPayment(models.Model):
_inherit = 'account.payment'

def invoice_seach(self):
""" Using ref find the invoice obj """
return self.env['account.move'].search([('name', '=', self.move_id.ref),('move_type', '=', 'out_invoice')], limit=1)


@api.model
def _prepare_refund(self, invoice, date_invoice=None, date=None, description=None, journal_id=None):
""" Prepare the dict of values to create the new refund from the invoice.
This method may be overridden to implement custom
refund generation (making sure to call super() to establish
a clean extension chain).
:param record invoice: invoice to refund
:param string date_invoice: refund creation date from the wizard
:param integer date: force date from the wizard
:param string description: description of the refund from the wizard
:param integer journal_id: account.journal from the wizard
:return: dict of value to create() the refund
"""
values = {}
for field in self._get_refund_copy_fields():
if invoice._fields[field].type == 'many2one':
values[field] = invoice[field].id
else:
values[field] = invoice[field] or False

values['invoice_line_ids'] = self._refund_cleanup_lines(invoice.invoice_line_ids)
tax_lines = invoice.tax_line_ids
taxes_to_change = {
line.tax_id.id: line.tax_id.refund_account_id.id
for line in tax_lines.filtered(lambda l: l.tax_id.refund_account_id != l.tax_id.account_id)
}
cleaned_tax_lines = self._refund_cleanup_lines(tax_lines)
values['tax_line_ids'] = self._refund_tax_lines_account_change(cleaned_tax_lines, taxes_to_change)

if journal_id:
journal = self.env['account.journal'].browse(journal_id)
elif invoice['type'] == 'in_invoice':
journal = self.env['account.journal'].search([('type', '=', 'purchase')], limit=1)
else:
journal = self.env['account.journal'].search([('type', '=', 'sale')], limit=1)
values['journal_id'] = journal.id

values['type'] = TYPE2REFUND[invoice['type']]
values['date_invoice'] = date_invoice or fields.Date.context_today(invoice)
values['state'] = 'draft'
values['number'] = False
values['origin'] = invoice.number
values['payment_term_id'] = False
values['refund_invoice_id'] = invoice.id
#=============Customized code starts========= Added Custom discount fields in refund
values['discount_type'] = invoice.discount_type
values['discount'] = invoice.discount
values['discount_percentage'] = invoice.discount_percentage
values['disc_acc_id'] = invoice.disc_acc_id.id
#===========Customized code ends=============

if date:
values['date'] = date
if description:
values['name'] = description
return values

36 changes: 0 additions & 36 deletions bahmni_account/models/account_invoice_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,39 +4,3 @@
class AccountInvoiceLine(models.Model):
_inherit = 'account.move.line'

@api.model
def create(self, vals):
'''This method is overridden to update discount amount in invoice,
when invoice is getting created from sale order, and discount type selected in sale order is percentage.
Since, discount amount in readonly field and it gets updated by onchange method, which won't get called when invoice is created from backend.'''
if vals.get('invoice_id'):
invoice_obj = self.env['account.move'].browse(vals.get('invoice_id'))
amount_untaxed = 0.0
amount_tax = 0.0
# calculating total from already created invoice lines.
for ln in invoice_obj.invoice_line_ids:
amount_untaxed += ln.price_subtotal
taxes = ln.invoice_line_tax_ids.compute_all(ln.price_subtotal, invoice_obj.currency_id,
ln.quantity, product=ln.product_id,
partner=invoice_obj.partner_shipping_id)
amount_tax += sum(t.get('amount', 0.0) for t in taxes.get('taxes', []))
if vals.get('invoice_line_tax_ids'):
price_unit = vals.get('price_unit') * vals.get('quantity')
if vals.get('discount'):
price_unit = price_unit * (1 - vals['discount']/100)
amount_untaxed += price_unit
tax_ids = []
if len(vals['invoice_line_tax_ids'][0]) == 3:
tax_ids = vals['invoice_line_tax_ids'][0][2]
elif len(vals['invoice_line_tax_ids'][0]) == 1:
tax_ids = vals['invoice_line_tax_ids'][0]
tax_obj = self.env['account.tax'].browse(tax_ids)
taxes = tax_obj.compute_all(price_unit, invoice_obj.currency_id,
vals.get('quantity'), product=vals.get('product_id'),
partner=invoice_obj.partner_id)
amount_tax += sum(t.get('amount', 0.0) for t in taxes.get('taxes', []))
if invoice_obj.discount_type == 'percentage':
discount_amount = (invoice_obj.currency_id.round(amount_untaxed) +
invoice_obj.currency_id.round(amount_tax)) * invoice_obj.discount_percentage / 100
invoice_obj.write({'discount': discount_amount})
return super(AccountInvoiceLine, self).create(vals)
39 changes: 39 additions & 0 deletions bahmni_account/report/onscreen_header_and_footer.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<t t-name="web.external_layout_standard">
<div t-attf-class="header o_company_#{company.id}_layout" t-att-style="report_header_style">
<div style="width: 55%;float: left;">
<address>
<p style="margin-bottom: -5px;padding: 1px;"><span t-field="company.company_details"/></p>
<p style="margin-bottom: 2px;">Phone : <span t-field="o.company_id.phone"/></p>
</address>
</div>
<div style="width: 25%;float: right;">
<img t-att-src="image_data_uri(o.company_id.logo)"/></div>
</div>

<div t-attf-class="article o_report_layout_standard o_company_#{company.id}_layout {{ 'o_report_layout_background' if company.layout_background in ['Geometric', 'Custom'] else '' }}" t-attf-style="background-image: url({{ 'data:image/png;base64,%s' % company.layout_background_image.decode('utf-8') if company.layout_background_image and company.layout_background == 'Custom' else '/base/static/img/bg_background_template.jpg' if company.layout_background == 'Geometric' else ''}});" t-att-data-oe-model="o and o._name" t-att-data-oe-id="o and o.id" t-att-data-oe-lang="o and o.env.context.get('lang')">
<div class="pt-5">
<!-- This div ensures that the address is not cropped by the header. -->
<t t-call="web.address_layout"/>
</div>
<t t-out="0"/>
</div>

<div t-attf-class="footer o_standard_footer o_company_#{company.id}_layout">
<div class="text-center" style="border-top: 1px solid black;">
<ul class="list-inline mb4">
<div style="width: 65%;float: right;">
<!--Page: <span class="page"/> of <span class="topage"/>-->
</div>
<div style="width: 35%;float: left;" t-if="report_type == 'pdf'">
<span t-field="user.name"/> - <span t-esc="context_timestamp(datetime.datetime.now()).strftime('%d/%m/%Y %H:%M:%S')"/>
</div>
</ul>
<div t-if="report_type == 'pdf'" style="width: 30%; float: left;">
Page: <span class="page"/> of <span class="topage"/>
</div>
<div t-if="report_type == 'pdf' and display_name_in_footer" class="text-muted">
<span t-field="o.name"/>
</div>
</div>
</div>
</t>
Loading

0 comments on commit a287b14

Please sign in to comment.