<commit_before># -*- coding: utf-8 -*-
###############################################################################
#
#    Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
import os
import sys
import base64
import xlrd
import logging
import openerp
import openerp.netsvc as netsvc
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv, expression, orm
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from openerp import SUPERUSER_ID, api
from openerp import tools
from openerp.tools.translate import _
from openerp.tools.float_utils import float_round as round
from openerp.tools import (DEFAULT_SERVER_DATE_FORMAT,
    DEFAULT_SERVER_DATETIME_FORMAT,
    DATETIME_FORMATS_MAP,
    float_compare)

_logger = logging.getLogger(__name__)


class SaleOrderDelivery(orm.Model):
    """ Model name: SaleOrderDelivery
    """
    _name = 'sale.order.delivery'
    _description = 'Sale order delivery'
    _order = 'create_date desc'

    def import_load_delivery_file(self, cr, uid, ids, context=None):
        """ Import file and create order delivery
        """
        # Pool used:
        order_pool = self.pool.get('sale.order')
        line_pool = self.pool.get('sale.order.line')
        delivery_id = ids[0]

        delivery = self.browse(cr, uid, delivery_id, context=context)
        if delivery.order_ids:
            raise osv.except_osv(
                _('Errore'),
                _(u'Questa consegna ha già dei documenti collegati, partire da'
                  u' una vuota!'),
                )
        if not delivery.file:
            raise osv.except_osv(
                _('Errore'),
                _(u'Caricare prima il file qui a sinistra!'),
                )

        # Load and save Excel file:
        b64_file = base64.decodestring(delivery.file)
        now = datetime.now().strftime(DEFAULT_SERVER_DATETIME_FORMAT)
        filename = '/tmp/delivery_%s.xlsx' % now.replace(
            ':', '_').replace('-', '_')
        f = open(filename, 'wb')
        f.write(b64_file)
        f.close()

        # ---------------------------------------------------------------------
        # Load force name (for web publish)
        # ---------------------------------------------------------------------
        try:
            wb = xlrd.open_workbook(filename)
        except:
            raise osv.except_osv(
                _('Error XLSX'),
                _('Cannot read XLS file: %s' % filename),
                )

        # ---------------------------------------------------------------------
        # Read Excel file
        # ---------------------------------------------------------------------
        ws = wb.sheet_by_index(0)
        _logger.warning('Read first page')

        linked_ids = []
        partner_id = False
        start = False
        result = {
            'error': '',
            'warning': '',
            'info': '',
        }

        for row in range(ws.nrows):
            human_row = row + 1
            # Check if start:
            if not start:
                if ws.cell(row, 0).value == 'START':
                    start = True
                    for col in range(ws.ncols):
                        if ws.cell(row, col).value == 'QUANTITY':
                            quantity_col = col
                            break
                    if not quantity_col:
                        raise osv.except_osv(
                            _('Errore'),
                            _(u'Colonna scarico merce non trovata!'),
                        )
                continue

            # Read data:
            line_id = int(ws.cell(row, 0).value)
            quantity = int(ws.cell(row, quantity_col).value)

            # -----------------------------------------------------------------
            # Check data:
            # -----------------------------------------------------------------
            # a. Quantity positive:
            if not quantity:
                result['info'] += u'%s. Riga senza quantità' % human_row
                continue
            if quantity < 0:
                result['info'] += u'%s. Riga con q. negativa!' % human_row
                continue

            # b. ID row not found:
            try:
                line = line_pool.browse(cr, uid, line_id, context=context)
            except:
                result['error'] += '%s. ID riga non trovato!' % (row + 1)
                raise osv.except_osv(
                    _('Errore'),
                    _(u'ID riga non trovata!'),
                )

            # c. Check available:
            available = (line.product_uom_maked_sync_qty + line.mx_assigned_qty
                         - line.delivered_qty)
            if quantity > available:
                if available:
                    result['warning'] += \
                        '%s. Q. %s > %s (disponibile) preso la disponibile' % (
                            human_row, quantity, available)
                    quantity = available
                else:
                    result['error'] += u'%s. Nulla da consegnare!'
                    quantity = 0

            # d. Check partner
            order_partner_id = line.order_id.partner_id.id
            if partner_id:
                if partner_id != order_partner_id:
                    raise osv.except_osv(
                        _('Error XLSX'),
                        _('Partner differenti negli ordini collegati!'),
                    )<commit_msg>generic bugfix (fast message)<commit_after># -*- coding: utf-8 -*-
###############################################################################
#
#    Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
import os
import sys
import base64
import xlrd
import logging
import openerp
import openerp.netsvc as netsvc
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv, expression, orm
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from openerp import SUPERUSER_ID, api
from openerp import tools
from openerp.tools.translate import _
from openerp.tools.float_utils import float_round as round
from openerp.tools import (DEFAULT_SERVER_DATE_FORMAT,
    DEFAULT_SERVER_DATETIME_FORMAT,
    DATETIME_FORMATS_MAP,
    float_compare)

_logger = logging.getLogger(__name__)


class SaleOrderDelivery(orm.Model):
    """ Model name: SaleOrderDelivery
    """
    _name = 'sale.order.delivery'
    _description = 'Sale order delivery'
    _order = 'create_date desc'

    def import_load_delivery_file(self, cr, uid, ids, context=None):
        """ Import file and create order delivery
        """
        # Pool used:
        order_pool = self.pool.get('sale.order')
        line_pool = self.pool.get('sale.order.line')
        delivery_id = ids[0]

        delivery = self.browse(cr, uid, delivery_id, context=context)
        if delivery.order_ids:
            raise osv.except_osv(
                _('Errore'),
                _(u'Questa consegna ha già dei documenti collegati, partire da'
                  u' una vuota!'),
                )
        if not delivery.file:
            raise osv.except_osv(
                _('Errore'),
                _(u'Caricare prima il file qui a sinistra!'),
                )

        # Load and save Excel file:
        b64_file = base64.decodestring(delivery.file)
        now = datetime.now().strftime(DEFAULT_SERVER_DATETIME_FORMAT)
        filename = '/tmp/delivery_%s.xlsx' % now.replace(
            ':', '_').replace('-', '_')
        f = open(filename, 'wb')
        f.write(b64_file)
        f.close()

        # ---------------------------------------------------------------------
        # Load force name (for web publish)
        # ---------------------------------------------------------------------
        try:
            wb = xlrd.open_workbook(filename)
        except:
            raise osv.except_osv(
                _('Error XLSX'),
                _('Cannot read XLS file: %s' % filename),
                )

        # ---------------------------------------------------------------------
        # Read Excel file
        # ---------------------------------------------------------------------
        ws = wb.sheet_by_index(0)
        _logger.warning('Read first page')

        linked_ids = []
        partner_id = False
        start = False
        result = {
            'error': '',
            'warning': '',
            'info': '',
        }

        for row in range(ws.nrows):
            human_row = row + 1
            # Check if start:
            if not start:
                if ws.cell(row, 0).value == 'START':
                    start = True
                    for col in range(ws.ncols):
                        if ws.cell(row, col).value == 'QUANTITY':
                            quantity_col = col
                            break
                    if not quantity_col:
                        raise osv.except_osv(
                            _('Errore'),
                            _(u'Colonna scarico merce non trovata!'),
                        )
                continue

            # Read data:
            line_id = int(ws.cell(row, 0).value)
            quantity = int(ws.cell(row, quantity_col).value)

            # -----------------------------------------------------------------
            # Check data:
            # -----------------------------------------------------------------
            # a. Quantity positive:
            if not quantity:
                result['info'] += u'%s. Riga senza quantità' % human_row
                continue
            if quantity < 0:
                result['info'] += u'%s. Riga con q. negativa!' % human_row
                continue

            # b. ID row not found:
            try:
                line = line_pool.browse(cr, uid, line_id, context=context)
            except:
                result['error'] += '%s. ID riga non trovato!' % (row + 1)
                raise osv.except_osv(
                    _('Errore'),
                    _(u'ID riga non trovata!'),
                )

            # c. Check available:
            try:
                mrp_qty = line.product_uom_maked_sync_qty
            except:
                mrp_qty = 0
            available = (mrp_qty + line.mx_assigned_qty
                         - line.delivered_qty)
            if quantity > available:
                if available:
                    result['warning'] += \
                        '%s. Q. %s > %s (disponibile) preso la disponibile' % (
                            human_row, quantity, available)
                    quantity = available
                else:
                    result['error'] += u'%s. Nulla da consegnare!'
                    quantity = 0

            # d. Check partner
            order_partner_id = line.order_id.partner_id.id
            if partner_id:
                if partner_id != order_partner_id:
                    raise osv.except_osv(
                        _('Error XLSX'),
                        _('Partner differenti negli ordini collegati!'),
                    )
{'fraction_non_alphanumeric': 0.17144653099709278, 'fraction_numerical': 0.004164374950891805, 'mean_word_length': 1.363163757890828, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1755286', 'n_tokens_mistral': 3406, 'n_tokens_neox': 3196, 'n_words': 919}