Exemplo n.º 1
0
 def unlink(self):
     for log in self:
         if log.state != 'draft':
             raise Warning(
                 _("Only log objects in state 'draft' can be deleted !"))
     return super(AccountCodaBatchLog, self).unlink()
Exemplo n.º 2
0
 def _onchange_ics_file_name(self):
     if self.ics_file_name:
         if not re.match(r'.*\.ics$', self.ics_file_name):
             raise Warning("Please select *.ics file")
Exemplo n.º 3
0
 def _check_seats_limit(self):
     if self.seats_max and self.seats_available < 0:
         raise Warning(_('No more available seats.'))
Exemplo n.º 4
0
 def get_state(self):
     self.get_connection()
     raise Warning(_('Not implemented yet!'))
Exemplo n.º 5
0
 def _check_cpf(self):
     if self.cpf:
         if not validate_cpf(self.cpf):
             raise Warning((u'CPF inválido!'))
     return True
Exemplo n.º 6
0
    def mercadopago_form_generate_values(self, partner_values, tx_values):
        self.ensure_one()
        base_url = self.env['ir.config_parameter'].get_param('web.base.url')
        if (not self.mercadopago_client_id or not self.mercadopago_secret_key):
            raise ValidationError(
                _('YOU MUST COMPLETE acquirer.mercadopago_client_id and '
                  'acquirer.mercadopago_secret_key'))
        if tx_values.get('return_url'):
            success_url = MercadoPagoController._success_url
            failure_url = MercadoPagoController._failure_url
            pending_url = MercadoPagoController._pending_url
        else:
            success_url = MercadoPagoController._success_no_return_url
            failure_url = MercadoPagoController._pending_no_return_url
            pending_url = MercadoPagoController._pending_url

        # TODO, implement, not implemented yet because mercadopago only
        # shows description of first line and we would need to send taxes too
        # sale_order = self.env['sale.order'].search(
        #     [('name', '=', tx_values["reference"])], limit=1)
        # if self.mercadopago_description == 'so_lines' and sale_order:
        #     items = [{
        #         "title": line.name,
        #         "quantity": line.product_uom_qty,
        #         "currency_id": (
        #             tx_values['currency'] and
        #             tx_values['currency'].name or ''),
        #         "unit_price": line.price_unit,
        #     } for line in sale_order.order_line]
        # else:
        if (not self.mercadopago_item_title
                or "%s" not in self.mercadopago_item_title):
            raise Warning(
                _('No generic message defined for mercadopago or message '
                  'does not contains %/s!'))
        items = [{
            "title":
            self.mercadopago_item_title % (tx_values["reference"]),
            # "title": _("Orden Ecommerce %s") % tx_values["reference"],
            "quantity":
            1,
            "currency_id":
            (tx_values['currency'] and tx_values['currency'].name or ''),
            "unit_price":
            tx_values["amount"],
        }]

        preference = {
            "items": items,
            "payer": {
                "name": partner_values["first_name"],
                "surname": partner_values["last_name"],
                "email": partner_values["email"],
            },
            "back_urls": {
                "success": '%s' % urlparse.urljoin(base_url, success_url),
                "failure": '%s' % urlparse.urljoin(base_url, failure_url),
                "pending": '%s' % urlparse.urljoin(base_url, pending_url)
            },
            # "notification_url": '%s' % urlparse.urljoin(
            #     base_url, MercadoPagoController._notify_url),
            "auto_return": "approved",
            "external_reference": tx_values["reference"],
            "expires": False,
        }
        tx_values['mercadopago_data'] = {
            'mercadopago_preference': preference,
            'mercadopago_client_id': self.mercadopago_client_id,
            'mercadopago_secret_key': self.mercadopago_secret_key,
            'environment': self.environment,
        }
        return partner_values, tx_values
Exemplo n.º 7
0
    def confirm_stored_shipment(self):
        """Create shipment(s) from a stored shipment."""
        if not self.unifaun_stored_shipmentid:
            raise Warning(_('No stored shipment found for this order.'))
        if self.unifaun_shipmentid:
            raise Warning(
                _('The stored shipment has already been confirmed (there is a Shipment id).'
                  ))
        if self.carrier_tracking_ref:
            raise Warning(
                _('Transport already ordered (there is a Tracking ref)'))
        if not self.carrier_id.unifaun_print_settings_id:
            raise Warning(
                _("No print settings found for carrier %s") %
                self.carrier_id.name)
        rec = {}
        # Send label printing instructions
        for i in range(1, 5):
            format = getattr(self.carrier_id.unifaun_print_settings_id,
                             'format_%s' % i)
            if format == 'null':
                rec.update({
                    'target%sMedia' % i: None,
                    'target%sXOffset' % i: 0.0,
                    'target%sYOffset' % i: 0.0,
                })
            else:
                x_offset = getattr(self.carrier_id.unifaun_print_settings_id,
                                   'x_offset_%s' % i)
                y_offset = getattr(self.carrier_id.unifaun_print_settings_id,
                                   'y_offset_%s' % i)
                rec.update({
                    'target%sMedia' % i: format,
                    'target%sXOffset' % i: x_offset,
                    'target%sYOffset' % i: y_offset,
                })
        response = self.carrier_id.unifaun_send(
            'stored-shipments/%s/shipments' % self.unifaun_stored_shipmentid,
            None, rec)
        if type(response) == list:
            _logger.warn('\n%s\n' % response)
            unifaun_shipmentid = ''
            carrier_tracking_ref = ''
            unifaun_pdfs = []
            parcels = 0
            for r in response:
                # Could be more than one shipment.
                if carrier_tracking_ref:
                    carrier_tracking_ref += ', '
                carrier_tracking_ref += r.get('shipmentNo') or ''
                if unifaun_shipmentid:
                    unifaun_shipmentid += ', '
                unifaun_shipmentid += r.get('id') or ''
                if r.get('pdfs'):
                    unifaun_pdfs += r['pdfs']
                for parcel in r.get('parcels') or []:
                    parcels += 1
                if self.package_ids and r.get('parcels'):
                    i = 0
                    for package in self.package_ids:
                        if i < len(r['parcels']):
                            package.unifaun_parcelno = r['parcels'][i].get(
                                u'parcelNo')
                        i += 1
            self.number_of_packages = parcels
            self.carrier_tracking_ref = carrier_tracking_ref
            self.unifaun_shipmentid = unifaun_shipmentid
            # create an attachment
            # TODO: several pdfs?
            for pdf in unifaun_pdfs:
                attachment = self.carrier_id.unifaun_download(pdf)
                attachment.write({'res_model': self._name, 'res_id': self.id})
                self.env['stock.picking.unifaun.pdf'].create({
                    'name':
                    pdf.get('description'),
                    'href':
                    pdf.get('href'),
                    'unifaunid':
                    pdf.get('id'),
                    'attachment_id':
                    attachment.id,
                    'picking_id':
                    self.id,
                })

            self.env['mail.message'].create({
                'body':
                _(u"Unifaun<br/>rec %s<br/>resp %s" % (rec, response)),
                'subject':
                "Shipment(s) Created",
                'author_id':
                self.env['res.users'].browse(self.env.uid).partner_id.id,
                'res_id':
                self.id,
                'model':
                self._name,
                'type':
                'notification',
            })
            self.unifaun_send_track_mail_silent()
        else:
            self.env['mail.message'].create({
                'body':
                _("Unifaun error!<br/>rec %s<br/>resp %s" % (rec, response)),
                'subject':
                "Create Shipment",
                'author_id':
                self.env['res.users'].browse(self.env.uid).partner_id.id,
                'res_id':
                self.id,
                'model':
                self._name,
                'type':
                'notification',
            })
        _logger.info('Unifaun Order Transport: rec %s response %s' %
                     (rec, response))
Exemplo n.º 8
0
 def unlink(self):
     if self.state not in ('draft', 'cancel'):
         raise Warning(
             _('You cannot delete a environment which is not \
                 draft or cancelled.'))
     return super(environment, self).unlink()
Exemplo n.º 9
0
 def make_env_paths(self):
     self.server_id.get_env()
     if exists(self.path, use_sudo=True):
         raise Warning(_("Folder '%s' already exists") % (self.path))
     sudo('mkdir -p ' + self.path)
Exemplo n.º 10
0
    def import_data_xls(self):
        for rec in self:
            cr, uid, context = self.env.args
            # Objects Creation

            datafile = rec.xls_file
            file_name = str(rec.datas_fname)

            # Checking for Suitable File
            if not datafile or not file_name.lower().endswith((
                    '.xls',
                    '.xlsx',
            )):
                raise Warning(
                    _("Please Select an .xls or its compatible file to Import Products"
                      ))
            # Checking for file type (extension)
            if file_name.lower().endswith((
                    '.xls',
                    '.xlsx',
            )):
                xls_data = base64.decodestring(datafile)
                temp_path = tempfile.gettempdir()
                fp = open(temp_path + '/xsl_file.xls', 'wb+')
                fp.write(xls_data)
                fp.close()
                wb = open_workbook(temp_path + '/xsl_file.xls')
                for sheet in wb.sheets():
                    header_list = []
                    for rownum in range(sheet.nrows):
                        # headers
                        if rownum == 0:
                            # converting unicode chars. into string
                            header_list = [
                                x.strip().encode('UTF8')
                                for x in sheet.row_values(rownum)
                            ]
                        vals = {}
                        product_ids = False
                        if header_list and rownum > 0:
                            record_data_l = [x for x in \
                                            sheet.row_values(rownum)]
                            final_dictionary = dict(
                                zip(header_list, record_data_l))
                            if record_data_l and final_dictionary:
                                for header_l in header_list:
                                    if header_l:
                                        rec_value = final_dictionary.get(
                                            header_l, False) or False
                                        same_ref_product = final_dictionary.get(
                                            'Item Reference', False) or False
                                        product_ids = self.env[
                                            'product.product'].search([
                                                ('default_code', '=',
                                                 same_ref_product)
                                            ])
                                        #                                         if header_l == 'EAN':
                                        #                                             vals.update({'ean13': rec_value})
                                        if not product_ids:
                                            vals.update(
                                                {'newly_imp_prod': True})
                                            if header_l == 'Item Reference':
                                                vals.update({
                                                    'default_code':
                                                    rec_value or ''
                                                })
                                            elif header_l == 'Item Name':
                                                vals.update(
                                                    {'name': rec_value or ''})
                                            elif header_l == 'Brand':
                                                brand = self.env[
                                                    'brand.brand'].search([
                                                        ('name', '=',
                                                         rec_value)
                                                    ])
                                                if not brand:
                                                    brand = self.env[
                                                        'brand.brand'].create({
                                                            'name':
                                                            rec_value
                                                        })
                                                vals.update(
                                                    {'brand': brand.id or ''})
                                            elif header_l == 'Flavor':
                                                flavor = self.env[
                                                    'flavor.flavor'].search([
                                                        ('name', '=',
                                                         rec_value)
                                                    ])
                                                if not flavor:
                                                    flavor = self.env[
                                                        'flavor.flavor'].create(
                                                            {
                                                                'name':
                                                                rec_value
                                                            })
                                                vals.update({
                                                    'flavor':
                                                    flavor.ids[0] or ''
                                                })
                                            elif header_l == 'Price':
                                                vals.update({
                                                    'list_price':
                                                    rec_value or ''
                                                })
                            if vals:
                                self.env['product.product'].create(vals)
        po_create_wiz_id = self.env['ir.model.data'].get_object_reference(
            'galaxy_purchase', 'wiz_galaxy_create_po_form')[1]
        return {
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'wiz.galaxy.create.po',
            'views': [(po_create_wiz_id, 'form')],
            'view_id': po_create_wiz_id,
            'target': 'new',
        }
Exemplo n.º 11
0
 def _check_number(self):
     if not self.number or self.number < 10 or self.number > 99:
         raise Warning(_('Number should be between 10 and 99'))
Exemplo n.º 12
0
 def copy(self, cr, uid, id, values, context=None):
     raise Warning(
         _("Duplicating workflows is not possible, please create a new workflow"
           ))
Exemplo n.º 13
0
#~ from datetime import datetime
#~ from dateutil.relativedelta import relativedelta
#~ from operator import itemgetter

#~ from openerp import pooler
#~ from openerp.osv import fields, osv
#~ from openerp.tools.translate import _

from openerp import models, fields, api, _
from openerp.exceptions import except_orm, Warning, RedirectWarning
import base64

try:
    from xlrd import open_workbook
except ImportError:
    raise Warning('excel library missing, pip install xlrd')



import logging
_logger = logging.getLogger(__name__)


class account_bank_accounts_wizard(models.TransientModel):
    _inherit='account.bank.accounts.wizard'

    account_type = fields.Selection(selection_add=[('bg','Bankgiro'),('pg','Plusgiro')])


class wizard_multi_charts_accounts(models.TransientModel):
    """
Exemplo n.º 14
0
 def _generic_reformat_phonenumbers(self, cr, uid, ids, vals, context=None):
     """Reformat phone numbers in E.164 format i.e. +33141981242"""
     assert isinstance(self._country_field, (str, unicode, type(None))),\
         'Wrong self._country_field'
     assert isinstance(self._partner_field, (str, unicode, type(None))),\
         'Wrong self._partner_field'
     assert isinstance(self._phone_fields, list),\
         'self._phone_fields must be a list'
     if context is None:
         context = {}
     if ids and isinstance(ids, (int, long)):
         ids = [ids]
     if any([vals.get(field) for field in self._phone_fields]):
         user = self.pool['res.users'].browse(cr, uid, uid, context=context)
         # country_id on res.company is a fields.function that looks at
         # company_id.partner_id.addres(default).country_id
         countrycode = None
         if self._country_field:
             if vals.get(self._country_field):
                 country = self.pool['res.country'].browse(
                     cr, uid, vals[self._country_field], context=context)
                 countrycode = country.code
             elif ids:
                 rec = self.browse(cr, uid, ids[0], context=context)
                 country = safe_eval('rec.' + self._country_field,
                                     {'rec': rec})
                 countrycode = country and country.code or None
         elif self._partner_field:
             if vals.get(self._partner_field):
                 partner = self.pool['res.partner'].browse(
                     cr, uid, vals[self._partner_field], context=context)
                 countrycode = partner.country_id and\
                     partner.country_id.code or None
             elif ids:
                 rec = self.browse(cr, uid, ids[0], context=context)
                 partner = safe_eval('rec.' + self._partner_field,
                                     {'rec': rec})
                 if partner:
                     countrycode = partner.country_id and\
                         partner.country_id.code or None
         if not countrycode:
             if user.company_id.country_id:
                 countrycode = user.company_id.country_id.code
             else:
                 _logger.warning(
                     "You should set a country on the company '%s' "
                     "to allow the reformat of phone numbers",
                     user.company_id.name)
                 countrycode = None
         if countrycode:
             countrycode = countrycode.upper()
             # with country code = None, phonenumbers.parse() will work
             # with phonenumbers formatted in E164, but will fail with
             # phone numbers in national format
         for field in self._phone_fields:
             if vals.get(field):
                 init_value = vals.get(field)
                 try:
                     res_parse = phonenumbers.parse(vals.get(field),
                                                    countrycode)
                     vals[field] = phonenumbers.format_number(
                         res_parse, phonenumbers.PhoneNumberFormat.E164)
                     if init_value != vals[field]:
                         _logger.debug(
                             "%s initial value: '%s' updated value: '%s'",
                             field, init_value, vals[field])
                 except Exception, e:
                     # I do BOTH logger and raise, because:
                     # raise is usefull when the record is created/written
                     #    by a user via the Web interface
                     # logger is usefull when the record is created/written
                     #    via the webservices
                     _logger.error(
                         "Cannot reformat the phone number '%s' to "
                         "international format with region=%s" %
                         (vals.get(field), countrycode))
                     if context.get('raise_if_phone_parse_fails'):
                         raise Warning(
                             _("Cannot reformat the phone number '%s' to "
                               "international format. Error message: %s") %
                             (vals.get(field), e))
Exemplo n.º 15
0
 def create(self, vals):
     if 'from_m2m' not in self._context:
         raise Warning(_('You can only '
                         'create Areas from companies!'))
     return super(partner_area, self).create(vals)
Exemplo n.º 16
0
    def create_vat(self):
        kontomoms = self.env['account.account'].with_context({'period_from': self.period_start.id, 'period_to': self.period_stop.id, 'state': self.target_move}).search(self.get_tax_account_domain())
        momsskuld = self.env['account.account'].search([('code', '=', '2650')])
        momsfordran = self.env['account.account'].search([('code', '=', '1650')])
        skattekonto = self.env['account.account'].search([('code', '=', '1630')])
        if len(kontomoms) > 0 and momsskuld and momsfordran and skattekonto:
            total = 0.0
            moms_journal_id = self.env['ir.config_parameter'].get_param('l10n_se_report.moms_journal')
            if not moms_journal_id:
                raise Warning('Konfigurera din momsdeklaration journal!')
            else:
                moms_journal = self.env['account.journal'].browse(moms_journal_id)
                vat = self.env['account.move'].create({
                    'journal_id': moms_journal.id,
                    'period_id': self.period_start.id,
                    'date': fields.Date.today(),
                })
                if vat:
                    for k in kontomoms: # kollar på 26xx konton
                        if k.balance > 0.0: # ingående moms
                            self.env['account.move.line'].create({
                                'name': k.name,
                                'account_id': k.id,
                                'credit': k.balance,
                                'debit': 0.0,
                                'move_id': vat.id,
                            })
                        if k.balance < 0.0: # utgående moms
                            self.env['account.move.line'].create({
                                'name': k.name,
                                'account_id': k.id,
                                'debit': abs(k.balance),
                                'credit': 0.0,
                                'move_id': vat.id,
                            })
                        total += k.balance
                    if total > 0.0: # momsfordran, moms ska få tillbaka
                        self.env['account.move.line'].create({
                            'name': momsfordran.name,
                            'account_id': momsfordran.id, # moms_journal.default_debit_account_id
                            'partner_id': '',
                            'debit': total,
                            'credit': 0.0,
                            'move_id': vat.id,
                        })
                        self.env['account.move.line'].create({
                            'name': momsfordran.name,
                            'account_id': momsfordran.id,
                            'partner_id': '',
                            'debit': 0.0,
                            'credit': total,
                            'move_id': vat.id,
                        })
                        self.env['account.move.line'].create({
                            'name': skattekonto.name,
                            'account_id': skattekonto.id,
                            'partner_id': self.env.ref('base.res_partner-SKV').id,
                            'debit': total,
                            'credit': 0.0,
                            'move_id': vat.id,
                        })
                    if total < 0.0: # moms redovisning, moms ska betalas in
                        self.env['account.move.line'].create({
                            'name': momsskuld.name,
                            'account_id': momsskuld.id, # moms_journal.default_credit_account_id
                            'partner_id': '',
                            'debit': 0.0,
                            'credit': abs(total),
                            'move_id': vat.id,
                        })
                        self.env['account.move.line'].create({
                            'name': momsskuld.name,
                            'account_id': momsskuld.id,
                            'partner_id': '',
                            'debit': abs(total),
                            'credit': 0.0,
                            'move_id': vat.id,
                        })
                        self.env['account.move.line'].create({
                            'name': skattekonto.name,
                            'account_id': skattekonto.id,
                            'partner_id': self.env.ref('base.res_partner-SKV').id,
                            'debit': 0.0,
                            'credit': abs(total),
                            'move_id': vat.id,
                        })

                    return {
                        'type': 'ir.actions.act_window',
                        'res_model': 'account.move',
                        'view_type': 'form',
                        'view_mode': 'form',
                        'view_id': self.env.ref('account.view_move_form').id,
                        'res_id': vat.id,
                        'target': 'current',
                        'context': {}
                    }
        else:
            raise Warning(_('Kontomoms: %sst, momsskuld: %s, momsfordran: %s, skattekonto: %s') %(len(kontomoms), momsskuld, momsfordran, skattekonto))
Exemplo n.º 17
0
    def check_argentinian_invoice_taxes(self):
        """
        We make theis function to be used as a constraint but also to be called
        from other models like vat citi
        """
        # only check for argentinian localization companies
        _logger.info('Running checks related to argentinian documents')

        # we consider argentinian invoices the ones from companies with
        # use_argentinian_localization and that belongs to a journal with
        # use_documents
        argentinian_invoices = self.filtered(
            lambda r: (r.use_argentinian_localization and r.use_documents))
        if not argentinian_invoices:
            return True

        # check invoice tax has code
        without_tax_code = self.env['account.invoice.tax'].search([
            ('invoice_id', 'in', argentinian_invoices.ids),
            ('tax_code_id', '=', False),
        ])
        if without_tax_code:
            raise Warning(
                _("You are using argentinian localization and there are some "
                  "invoices with taxes that don't have tax code, tax code is "
                  "required to generate this report. Invoies ids: %s" %
                  (without_tax_code.mapped('invoice_id.id'))))

        # check codes has argentinian tax attributes configured
        tax_codes = argentinian_invoices.mapped('tax_line.tax_code_id')
        unconfigured_tax_codes = tax_codes.filtered(
            lambda r: not r.type or not r.tax or not r.application)
        if unconfigured_tax_codes:
            raise Warning(
                _("You are using argentinian localization and there are some tax"
                  " codes that are not configured. Tax codes ids: %s" %
                  (unconfigured_tax_codes.ids)))

        # Check invoice with amount
        invoices_without_amount = self.search([('id', 'in',
                                                argentinian_invoices.ids),
                                               ('amount_total', '=', 0.0)])
        if invoices_without_amount:
            raise Warning(
                _('Invoices ids %s amount is cero!') %
                (invoices_without_amount.ids))

        # Check invoice requiring vat

        # out invoice must have vat if are argentinian and from a company with
        # responsability that requires vat
        sale_invoices_with_vat = self.search([
            ('id', 'in', argentinian_invoices.ids),
            ('type', 'in', ['out_invoice', 'out_refund']),
            ('company_id.partner_id.responsability_id.vat_tax_required_on_sales_invoices',
             '=', True)
        ])

        # check purchase invoice has supplier invoice number
        purchase_invoices = argentinian_invoices.filtered(
            lambda r: r.type in ('in_invoice', 'in_refund'))
        purchase_invoices_without_sup_number = purchase_invoices.filtered(
            lambda r: (not r.supplier_invoice_number))
        if purchase_invoices_without_sup_number:
            raise Warning(
                _("Some purchase invoices don't have supplier nunmber.\n"
                  "Invoices ids: %s" %
                  purchase_invoices_without_sup_number.ids))

        # purchase invoice must have vat if document class letter has vat
        # discriminated
        purchase_invoices_with_vat = purchase_invoices.filtered(lambda r: (
            r.afip_document_class_id.document_letter_id.vat_discriminated))

        invoices_with_vat = (sale_invoices_with_vat +
                             purchase_invoices_with_vat)

        for invoice in invoices_with_vat:
            # we check vat base amount is equal to amount untaxed
            # usamos una precision de 0.1 porque en algunos casos no pudimos
            # arreglar pbñe,as de redondedo
            if abs(invoice.vat_base_amount - invoice.amount_untaxed) > 0.1:
                raise Warning(
                    _("Invoice ID: %i\n"
                      "Invoice subtotal (%.2f) is different from invoice base"
                      " vat amount (%.2f)" %
                      (invoice.id, invoice.amount_untaxed,
                       invoice.vat_base_amount)))

        # check purchase invoices that can't have vat. We check only the ones
        # with document letter because other documents may have or not vat tax
        purchase_invoices_without = purchase_invoices.filtered(lambda r: (
            r.afip_document_class_id.document_letter_id and not r.
            afip_document_class_id.document_letter_id.vat_discriminated))
        for invoice in purchase_invoices_without:
            if invoice.vat_tax_ids:
                raise Warning(
                    _("Invoice ID %i shouldn't have any vat tax" % invoice.id))

        # Check except vat invoice
        afip_exempt_codes = ['Z', 'X', 'E', 'N', 'C']
        for invoice in argentinian_invoices:
            special_vat_taxes = invoice.tax_line.filtered(
                lambda r: r.tax_code_id.afip_code in [1, 2, 3])
            if (special_vat_taxes and invoice.fiscal_position.afip_code
                    not in afip_exempt_codes):
                raise Warning(
                    _("If there you have choose a tax with 0, exempt or untaxed,"
                      " you must choose a fiscal position with afip code in %s. "
                      "Invoice id %i" % (afip_exempt_codes, invoice.id)))
Exemplo n.º 18
0
    def _process_order(self, order):
        # initialization
        pos_line_obj = self.env['pos.order.line']
        move_obj = self.env['stock.move']
        picking_obj = self.env['stock.picking']
        stock_imm_tra_obj = self.env['stock.immediate.transfer']
        draft_order_id = order.get('old_order_id')
        picking_type_id = False
        picking_id_cust = False
        picking_id_rev = False
        if order.get('draft_order'):
            if not draft_order_id:
                order.pop('draft_order')
                order_id = self.create(self._order_fields(order))
                return order_id
            else:
                order_id = draft_order_id
                pos_line_ids = pos_line_obj.search([('order_id', '=', order_id)
                                                    ])
                if pos_line_ids:
                    pos_line_obj.unlink(pos_line_ids)
                self.write([order_id], {
                    'lines': order['lines'],
                    'partner_id': order.get('partner_id')
                })
                return order_id

        if not order.get('draft_order') and draft_order_id:
            order_id = draft_order_id
            order_obj = self.browse(order_id)
            pos_line_ids = pos_line_obj.search([('order_id', '=', order_id)])
            if pos_line_ids:
                if not order.get('cancel_order'):
                    for line_id in pos_line_ids:
                        line_id.unlink()
            temp = order.copy()
            temp.pop('statement_ids', None)
            temp.pop('name', None)
            temp.update({'date_order': order.get('creation_date')})
            warehouse_id = self.env['stock.warehouse'].search([
                ('lot_stock_id', '=', order_obj.config_id.stock_location_id.id)
            ],
                                                              limit=1)
            location_dest_id, supplierloc = self.env[
                'stock.warehouse']._get_partner_locations()
            if warehouse_id:
                picking_type_id = self.env['stock.picking.type'].search([
                    ('warehouse_id', '=', warehouse_id.id),
                    ('code', '=', 'internal')
                ])
            for line in order.get('lines'):
                prod_id = self.env['product.product'].browse(
                    line[2].get('product_id'))
                prod_dict = line[2]
                if prod_id.type != 'service' and prod_dict and prod_dict.get(
                        'cancel_item'):
                    # customer delivery order
                    picking_type_out = self.env['stock.picking.type'].search(
                        [('warehouse_id', '=',
                          order_obj.picking_id.picking_type_id.warehouse_id.id
                          ), ('code', '=', 'outgoing')],
                        limit=1)
                    if picking_type_out:
                        picking_id_cust = picking_obj.create({
                            'name':
                            picking_type_out.sequence_id.next_by_id(),
                            'picking_type_id':
                            picking_type_out.id,
                            'location_id':
                            order_obj.config_id.reserve_stock_location_id.id,
                            'location_dest_id':
                            location_dest_id.id,
                            'state':
                            'draft',
                            'origin':
                            order_obj.name
                        })
                    if order_obj.picking_id:
                        # unreserve order
                        picking_id_rev = picking_obj.create({
                            'name':
                            picking_type_out.sequence_id.next_by_id(),
                            'picking_type_id':
                            order_obj.picking_id.picking_type_id.id,
                            'location_id':
                            order_obj.config_id.reserve_stock_location_id.id,
                            'location_dest_id':
                            order_obj.config_id.stock_location_id.id,
                            'state':
                            'draft',
                            'origin':
                            order_obj.name
                        })
                        if prod_dict.get(
                                'consider_qty'
                        ) and not order_obj.order_status == 'partial' and not order.get(
                                'reserved'):
                            move_obj.create({
                                'product_id':
                                prod_id.id,
                                'name':
                                prod_id.name,
                                'product_uom_qty':
                                prod_dict.get('consider_qty'),
                                'location_id':
                                order_obj.config_id.reserve_stock_location_id.
                                id,
                                'location_dest_id':
                                location_dest_id.id,
                                'product_uom':
                                prod_id.uom_id.id,
                                'origin':
                                order_obj.name,
                                'picking_id':
                                picking_id_cust.id
                            })
                        if prod_dict.get('cancel_qty'):
                            move_obj.create({
                                'product_id':
                                prod_id.id,
                                'name':
                                prod_id.name,
                                'product_uom_qty':
                                abs(prod_dict.get('cancel_qty')),
                                'location_id':
                                order_obj.config_id.reserve_stock_location_id.
                                id,
                                'location_dest_id':
                                order_obj.config_id.stock_location_id.id,
                                'product_uom':
                                prod_id.uom_id.id,
                                'origin':
                                order_obj.name,
                                'picking_id':
                                picking_id_rev.id
                            })
            if picking_id_cust and picking_id_cust.move_lines:
                picking_id_cust.action_confirm()
                picking_id_cust.action_assign()
                picking_id_cust.button_validate()
                stock_transfer_id = stock_imm_tra_obj.search(
                    [('pick_ids', '=', picking_id_cust.id)],
                    limit=1).process()
                if stock_transfer_id:
                    stock_transfer_id.process()
                order_obj.with_context({
                    'out_order': True
                }).write({
                    'picking_id': picking_id_cust.id,
                    'unreserved': True
                })
            elif picking_id_cust:
                picking_id_cust.unlink()
            if picking_id_rev and picking_id_rev.move_lines:
                picking_id_rev.action_confirm()
                picking_id_rev.action_assign()
                picking_id_rev.button_validate()
                stock_transfer_id = stock_imm_tra_obj.search(
                    [('pick_ids', '=', picking_id_rev.id)], limit=1).process()
                if stock_transfer_id:
                    stock_transfer_id.process()
                order_obj.with_context({
                    'out_order': True
                }).write({
                    'picking_id': picking_id_rev.id,
                    'unreserved': True
                })
            elif picking_id_rev:
                picking_id_rev.unlink()
            total_price = 0.00
            for line in temp.get('lines'):
                linedict = line[2]
                if order_obj.session_id.config_id.prod_for_payment.id == linedict.get(
                        'product_id'):
                    temp.get('lines').remove(line)
                if order_obj.session_id.config_id.refund_amount_product_id.id == linedict.get(
                        'product_id'):
                    temp.get('lines').remove(line)
            total_price += sum([
                line[2].get('price_subtotal_incl')
                for line in temp.get('lines')
            ])
            temp['amount_total'] = total_price
            order_obj.write(temp)
            for payments in order['statement_ids']:
                order_obj.with_context({
                    'from_pos': True
                }).add_payment(self._payment_fields(payments[2]))
            session = self.env['pos.session'].browse(order['pos_session_id'])
            if session.sequence_number <= order['sequence_number']:
                session.write(
                    {'sequence_number': order['sequence_number'] + 1})
                session.refresh()
            if not float_is_zero(
                    order['amount_return'], self.env['decimal.precision'].
                    precision_get('Account')) or order['cancel_order']:
                cash_journal = session.cash_journal_id
                if not cash_journal:
                    cash_journal_ids = session.statement_ids.filtered(
                        lambda st: st.journal_id.type == 'cash')
                    if not len(cash_journal_ids):
                        raise Warning(
                            _('error!'),
                            _("No cash statement found for this session. Unable to record returned cash."
                              ))
                    cash_journal = cash_journal_ids[0].journal_id
                order_obj.with_context({
                    'from_pos': True
                }).add_payment({
                    'amount':
                    -order['amount_return'],
                    'payment_date':
                    time.strftime('%Y-%m-%d %H:%M:%S'),
                    'payment_name':
                    _('return'),
                    'journal':
                    cash_journal.id,
                })
            return order_obj
        if not order.get('draft_order') and not draft_order_id:
            order_id = super(pos_order, self)._process_order(order)
            if order_id.reserved:
                order_id.do_internal_transfer()
            return order_id
Exemplo n.º 19
0
    def order_stored_shipment(self):
        """Create a stored shipment."""
        if self.carrier_tracking_ref:
            raise Warning(
                _('Transport already ordered (there is a Tracking ref)'))
        if self.unifaun_shipmentid:
            raise Warning(
                _('The stored shipment has already been confirmed (there is a Shipment id).'
                  ))
        if self.unifaun_stored_shipmentid:
            self.delete_stored_shipment()
            # ~ raise Warning(_('A stored shipment already exists for this order.'))
        #~ error = ''
        #~ #if not self.weight:
        #~ #    error += '\n' if error else ''
        #~ #    error += _('The delivery must have a weight.')
        #~ # TODO: Add more error handling
        #~ if error:
        #~ raise Warning(error)
        # Choose sender and receiver based on picking type (in or out).
        if self.picking_type_id.code == 'incoming':
            receiver = self.picking_type_id.warehouse_id.partner_id
            sender = self.partner_id
        elif self.picking_type_id.code == 'outgoing':
            sender = self.picking_type_id.warehouse_id.partner_id
            receiver = self.partner_id
        receiver_record = self.unifaun_receiver_record(receiver)
        receiver_record.update(
            self.unifaun_receiver_contact(receiver, receiver_record))
        rec = {
            'sender':
            self.unifaun_sender_record(sender),
            'senderPartners': [{
                'id':
                self.carrier_id.unifaun_sender or '',
                'custNo':
                self.carrier_id.unifaun_customer_no or '',
            }],
            'receiver':
            receiver_record,
            'service': {
                'id': self.carrier_id.unifaun_service_code or '',
            },
            'parcels':
            self.unifaun_get_parcel_data(),
            'orderNo':
            self.name,
            'senderReference':
            self.get_unifaun_sender_reference(),
            #~ "receiverReference": "receiver ref 345",
            #~ "options": [{
            #~ "message": "This is order number 123",
            #~ "to": "*****@*****.**",
            #~ "id": "ENOT",
            #~ "languageCode": "SE",
            #~ "from": "*****@*****.**"
            #~ }],
        }

        if self.unifaun_param_ids:
            self.unifaun_param_ids.add_to_record(rec)

        response = self.carrier_id.unifaun_send('stored-shipments', None, rec)
        if type(response) == type({}):
            _logger.warn('\n%s\n' % response)
            self.unifaun_stored_shipmentid = response.get('id', '')

            self.env['mail.message'].create({
                'body':
                _(u"Unifaun<br/>rec %s<br/>resp %s<br/>" % (rec, response)),
                'subject':
                "Order Transport",
                'author_id':
                self.env['res.users'].browse(self.env.uid).partner_id.id,
                'res_id':
                self.id,
                'model':
                self._name,
                'type':
                'notification',
            })
            self.set_unifaun_status(response.get('statuses') or [])
        else:
            self.env['mail.message'].create({
                'body':
                _("Unifaun error!<br/>rec %s<br/>resp %s<br/>" %
                  (rec, response)),
                'subject':
                "Order Transport",
                'author_id':
                self.env['res.users'].browse(self.env.uid).partner_id.id,
                'res_id':
                self.id,
                'model':
                self._name,
                'type':
                'notification',
            })
        _logger.info('Unifaun Order Transport: rec %s response %s' %
                     (rec, response))
Exemplo n.º 20
0
    def action_run_operations(self):
        self.ensure_one()
        invoices = self
        # TODO tal vez podemos agregar un campo calculado y hacer que devuevla
        # el porcentaje segun si es balance o porcentaje, el tema es que
        # el agrupador varia de modelo a modelo
        # if there is a line with balance we have 100.0, else we have
        total_percentage = self.operation_ids.filtered(
            lambda x: x.amount_type == 'balance') and 100.0 or sum(
                self.operation_ids.mapped('percentage'))
        last_quantities = {
            line.id: line.quantity
            for line in self.invoice_line
        }
        invoice_type = self.type
        remaining_op = len(self.operation_ids)
        sale_orders = []
        purchase_orders = []
        # if sale installed we get linked sales orders to update invoice links
        if self.env['ir.model'].search([('model', '=', 'sale.order')]):
            sale_orders = self.env['sale.order'].search([('invoice_ids', 'in',
                                                          [self.id])])
        # if purchase installed we also update links
        if self.env['ir.model'].search([('model', '=', 'purchase.order')]):
            purchase_orders = self.env['purchase.order'].search([
                ('invoice_ids', 'in', [self.id])
            ])

        for operation in self.operation_ids:
            default = {
                'operation_ids': False,
                # no copiamos para poder hacer control de las cantidades
                'invoice_line': False,
                # do not copy period (if we want it we should get right period
                # for the date, eg. in inter_company_rules)
                'period_id': False,
            }

            # por compatibilidad con stock_picking_invoice_link
            # como el campo nuevo tiene copy=False lo copiamos nosotros
            if 'picking_ids' in self._fields:
                default['picking_ids'] = [(6, 0, self.sudo().picking_ids.ids)]

            company = False
            journal = False
            # if op journal and is different from invoice journal
            if (operation.journal_id
                    and operation.journal_id != self.journal_id):
                company = operation.journal_id.company_id
                journal = operation.journal_id
                default['journal_id'] = journal.id
                default['company_id'] = company.id
            # if op company and is different from invoice company
            elif (operation.company_id
                  and operation.company_id != self.company_id):
                company = operation.company_id
                default['company_id'] = operation.company_id.id
                # we get a journal in new company
                journal = self.with_context(
                    company_id=company.id)._default_journal()
                if not journal:
                    raise Warning(
                        _('No %s journal found on company %s') %
                        (self.journal_type, company.name))
                default['journal_id'] = journal.id

            if operation.date:
                default['date_invoice'] = operation.date
            elif operation.days and operation.days2:
                # TODO tal vez podamos pasar alguna fecha a esta funcion si
                # interesa
                default['date_invoice'] = operation._get_date()

            # if journal then journal has change and we need to
            # upate, at least, account_id
            if journal:
                partner_data = self.onchange_partner_id(
                    invoice_type,
                    self.partner_id.id,
                    date_invoice=default.get('date_invoice', False)
                    or self.date_invoice,
                    payment_term=self.payment_term.id,
                    company_id=company.id)['value']
                default.update({
                    'account_id':
                    partner_data.get('account_id', False),
                    # we dont want to change fiscal position
                    # 'fiscal_position': partner_data.get(
                    #     'fiscal_position', False),
                    'partner_bank_id':
                    partner_data.get('partner_bank_id', False),
                    'payment_term':
                    partner_data.get('payment_term', False),
                })

            if operation.reference:
                default['reference'] = "%s%s" % (self.reference
                                                 or '', operation.reference)

            new_invoice = self.copy(default)

            for line in self.invoice_line:
                # if last operation and total perc 100 then we adjust qtys
                if remaining_op == 1 and total_percentage == 100.0:
                    new_quantity = last_quantities.get(line.id)
                else:
                    line_percentage = line._get_operation_percentage(operation)
                    new_quantity = line.quantity * line_percentage / 100.0
                    if operation.rounding:
                        new_quantity = float_round(
                            new_quantity,
                            precision_rounding=operation.rounding)
                    last_quantities[line.id] = (
                        last_quantities.get(line.id, line.quantity) -
                        new_quantity)

                line_defaults = {
                    'invoice_id': new_invoice.id,
                    'quantity': new_quantity,
                }
                # por compatibilidad con stock_picking_invoice_link
                # como el campo nuevo tiene copy=False lo copiamos nosotros
                if 'move_line_ids' in self._fields:
                    default['move_line_ids'] = [
                        (6, 0, line.sudo().move_line_ids.ids)
                    ]

                # if company has change, then we need to update lines
                if company and company != self.company_id:
                    line_data = line.with_context(
                        force_company=company.id).sudo().product_id_change(
                            line.product_id.id,
                            line.product_id.uom_id.id,
                            qty=new_quantity,
                            name='',
                            type=invoice_type,
                            partner_id=self.partner_id.id,
                            fposition_id=self.fiscal_position.id,
                            company_id=company.id)
                    # we only update account and taxes

                    account_id = line_data['value'].get('account_id')
                    # not acconunt usually for lines without product
                    if not account_id:
                        prop = self.env['ir.property'].with_context(
                            force_company=company.id).get(
                                'property_account_income_categ',
                                'product.category')
                        prop_id = prop and prop.id or False
                        account_id = self.fiscal_position.map_account(prop_id)
                        if not account_id:
                            raise Warning(
                                _('There is no income account defined as global '
                                  'property.'))

                    line_defaults.update({
                        'account_id':
                        account_id,
                        'invoice_line_tax_id':
                        [(6, 0, line_data['value'].get('invoice_line_tax_id',
                                                       []))],
                    })

                if new_quantity:
                    new_line = line.copy(line_defaults)
                    # if sale_orders we update links
                    if sale_orders:
                        sale_lines = self.env['sale.order.line'].search([
                            ('invoice_lines', 'in', [line.id])
                        ])
                        sale_lines.write({'invoice_lines': [(4, new_line.id)]})

                    if purchase_orders:
                        purchas_lines = self.env['purchase.order.line'].search(
                            [('invoice_lines', 'in', [line.id])])
                        purchas_lines.write(
                            {'invoice_lines': [(4, new_line.id)]})
                        purchase_orders.write(
                            {'invoice_ids': [(4, new_invoice.id)]})

            # not sure why but in some cases we need to update this and in
            # others it is updated automatically
            for order in sale_orders:
                if new_invoice not in order.invoice_ids:
                    self._cr.execute(
                        'insert into sale_order_invoice_rel (order_id, invoice_id) values (%s,%s)',
                        (order.id, new_invoice.id))

            # if no invoice lines then we unlink the invoice
            if not new_invoice.invoice_line:
                new_invoice.unlink()
            else:
                # update amounts for new invoice
                new_invoice.button_reset_taxes()
                if operation.automatic_validation:
                    new_invoice.signal_workflow('invoice_open')

                invoices += new_invoice

            # update remaining operations
            remaining_op -= 1

        # if operations sum 100, then we delete parent invoice, if not, then
        # we delete operations after succes operation
        self.operation_ids.unlink()
        # we delete original invoice if at least one was created and no need
        # for thisone
        if total_percentage == 100.0 and len(invoices) > 1:
            invoices -= self
            # we redirect workflow so that sale order doenst goes to except
            # state and also if we delete new invoice it sends to except
            # we only send first invoice because it does not works ok with many
            # invoices
            self.redirect_workflow([(self.id, invoices[0].id)])
            # borrar factura
            # por compatibilidad con sale commission, borramos las lineas y
            # luego la factura
            self.invoice_line.unlink()
            self.unlink()
            # actualizar pickings
        else:
            for line in self.invoice_line:
                line_quantity = last_quantities.get(line.id)
                # if remaining qty = 0 we delete line
                if not line_quantity or line_quantity == 0.0:
                    line.unlink()
                else:
                    line.quantity = last_quantities.get(line.id)
            # self.operation_ids.unlink()

        # por compatibilidad con stock_picking_invoice_link
        # we set all related pickings on invoiced state
        if 'picking_ids' in self._fields:
            pickings = invoices.sudo().mapped('picking_ids').filtered(
                lambda x: x.state != 'cancel')
            pickings.write({'invoice_state': 'invoiced'})

        # set plan false for all invoices
        invoices.write({'plan_id': False})

        if invoice_type in ['out_invoice', 'out_refund']:
            action_ref = 'account.action_invoice_tree1'
            form_view_ref = 'account.invoice_form'
        else:
            action_ref = 'account.action_invoice_tree2'
            form_view_ref = 'account.invoice_supplier_form'
        action = self.env.ref(action_ref)
        result = action.read()[0]

        if len(invoices) > 1:
            # result[
            result['domain'] = [('id', 'in', invoices.ids)]
        else:
            form_view = self.env.ref(form_view_ref)
            result['views'] = [(form_view.id, 'form')]
            result['res_id'] = invoices.id
        return result
 def confirm(self):
     if not self.is_compatible():
         raise Warning(_("Only females can be farrow"))
     if not self.is_ready():
         raise Warning(
             _("Only diagnosticated pregnant females can be farrow"))
     if self.dead == 0 and self.live == 0:
         raise Warning(_('no deads and no lives'))
     company = self.env['res.company'].search([(True, '=', True)])[0]
     journal = self.env['account.analytic.journal'].search([('code', '=',
                                                             'FAR')])
     analytic_line_obj = self.env['account.analytic.line']
     farrowing_cycle_obj = self.env['farm.farrowing.event_female_cycle']
     farrrowing_animalGroup_obj = self.env['farm.farrowing.event_group']
     location_obj = self.env['farm.foster.locations']
     foster_locations = []
     for loc in self.animal.specie.foster_location:
         foster_locations.append(loc.id)
         print loc.location
         print loc.location.location_id
     print foster_locations
     print self.farm.id
     foster_location = location_obj.search([
         ('location.location_id.location_id', '=', self.farm.id),
         ('id', 'in', foster_locations),
     ], ).location
     print foster_location
     farrowing_cycle_obj.create({
         'event': self.id,
         'cycle': self.animal.cycles[-1].id
     })
     if self.live != 0:
         self.get_female_move(foster_location)
         new_group = self.get_produced_group()
         farrrowing_animalGroup_obj.create({
             'event': self.id,
             'animal_group': new_group[0].id
         })
         self.animal.current_cycle.update_state(self)
         tot_cost = 0
         for line in self.animal.account.line_ids:
             tot_cost = tot_cost + line.amount
         analytic_line_obj.create({
             'name':
             'Farrow Cost',
             'date':
             self.timestamp,
             'ref':
             'farrow',
             'amount':
             tot_cost,
             'unit_amount':
             1,
             'account_id':
             new_group[0].account.id,
             'general_account_id':
             company.feed_account.id,
             'journal_id':
             journal.id,
         })
         analytic_line_obj.create({
             'name':
             'Farrow Cost',
             'date':
             self.timestamp,
             'ref':
             'farrow',
             'amount':
             -(tot_cost),
             'unit_amount':
             1,
             'account_id':
             self.animal.account.id,
             'general_account_id':
             company.feed_account.id,
             'journal_id':
             journal.id,
         })
     super(FarrowingEvent, self).confirm()
Exemplo n.º 22
0
    def create_partner(self, values):
        search_partner = self.env['res.partner'].search([('name','=',values.get('name'))])
        parent = False
        state = False
        country = False
        saleperson = False
        vendor_pmt_term = False
        cust_pmt_term = False
        
        if values.get('type') == 'company':
            if values.get('parent'):
                raise Warning('You can not give parent if you have select type is company')
            type =  'company'
        else:
            type =  'person'
            parent_search = self.env['res.partner'].search([('name','=',values.get('parent'))])
            if parent_search:
                parent =  parent_search.id
                
        if values.get('state'):
            state = self.find_state(values)
        if values.get('country'):
            country = self.find_country(values)
        if values.get('saleperson'):
            saleperson_search = self.env['res.users'].search([('name','=',values.get('saleperson'))])
            if not saleperson_search:
                raise Warning("Salesperson not available in system")
            else:
                saleperson = saleperson_search.id
        if values.get('cust_pmt_term'):
            cust_payment_term_search = self.env['account.payment.term'].search([('name','=',values.get('cust_pmt_term'))])
            if not cust_payment_term_search:
                raise Warning("Payment term not available in system")
            else:
                cust_pmt_term = cust_payment_term_search.id
        if values.get('vendor_pmt_term'):
            vendor_payment_term_search = self.env['account.payment.term'].search([('name','=',values.get('vendor_pmt_term'))])
            if not vendor_payment_term_search:
                raise Warning("Payment term not available in system")
            else:
                vendor_pmt_term = vendor_payment_term_search.id
        
        if search_partner:
            is_customer = False
            is_supplier = False
            if values.get('customer') == '1.0' or '1':
               is_customer = True

            if values.get('vendor') == '1.0' or '1':
               is_supplier = True

            search_partner.company_type = type
            search_partner.parent_id = parent or False
            search_partner.street = values.get('street')
            search_partner.street2 = values.get('street2')
            search_partner.city = values.get('city')
            search_partner.state_id = state
            search_partner.zip = values.get('zip')
            search_partner.country_id = country
            search_partner.website = values.get('website')
            
            search_partner.phone = values.get('phone')
            search_partner.mobile = values.get('mobile')
            search_partner.email = values.get('email')
            search_partner.customer = is_customer
            search_partner.supplier = is_supplier
            search_partner.user_id = saleperson
            search_partner.ref = values.get('street'),
            search_partner.property_payment_term_id = cust_pmt_term or False
            search_partner.property_supplier_payment_term_id = vendor_pmt_term or False
            return True
        else:
            is_customer = False
            is_supplier = False
            if int(float(values.get('customer'))) == 1:
               is_customer = True

            if int(float(values.get('vendor'))) == 1:
               is_supplier = True

            vals = {
                                  'name':values.get('name'),
                                  'company_type':type,
                                  'parent_id':parent or False,
                                  'street':values.get('street'),
                                  'street2':values.get('street2'),
                                  'city':values.get('city'),
                                  'state_id':state,
                                  'zip':values.get('zip'),
                                  'country_id':country,
                                  'website':values.get('website'),
                                  'phone':values.get('phone'),
                                  'mobile':values.get('mobile'),
                                  'email':values.get('email'),
                                  'customer':is_customer,
                                  'supplier':is_supplier,
                                  'user_id':saleperson,
                                  'ref':values.get('ref'),
                                  'property_payment_term_id':cust_pmt_term or False,
                                  'property_supplier_payment_term_id':vendor_pmt_term or False,
                                  }
            res = self.env['res.partner'].create(vals)
            return res
Exemplo n.º 23
0
def price_from_transsmart_price(price_str):
    """convert transsmart price string to odoo float field."""
    if price_str.startswith('EUR '):
        return float(price_str[4:].replace(',', '.'))
    raise Warning(
        _("Couldn't convert transsmart price %s to float") % (price_str, ))
Exemplo n.º 24
0
    def import_partner(self):
 
        if self.import_option == 'csv':   
            keys = ['name','type','parent','street','street2','city','state','zip','country','website','phone','mobile','email','customer','vendor','saleperson','ref','cust_pmt_term','vendor_pmt_term']
            csv_data = base64.b64decode(self.file)
            data_file = io.StringIO(csv_data.decode("utf-8"))
            data_file.seek(0)
            file_reader = []
            res = {}
            csv_reader = csv.reader(data_file, delimiter=',')
            try:
                file_reader.extend(csv_reader)
            except Exception:
                raise exceptions.Warning(_("Invalid file!"))
            values = {}
            for i in range(len(file_reader)):
#                val = {}
                field = list(map(str, file_reader[i]))
                values = dict(zip(keys, field))
                if values:
                    if i == 0:
                        continue
                    else:
                        values.update({'option':self.import_option})
                        if self.partner_option == 'create':
                            res = self.create_partner(values)
                        else:
                            search_partner = self.env['res.partner'].search([('name','=',values.get('name'))])
                            parent = False
                            state = False
                            country = False
                            saleperson = False
                            vendor_pmt_term = False
                            cust_pmt_term = False
                            
                            is_customer = False
                            is_supplier = False
                            if int(float(values.get('customer'))) == 1:
                               is_customer = True

                            if int(float(values.get('vendor'))) == 1:
                               is_supplier = True

                            if values.get('type') == 'company':
                                if values.get('parent'):
                                    raise Warning('You can not give parent if you have select type is company')
                                type =  'company'
                            else:
                                type =  'person'
                                parent_search = self.env['res.partner'].search([('name','=',values.get('parent'))])
                                if parent_search:
                                    parent =  parent_search.id
                                    
                            if values.get('state'):
                                state = self.find_state(values)
                            if values.get('country'):
                                country = self.find_country(values)
                            if values.get('saleperson'):
                                saleperson_search = self.env['res.users'].search([('name','=',values.get('saleperson'))])
                                if not saleperson_search:
                                    raise Warning("Salesperson not available in system")
                                else:
                                    saleperson = saleperson_search.id
                            if values.get('cust_pmt_term'):
                                cust_payment_term_search = self.env['account.payment.term'].search([('name','=',values.get('cust_pmt_term'))])
                                if not cust_payment_term_search:
                                    raise Warning("Payment term not available in system")
                                else:
                                    cust_pmt_term = cust_payment_term_search.id
                            if values.get('vendor_pmt_term'):
                                vendor_payment_term_search = self.env['account.payment.term'].search([('name','=',values.get('vendor_pmt_term'))])
                                if not vendor_payment_term_search:
                                    raise Warning("Payment term not available in system")
                                else:
                                    vendor_pmt_term = vendor_payment_term_search.id
                            
                            if search_partner:
                                search_partner.company_type = type
                                search_partner.parent_id = parent or False
                                search_partner.street = values.get('street')
                                search_partner.street2 = values.get('street2')
                                search_partner.city = values.get('city')
                                search_partner.state_id = state
                                search_partner.zip = values.get('zip')
                                search_partner.country_id = country
                                search_partner.website = values.get('website')
                                
                                search_partner.phone = values.get('phone')
                                search_partner.mobile = values.get('mobile')
                                search_partner.email = values.get('email')
                                search_partner.customer = is_customer
                                search_partner.supplier = is_supplier
                                search_partner.user_id = saleperson
                                search_partner.ref = values.get('ref')
                                search_partner.property_payment_term_id = cust_pmt_term or False
                                search_partner.property_supplier_payment_term_id = vendor_pmt_term or False
                            else:
                                raise Warning(_('%s partner not found.') % values.get('name'))
        else:
            fp = tempfile.NamedTemporaryFile(delete = False,suffix=".xlsx")
            fp.write(binascii.a2b_base64(self.file))
            fp.seek(0)
            values = {}
            res = {}
            workbook = xlrd.open_workbook(fp.name)
            sheet = workbook.sheet_by_index(0)
            for row_no in range(sheet.nrows):
                if row_no <= 0:
                    fields = map(lambda row:row.value.encode('utf-8'), sheet.row(row_no))
                else:
                    line = (map(lambda row:isinstance(row.value, unicode) and row.value.encode('utf-8') or str(row.value), sheet.row(row_no)))
                    if self.partner_option == 'create':
                        values.update( {'name':line[0],
                                        'type': line[1],
                                        'parent': line[2],
                                        'street': line[3],
                                        'street2': line[4],
                                        'city': line[5],
                                        'state': line[6],
                                        'zip': line[7],
                                        'country': line[8],
                                        'website': line[9],
                                        'phone': line[10],
                                        'mobile': line[11],
                                        'email': line[12],
                                        'customer': int(float(line[13])),
                                        'vendor': int(float(line[14])),
                                        'saleperson': line[15],
                                        'ref': line[16],
                                        'cust_pmt_term': line[17],
                                        'vendor_pmt_term': line[18],
                                        })
                        res = self.create_partner(values)
                    else:
                        search_partner = self.env['res.partner'].search([('name','=',line[0])])
                        parent = False
                        state = False
                        country = False
                        saleperson = False
                        vendor_pmt_term = False
                        cust_pmt_term = False

                        is_customer = False
                        is_supplier = False
                        if line[13]:
                            if int(float(line[13])) == 1:
                               is_customer = True

                        if line[14]:
                            if int(float(line[14])) == 1:
                               is_supplier = True

                        if line[1] == 'company':
                            if line[2]:
                                raise Warning('You can not give parent if you have select type is company')
                            type =  'company'
                        else:
                            type =  'person'
                            parent_search = self.env['res.partner'].search([('name','=',line[2])])
                            if parent_search:
                                parent =  parent_search.id
                            else:
                                raise Warning("Parent contact  not available")
                        
                        if line[6]:
                            state = self.find_state(line)
                        if line[8]:
                            country = self.find_country(line)
                        if line[15]:
                            saleperson_search = self.env['res.users'].search([('name','=',line[15])])
                            if not saleperson_search:
                                raise Warning("Salesperson not available in system")
                            else:
                                saleperson = saleperson_search.id
                        if line[17]:
                            cust_payment_term_search = self.env['account.payment.term'].search([('name','=',line[17])])
                            if not cust_payment_term_search:
                                raise Warning("Payment term not available in system")
                            else:
                                cust_pmt_term = cust_payment_term_search.id
                        if line[18]:
                            vendor_payment_term_search = self.env['account.payment.term'].search([('name','=',line[18])])
                            if not vendor_payment_term_search:
                                raise Warning("Payment term not available in system")
                            else:
                                vendor_pmt_term = vendor_payment_term_search.id
                        
                        if search_partner:
                            search_partner.company_type = type
                            search_partner.parent_id = parent or False
                            search_partner.street = line[3]
                            search_partner.street2 = line[4]
                            search_partner.city = line[5]
                            search_partner.state_id = state
                            search_partner.zip = line[7]
                            search_partner.country_id = country
                            search_partner.website = line[9]
                            
                            search_partner.phone = line[10]
                            search_partner.mobile = line[11]
                            search_partner.email = line[12]
                            search_partner.customer = is_customer
                            search_partner.supplier = is_supplier
                            search_partner.user_id = saleperson
                            search_partner.ref = line[16]
                            search_partner.property_payment_term_id = cust_pmt_term or False
                            search_partner.property_supplier_payment_term_id = vendor_pmt_term or False
                        else:
                            raise Warning(_('%s partner not found.') % line[0])
        return res
Exemplo n.º 25
0
 def _check_company_id(self):
     if self.point_of_sale_id and self.point_of_sale_id.company_id != self.company_id:
         raise Warning(
             _('The company of the point of sale and of the \
             journal must be the same!'))
Exemplo n.º 26
0
    def wizard_release_lc(self):
        lc_active_ids = self._context.get('active_ids')
        lc_id = self.env['account.letter'].browse(lc_active_ids)
        lc_release = self.env['account.letter.release']
        if lc_id:
            lc_release.create({
                'letter_id': lc_id.id,
                'shipment_val': self.shipment_val,
                'lc_val': self.lc_val,
                'loan_val': self.loan_val,
            })
            total_shipment_val = sum(
                rel.shipment_val
                for rel in lc_release.search([('letter_id', '=', lc_id.id)]))
            if total_shipment_val > lc_id.lc_value:
                raise Warning(
                    'You Can not proceed with shipment amount above PO value!!!'
                )
            else:
                partner_payable_account = lc_id.partner_id.property_account_payable_id
                bank_related_account_id = lc_id.journal_id.default_credit_account_id
                if not partner_payable_account:
                    raise Warning(
                        "Related partner doesn't have Partner Payable Account!!!"
                    )
                if not bank_related_account_id:
                    raise Warning(
                        "Related Bank doesn't have Default Credit Account!!!")
                ref = 'Lc With Release number ' + lc_id.number + ' / ' + lc_id.name
                company_currency = self.env.user.company_id.currency_id
                shipment_val = self.shipment_val
                # lc_id.form_for and or
                lc_val = self.lc_val
                loan_val = self.loan_val
                bank_exp_val = self.bank_exp
                mang_exp_val = self.mang_exp
                if company_currency != lc_id.currency_id:
                    shipment_val = lc_id.currency_id.compute(
                        shipment_val, company_currency)
                    lc_val = lc_id.currency_id.compute(lc_val,
                                                       company_currency)
                    loan_val = lc_id.currency_id.compute(
                        loan_val, company_currency)
                    bank_exp_val = lc_id.currency_id.compute(
                        bank_exp_val, company_currency)
                    mang_exp_val = lc_id.currency_id.compute(
                        mang_exp_val, company_currency)

                shipment_debit_line_vals = {
                    'name':
                    lc_id.name,
                    'account_id':
                    partner_payable_account.id,
                    'debit':
                    shipment_val,
                    'ref':
                    ref,
                    'partner_id':
                    lc_id.partner_id.id,
                    'currency_id':
                    lc_id.currency_id and lc_id.currency_id.id or False,
                }
                if lc_id.form_for:
                    account_id = bank_related_account_id.id
                else:
                    account_id = lc_id.lc_margin_account_id.id
                lc_credit_line_vals = {
                    'name':
                    lc_id.name,
                    'account_id':
                    account_id,
                    'credit':
                    lc_val,
                    'ref':
                    ref,
                    'partner_id':
                    lc_id.partner_id.id,
                    'currency_id':
                    lc_id.currency_id and lc_id.currency_id.id or False,
                    'analytic_account_id':
                    lc_id.form_for and lc_id.analytic_account_id.id or False
                }
                loan_credit_line_vals = {
                    'name':
                    lc_id.name,
                    'account_id':
                    lc_id.lc_loan_account_id.id,
                    'credit':
                    loan_val,
                    'ref':
                    ref,
                    'date_maturity':
                    lc_id.lc_date_end,
                    'currency_id':
                    lc_id.currency_id and lc_id.currency_id.id or False,
                    'analytic_account_id':
                    lc_id.analytic_account_id and lc_id.analytic_account_id.id
                    or False,
                    'partner_id':
                    lc_id.partner_id.id,
                }

                move_vals = {
                    'name':
                    lc_id.name,
                    'journal_id':
                    lc_id.journal_id.id,
                    'date':
                    date.today(),
                    'ref':
                    ref,
                    'state':
                    'posted',
                    'letter_id':
                    lc_id.id,
                    'line_ids': [(0, 0, shipment_debit_line_vals),
                                 (0, 0, lc_credit_line_vals),
                                 (0, 0, loan_credit_line_vals)]
                }
                move_one = self.env['account.move'].create(move_vals)

                bank_exp_debit_line_vals = {
                    'name':
                    lc_id.name,
                    'account_id':
                    lc_id.lc_commission_account_id.id,
                    'debit':
                    bank_exp_val,
                    'ref':
                    ref,
                    'currency_id':
                    lc_id.currency_id and lc_id.currency_id.id or False,
                }
                mang_exp_debit_line_vals = {
                    'name':
                    lc_id.name,
                    'account_id':
                    lc_id.lc_manag_exp_account_id.id,
                    'debit':
                    mang_exp_val,
                    'ref':
                    ref,
                    'currency_id':
                    lc_id.currency_id and lc_id.currency_id.id or False,
                }
                mang_bank_exp_credit_line_vals = {
                    'name':
                    lc_id.name,
                    'account_id':
                    bank_related_account_id.id,
                    'credit':
                    bank_exp_val + mang_exp_val,
                    'ref':
                    ref,
                    'currency_id':
                    lc_id.currency_id and lc_id.currency_id.id or False,
                    'analytic_account_id':
                    lc_id.analytic_account_id and lc_id.analytic_account_id.id
                    or False,
                }

                move_vals['line_ids'] = [(0, 0, bank_exp_debit_line_vals),
                                         (0, 0, mang_exp_debit_line_vals),
                                         (0, 0, mang_bank_exp_credit_line_vals)
                                         ]
                move_two = self.env['account.move'].create(move_vals)

                if move_one and move_two:
                    if lc_id.state == 'validate':
                        lc_id.write({'state': 'release'})
                    return True
                else:
                    raise Warning(
                        "Something went wrong.\n The Entries doesn't created\n please review your administer."
                    )
Exemplo n.º 27
0
    def _price_rule_get_multi(self,
                              cr,
                              uid,
                              pricelist,
                              products_by_qty_by_partner,
                              context=None):
        context = context or {}
        date = context.get('date') or time.strftime('%Y-%m-%d')
        date = date[0:10]

        products = map(lambda x: x[0], products_by_qty_by_partner)
        currency_obj = self.pool.get('res.currency')
        product_obj = self.pool.get('product.template')
        product_uom_obj = self.pool.get('product.uom')
        price_type_obj = self.pool.get('product.price.type')

        if not products:
            return {}

        version = False
        for v in pricelist.version_id:
            if ((v.date_start is False) or
                (v.date_start <= date)) and ((v.date_end is False) or
                                             (v.date_end >= date)):
                version = v
                break
        if not version:
            raise Warning(
                _("At least one pricelist has no active version !\nPlease create or activate one."
                  ))

        categ_ids = {}
        for p in products:
            categ = p.categ_id
            while categ:
                categ_ids[categ.id] = True
                categ = categ.parent_id
        categ_ids = categ_ids.keys()

        is_product_template = products[0]._name == "product.template"
        if is_product_template:
            prod_tmpl_ids = [tmpl.id for tmpl in products]
            # all variants of all products
            prod_ids = [
                p.id for p in list(
                    chain.from_iterable(
                        [t.product_variant_ids for t in products]))
            ]
        else:
            prod_ids = [product.id for product in products]
            prod_tmpl_ids = [
                product.product_tmpl_id.id for product in products
            ]

        # Load all rules
        cr.execute(
            'SELECT i.id '
            'FROM product_pricelist_item AS i '
            'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = any(%s)) '
            'AND (product_id IS NULL OR (product_id = any(%s))) '
            'AND ((categ_id IS NULL) OR (categ_id = any(%s))) '
            'AND (price_version_id = %s) '
            'ORDER BY sequence, min_quantity desc',
            (prod_tmpl_ids, prod_ids, categ_ids, version.id))

        item_ids = [x[0] for x in cr.fetchall()]
        items = self.pool.get('product.pricelist.item').browse(cr,
                                                               uid,
                                                               item_ids,
                                                               context=context)

        price_types = {}

        results = {}
        for product, qty, partner in products_by_qty_by_partner:
            results[product.id] = 0.0
            rule_ids = []
            price = False

            # Final unit price is computed according to `qty` in the `qty_uom_id` UoM.
            # An intermediary unit price may be computed according to a different UoM, in
            # which case the price_uom_id contains that UoM.
            # The final price will be converted to match `qty_uom_id`.
            qty_uom_id = context.get('uom') or product.uom_id.id
            price_uom_id = product.uom_id.id
            qty_in_product_uom = qty
            if qty_uom_id != product.uom_id.id:
                try:
                    qty_in_product_uom = product_uom_obj._compute_qty(
                        cr, uid, context['uom'], qty, product.uom_id.id
                        or product.uos_id.id)
                except except_orm:
                    # Ignored - incompatible UoM in context, use default product UoM
                    pass

            for rule in items:
                if rule.min_quantity and qty_in_product_uom < rule.min_quantity:
                    continue
                if is_product_template:
                    if rule.product_tmpl_id and product.id != rule.product_tmpl_id.id:
                        continue
                    if rule.product_id and not (
                            product.product_variant_count == 1
                            and product.product_variant_ids[0].id
                            == rule.product_id.id):
                        # product rule acceptable on template if has only one variant
                        continue
                else:
                    if rule.product_tmpl_id and product.product_tmpl_id.id != rule.product_tmpl_id.id:
                        continue
                    if rule.product_id and product.id != rule.product_id.id:
                        continue

                if rule.categ_id:
                    cat = product.categ_id
                    while cat:
                        if cat.id == rule.categ_id.id:
                            break
                        cat = cat.parent_id
                    if not cat:
                        continue

                if rule.base == -1:
                    if rule.base_pricelist_id:
                        price_tmp, rule_ids_tmp = self._price_rule_get_multi(
                            cr,
                            uid,
                            rule.base_pricelist_id, [(product, qty, partner)],
                            context=context)[product.id]
                        ptype_src = rule.base_pricelist_id.currency_id.id
                        price_uom_id = qty_uom_id
                        price = currency_obj.compute(cr,
                                                     uid,
                                                     ptype_src,
                                                     pricelist.currency_id.id,
                                                     price_tmp,
                                                     round=False,
                                                     context=context)
                        rule_ids += rule_ids_tmp
                elif rule.base == -2:
                    seller = False
                    for seller_id in product.seller_ids:
                        if (not partner) or (seller_id.name.id != partner):
                            continue
                        seller = seller_id
                    if not seller and product.seller_ids:
                        seller = product.seller_ids[0]
                    if seller:
                        qty_in_seller_uom = qty
                        seller_uom = seller.product_uom.id
                        if qty_uom_id != seller_uom:
                            qty_in_seller_uom = product_uom_obj._compute_qty(
                                cr, uid, qty_uom_id, qty, to_uom_id=seller_uom)
                        price_uom_id = seller_uom
                        for line in seller.pricelist_ids:
                            if line.min_quantity <= qty_in_seller_uom:
                                price = line.price

                else:
                    if rule.base not in price_types:
                        price_types[rule.base] = price_type_obj.browse(
                            cr, uid, int(rule.base))
                    price_type = price_types[rule.base]

                    # price_get returns the price in the context UoM, i.e. qty_uom_id
                    price_uom_id = qty_uom_id
                    price = currency_obj.compute(
                        cr,
                        uid,
                        price_type.currency_id.id,
                        pricelist.currency_id.id,
                        product_obj._price_get(cr,
                                               uid, [product],
                                               price_type.field,
                                               context=context)[product.id],
                        round=False,
                        context=context)

                if price is not False:
                    price_limit = price
                    price = price * (1.0 + (rule.price_discount or 0.0))
                    if rule.price_round:
                        price = tools.float_round(
                            price, precision_rounding=rule.price_round)

                    convert_to_price_uom = (
                        lambda price: product_uom_obj._compute_price(
                            cr, uid, product.uom_id.id, price, price_uom_id))
                    if rule.price_surcharge:
                        price_surcharge = convert_to_price_uom(
                            rule.price_surcharge)
                        price += price_surcharge

                    if rule.price_min_margin:
                        price_min_margin = convert_to_price_uom(
                            rule.price_min_margin)
                        price = max(price, price_limit + price_min_margin)

                    if rule.price_max_margin:
                        price_max_margin = convert_to_price_uom(
                            rule.price_max_margin)
                        price = min(price, price_limit + price_max_margin)

                    rule_ids += [(price_limit, rule.id)]
                    break

            # Final price conversion to target UoM
            price = product_uom_obj._compute_price(cr, uid, price_uom_id,
                                                   price, qty_uom_id)

            results[product.id] = (price, rule_ids)
        return results
Exemplo n.º 28
0
 def validate_booking_order_line(self):
     repeat_list = []
     picking_obj = self.env['stock.picking']
     user_obj = self.env['res.users'].browse(self._uid)
     warehouse_id = self.env['stock.warehouse'].search(
         [('company_id', '=', user_obj.company_id.id)], limit=1)
     type_id = self.env['stock.picking.type'].search(
         [('warehouse_id', '=', warehouse_id[0].id),
          ('code', '=', 'outgoing')],
         limit=1)
     location_id = self.env['stock.location'].search(
         [('company_id', '=', user_obj.company_id.id),
          ('usage', '=', 'internal')],
         limit=1)
     location_dest_id = self.env['stock.location'].search(
         [('usage', '=', 'customer')], limit=1)
     for line_id in self.booking_order_line_ids:
         already_booked_product = line_id.search([
             ('product_id', '=', line_id.product_id.id),
             ('order_id', '!=', line_id.order_id.id),
             ('state', 'in', ['pending', 'out']),
         ])
         for exist_line_id in already_booked_product:
             if line_id.start_date >= exist_line_id.actual_start_date and line_id.start_date <= exist_line_id.actual_end_date:
                 raise Warning(
                     _('Product Already booked in order %s') %
                     exist_line_id.order_id.name)
             if line_id.end_date >= exist_line_id.actual_start_date and line_id.start_date <= exist_line_id.actual_end_date:
                 raise Warning(
                     _('Product Already booked in order %s') %
                     exist_line_id.order_id.name)
         for main in self.booking_order_line_ids:
             if main.id != line_id.id and main.id not in repeat_list:
                 if main.product_id == line_id.product_id:
                     repeat_list.append(main.id)
                     if line_id.start_date >= main.actual_start_date and line_id.start_date <= main.actual_end_date:
                         raise Warning(
                             _('You can not select same product for booked in same datetime'
                               ))
                     if line_id.end_date >= main.actual_start_date and line_id.start_date <= main.actual_end_date:
                         raise Warning(
                             _('You can not select same product for booked in same datetime'
                               ))
         # already_stock_picking_id = self.env['stock.picking'].search([('booking_order_id','=',line_id.order_id.id)])
         # stock_picking_id = False
         # if not already_stock_picking_id:
         #     stock_picking_id = self.env['stock.picking'].create({
         #         'partner_id':self.partner_id and self.partner_id.id or False,
         #         'picking_type_id': type_id.id or False,
         #         'location_id': location_id and location_id.id or False,
         #         'location_dest_id': location_dest_id and location_dest_id.id or False,
         #         'booking_order_id':line_id.order_id.id,
         #     })
         # self.env['stock.move'].create({
         #         'name': line_id.product_id.name,
         #         'product_id':line_id.product_id and line_id.product_id.id or False,
         #         'product_uom_qty':1,
         #         'product_uom': line_id.product_id and line_id.product_id.uom_id and line_id.product_id.uom_id.id or False,
         #         'location_id': location_id and location_id.id or False,
         #         'location_dest_id': location_dest_id and location_dest_id.id or False,
         #         'picking_id':stock_picking_id and stock_picking_id.id or already_stock_picking_id and already_stock_picking_id.id or False,
         #         })
         if line_id.order_id:
             line_id.state = 'pending'
             user_obj = self.env['res.users'].browse(self._uid)
             warehouse_id = self.env['stock.warehouse'].search(
                 [('company_id', '=', user_obj.company_id.id)], limit=1)
             outgoing_type_id = self.env['stock.picking.type'].search(
                 [('warehouse_id', '=', warehouse_id[0].id),
                  ('code', '=', 'outgoing')],
                 limit=1)
             incoming_type_id = self.env['stock.picking.type'].search(
                 [('warehouse_id', '=', warehouse_id[0].id),
                  ('code', '=', 'incoming')],
                 limit=1)
             out_stock_picking_id = picking_obj.search(
                 [('min_date', '=', line_id.start_date),
                  ('state', '=', 'draft'),
                  ('picking_type_id', '=', outgoing_type_id.id)],
                 limit=1)
             if not out_stock_picking_id:
                 out_stock_picking_id = line_id.order_id.create_stock_picking(
                     'do_out')
             in_stock_picking_id = picking_obj.search(
                 [('min_date', '=', line_id.end_date),
                  ('state', '=', 'draft'),
                  ('picking_type_id', '=', incoming_type_id.id)],
                 limit=1)
             if not in_stock_picking_id:
                 in_stock_picking_id = line_id.order_id.create_stock_picking(
                     'do_in')
             line_id.order_id.create_move_for_picking(
                 line_id, out_stock_picking_id, 'do_out')
             line_id.order_id.create_move_for_picking(
                 line_id, in_stock_picking_id, 'do_in')
         self.env['product.serial.number'].create({
             'product_id':
             line_id.product_id.id,
             'serial_no':
             line_id.product_id.serial_no,
             'booking_line_id':
             line_id.id,
             'booking_order_id':
             line_id.order_id.id,
             'actual_start_date':
             line_id.actual_start_date,
             'actual_end_date':
             line_id.actual_end_date,
         })
         line_id.state = 'pending'
         line_id.order_id.state = 'pending'
Exemplo n.º 29
0
 def _check_closing_date(self):
     if self.date_end < self.date_begin:
         raise Warning(
             _('Closing Date cannot be set before Beginning Date.'))
Exemplo n.º 30
0
    def _prepare_order_line_invoice_line(self,
                                         cr,
                                         uid,
                                         line,
                                         account_id=False,
                                         context=None):
        """Prepare the dict of values to create the new invoice line for a
           sales order line. This method may be overridden to implement custom
           invoice generation (making sure to call super() to establish
           a clean extension chain).

           :param browse_record line: sale.order.line record to invoice
           :param int account_id: optional ID of a G/L account to force
               (this is used for returning products including service)
           :return: dict of values to create() the invoice line
        """
        order = self.browse(cr, uid, line.id).order_id
        company = self.pool.get('res.company').browse(cr, uid,
                                                      order.company_id.id)
        res = {}
        if not line.invoiced:
            if not account_id:
                if line.product_id:
                    account_id = line.product_id.property_account_income.id
                    if not account_id:
                        account_id = line.product_id.categ_id.property_account_income_categ.id or company.property_account_income and company.property_account_income.id
                    if not account_id:
                        raise Warning(_('Error!'),
                                _('Please define income account for this product: "%s" (id:%d).') % \
                                    (line.product_id.name, line.product_id.id,))
                else:
                    prop = self.pool.get('ir.property').get(
                        cr,
                        uid,
                        'property_account_income_categ',
                        'product.category',
                        context=context)
                    account_id = prop and prop.id or False
            uosqty = self._get_line_qty(cr, uid, line, context=context)
            uos_id = self._get_line_uom(cr, uid, line, context=context)
            pu = 0.0
            if uosqty:
                pu = round(
                    line.price_unit * line.product_uom_qty / uosqty,
                    self.pool.get('decimal.precision').precision_get(
                        cr, uid, 'Product Price'))
            fpos = line.order_id.fiscal_position or False
            account_id = self.pool.get('account.fiscal.position').map_account(
                cr, uid, fpos, account_id)
            if not account_id:
                raise Warning(
                    _('Error!'),
                    _('There is no Fiscal Position defined or Income category account defined for default properties of Product categories.'
                      ))
            res = {
                'name':
                line.name,
                'sequence':
                line.sequence,
                'origin':
                line.order_id.name,
                'account_id':
                account_id,
                'price_unit':
                pu,
                'quantity':
                uosqty,
                'discount':
                line.discount,
                'uos_id':
                uos_id,
                'product_id':
                line.product_id.id or False,
                'invoice_line_tax_id': [(6, 0, [x.id for x in line.tax_id])],
                'account_analytic_id':
                line.order_id.project_id and line.order_id.project_id.id
                or False,
            }
        return res