<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2015 RyePDX LLC
#    Copyright (C) 2011 NovaPoint Group LLC (<http://www.novapointgroup.com>)
#    Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>)
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>
#
##############################################################################

import datetime
from decimal import Decimal

import time
import decimal_precision as dp

from openerp.osv import osv, fields

class account_invoice(osv.osv):
    _inherit = "account.invoice"

    def _total_weight_net(self, cr, uid, ids, field_name, arg, context=None):
        """Compute the total net weight of the given Invoice."""
        result = {}
        for invoice in self.browse(cr, uid, ids, context=context):
            result[invoice.id] = 0.0
            for line in invoice.invoice_line:
                if line.product_id:
                    result[invoice.id] += line.weight_net or 0.0
        return result

    def _get_invoice(self, cr, uid, ids, context=None):
        """Get the invoice ids of the given Invoice Lines."""
        result = {}
        for line in self.pool.get('account.invoice.line').browse(cr, uid, ids, context=context):
            result[line.invoice_id.id] = True
        return result.keys()

    def _amount_shipment_tax(self, cr, uid, shipment_taxes, shipment_charge):
        val = 0.0
        for c in self.pool.get('account.tax').compute_all(cr, uid, shipment_taxes, shipment_charge, 1)['taxes']:
            val += c.get('amount', 0.0)
        return val

    def _amount_all(self, cr, uid, ids, name, args, context=None):
        res = super(account_invoice, self)._amount_all(cr, uid, ids, name, args, context=context)
        for invoice in self.browse(cr, uid, ids, context=context):
            if invoice.shipcharge:
                res[invoice.id]['amount_total'] = res[invoice.id]['amount_untaxed'] + res[invoice.id]['amount_tax'] + invoice.shipcharge
        return res

    def _get_invoice_tax(self, cr, uid, ids, context=None):
        invoice = self.pool.get('account.invoice')
        return super(account_invoice, invoice)._get_invoice_tax(cr, uid, ids, context=context)

    def _get_invoice_line(self, cr, uid, ids, context=None):
        invoice = self.pool.get('account.invoice')
        return super(account_invoice, invoice)._get_invoice_line(cr, uid, ids, context=context)

    def _get_invoice_from_line(self, cr, uid, ids, context=None):
        invoice = self.pool.get('account.invoice')
        return super(account_invoice, invoice)._get_invoice_from_line(cr, uid, ids, context=context)

    def finalize_invoice_move_lines(self, cr, uid, invoice, move_lines):
        """
        finalize_invoice_move_lines(cr, uid, invoice, move_lines) -> move_lines
        Hook method to be overridden in additional modules to verify and possibly alter the
        move lines to be created by an invoice, for special cases.
        Args:
            invoice: browsable record of the invoice that is generating the move lines
            move_lines: list of dictionaries with the account.move.lines (as for create())
        Returns:
            The (possibly updated) final move_lines to create for this invoice
        """
        move_lines = super(account_invoice, self).finalize_invoice_move_lines(cr, uid, invoice, move_lines)
        if invoice.type == "out_refund":
            account = invoice.account_id.id
        else:
            account = invoice.sale_account_id.id
        if invoice.type in ('out_invoice','out_refund')  and account and invoice.shipcharge:
            lines1 = {
                'analytic_account_id': False,
                'tax_code_id': False,
                'analytic_lines': [],
                'tax_amount': False,
                'name': 'Shipping Charge',
                'ref': '',
                'currency_id': False,
                'credit': invoice.shipcharge,
                'product_id': False,
                'date_maturity': False,
                'debit': False,
                'date': time.strftime("%Y-%m-%d"),
                'amount_currency': 0,
                'product_uom_id':  False,
                'quantity': 1,
                'partner_id': invoice.partner_id.id,
                'account_id': account
            }
            move_lines.append((0, 0, lines1))
            has_entry = False
            for move_line in move_lines:
                journal_entry = move_line[2]
                if journal_entry['account_id'] == invoice.partner_id.property_account_receivable.id:
                    journal_entry['debit'] += invoice.shipcharge
                    has_entry = True
                    break
            if not has_entry:       # If debit line does not exist create one
                lines2 = {
                    'analytic_account_id': False,
                    'tax_code_id': False,
                    'analytic_lines': [],
                    'tax_amount': False,
                    'name': '/',
                    'ref': '',
                    'currency_id': False,
                    'credit': False,
                    'product_id': False,
                    'date_maturity': False,
                    'debit': invoice.shipcharge,
                    'date': time.strftime("%Y-%m-%d"),
                    'amount_currency': 0,
                    'product_uom_id': False,
                    'quantity': 1,
                    'partner_id': invoice.partner_id.id,
                    'account_id': invoice.partner_id.property_account_receivable.id
                }
                move_lines.append((0, 0, lines2))
        return move_lines


    def _get_invoice_ship_methods(self, cr, uid, ids, field_name, args, context=None):
        methods = {}
        todays_ratecards = self._get_todays_ratecards(cr, uid, context=context)

        for invoice_obj in self.browse(cr, uid, ids):
            methods[invoice_obj.id] = [m.id for m in self._get_ship_methods(
                cr, uid, invoice_obj.recipient_country_id.id, invoice_obj.amount_total,
                ratecards=todays_ratecards, context=context
            )]

        return methods

    def _get_todays_ratecards(self, cr, uid, context=None):
        table_pool = self.pool.get('shipping.rate.card')
        today = datetime.date.today().strftime("%Y-%m-%d")

        return table_pool.browse(cr, uid, table_pool.search(
            cr, uid, ['|', ('from_date', '<=', today), ('from_date', '=', None),
                      '|', ('to_date', '>', today), ('to_date', '=', None)], context=context
        ), context=context)

    _columns = {
        'shipcharge': fields.float('Shipping Cost', required=True),
        'ship_method_id': fields.many2one('shipping.rate', 'Shipping Method',
                                          domain="[('id', 'in', valid_shipping_methods[0][2])]",
                                          context="{'group_by':'name', 'order':'country_id, to_price'}"
        ),
        'valid_shipping_methods': fields.function(_get_invoice_ship_methods, type="many2many", relation="shipping.rate"),<commit_msg>Fix _get_ship_methods not found error in account_invoice.<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2015 RyePDX LLC
#    Copyright (C) 2011 NovaPoint Group LLC (<http://www.novapointgroup.com>)
#    Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>)
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>
#
##############################################################################

import datetime
from decimal import Decimal

import time
import decimal_precision as dp

from openerp.osv import osv, fields

class account_invoice(osv.osv):
    _inherit = "account.invoice"

    def _total_weight_net(self, cr, uid, ids, field_name, arg, context=None):
        """Compute the total net weight of the given Invoice."""
        result = {}
        for invoice in self.browse(cr, uid, ids, context=context):
            result[invoice.id] = 0.0
            for line in invoice.invoice_line:
                if line.product_id:
                    result[invoice.id] += line.weight_net or 0.0
        return result

    def _get_invoice(self, cr, uid, ids, context=None):
        """Get the invoice ids of the given Invoice Lines."""
        result = {}
        for line in self.pool.get('account.invoice.line').browse(cr, uid, ids, context=context):
            result[line.invoice_id.id] = True
        return result.keys()

    def _amount_shipment_tax(self, cr, uid, shipment_taxes, shipment_charge):
        val = 0.0
        for c in self.pool.get('account.tax').compute_all(cr, uid, shipment_taxes, shipment_charge, 1)['taxes']:
            val += c.get('amount', 0.0)
        return val

    def _amount_all(self, cr, uid, ids, name, args, context=None):
        res = super(account_invoice, self)._amount_all(cr, uid, ids, name, args, context=context)
        for invoice in self.browse(cr, uid, ids, context=context):
            if invoice.shipcharge:
                res[invoice.id]['amount_total'] = res[invoice.id]['amount_untaxed'] + res[invoice.id]['amount_tax'] + invoice.shipcharge
        return res

    def _get_invoice_tax(self, cr, uid, ids, context=None):
        invoice = self.pool.get('account.invoice')
        return super(account_invoice, invoice)._get_invoice_tax(cr, uid, ids, context=context)

    def _get_invoice_line(self, cr, uid, ids, context=None):
        invoice = self.pool.get('account.invoice')
        return super(account_invoice, invoice)._get_invoice_line(cr, uid, ids, context=context)

    def _get_invoice_from_line(self, cr, uid, ids, context=None):
        invoice = self.pool.get('account.invoice')
        return super(account_invoice, invoice)._get_invoice_from_line(cr, uid, ids, context=context)

    def finalize_invoice_move_lines(self, cr, uid, invoice, move_lines):
        """
        finalize_invoice_move_lines(cr, uid, invoice, move_lines) -> move_lines
        Hook method to be overridden in additional modules to verify and possibly alter the
        move lines to be created by an invoice, for special cases.
        Args:
            invoice: browsable record of the invoice that is generating the move lines
            move_lines: list of dictionaries with the account.move.lines (as for create())
        Returns:
            The (possibly updated) final move_lines to create for this invoice
        """
        move_lines = super(account_invoice, self).finalize_invoice_move_lines(cr, uid, invoice, move_lines)
        if invoice.type == "out_refund":
            account = invoice.account_id.id
        else:
            account = invoice.sale_account_id.id
        if invoice.type in ('out_invoice','out_refund')  and account and invoice.shipcharge:
            lines1 = {
                'analytic_account_id': False,
                'tax_code_id': False,
                'analytic_lines': [],
                'tax_amount': False,
                'name': 'Shipping Charge',
                'ref': '',
                'currency_id': False,
                'credit': invoice.shipcharge,
                'product_id': False,
                'date_maturity': False,
                'debit': False,
                'date': time.strftime("%Y-%m-%d"),
                'amount_currency': 0,
                'product_uom_id':  False,
                'quantity': 1,
                'partner_id': invoice.partner_id.id,
                'account_id': account
            }
            move_lines.append((0, 0, lines1))
            has_entry = False
            for move_line in move_lines:
                journal_entry = move_line[2]
                if journal_entry['account_id'] == invoice.partner_id.property_account_receivable.id:
                    journal_entry['debit'] += invoice.shipcharge
                    has_entry = True
                    break
            if not has_entry:       # If debit line does not exist create one
                lines2 = {
                    'analytic_account_id': False,
                    'tax_code_id': False,
                    'analytic_lines': [],
                    'tax_amount': False,
                    'name': '/',
                    'ref': '',
                    'currency_id': False,
                    'credit': False,
                    'product_id': False,
                    'date_maturity': False,
                    'debit': invoice.shipcharge,
                    'date': time.strftime("%Y-%m-%d"),
                    'amount_currency': 0,
                    'product_uom_id': False,
                    'quantity': 1,
                    'partner_id': invoice.partner_id.id,
                    'account_id': invoice.partner_id.property_account_receivable.id
                }
                move_lines.append((0, 0, lines2))
        return move_lines


    def _get_invoice_ship_methods(self, cr, uid, ids, field_name, args, context=None):
        methods = {}
        todays_ratecards = self._get_todays_ratecards(cr, uid, context=context)
        sale_pool = self.pool.get("sale.order")

        for invoice_obj in self.browse(cr, uid, ids):
            methods[invoice_obj.id] = [m.id for m in sale_pool._get_ship_methods(
                cr, uid, invoice_obj.recipient_country_id.id, invoice_obj.amount_total,
                ratecards=todays_ratecards, context=context
            )]

        return methods

    def _get_todays_ratecards(self, cr, uid, context=None):
        table_pool = self.pool.get('shipping.rate.card')
        today = datetime.date.today().strftime("%Y-%m-%d")

        return table_pool.browse(cr, uid, table_pool.search(
            cr, uid, ['|', ('from_date', '<=', today), ('from_date', '=', None),
                      '|', ('to_date', '>', today), ('to_date', '=', None)], context=context
        ), context=context)

    _columns = {
        'shipcharge': fields.float('Shipping Cost', required=True),
        'ship_method_id': fields.many2one('shipping.rate', 'Shipping Method',
                                          domain="[('id', 'in', valid_shipping_methods[0][2])]",
                                          context="{'group_by':'name', 'order':'country_id, to_price'}"
        ),
        'valid_shipping_methods': fields.function(_get_invoice_ship_methods, type="many2many", relation="shipping.rate"),
{'fraction_non_alphanumeric': 0.1283250142162128, 'fraction_numerical': 0.005560118784355848, 'mean_word_length': 2.2461033634126335, 'pattern_counts': {'":': 2, '<': 11, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5350898', 'n_tokens_mistral': 4710, 'n_tokens_neox': 4374, 'n_words': 1159}