コード例 #1
0
    def make_invoices(self, cr, uid, ids, context=None):
        """
        To make invoices.

             @param self: The object pointer.
             @param cr: A database cursor
             @param uid: ID of the user currently logged in
             @param ids: the ID or list of IDs
             @param context: A standard dictionary

             @return: A dictionary which of fields with values.

        """
        if context is None:
            context = {}
        ctx = context.copy()
        ctx['_partial_invoice'] = {}
        #res = False
        #        invoices = {}

        sales_order_line_obj = self.pool.get('sale.order.line')
        sales_order_obj = self.pool.get('sale.order')
        wf_service = netsvc.LocalService('workflow')
        partner_ids = []
        origin = []
        invoice_line_ids = []
        orders = []
        vals = {}
        order_lines = {}
        #    import ipdb; ipdb.set_trace()

        wiz = self.browse(cr, uid, ids, context)[0]

        for line_part in wiz.line_ids:
            line = line_part.sale_order_line_id
            partner = line.order_id.partner_id
            if not partner_ids:
                partner_ids.append(partner.id)
                vals['partner_id'] = line.order_id.partner_invoice_id.id
                vals['account_id'] = partner.property_account_receivable.id
                if partner.property_payment_term.id:
                    vals['pay_term'] = partner.property_payment_term.id
                else:
                    vals['pay_term'] = False
                vals[
                    'company_id'] = line.order_id.company_id and line.order_id.company_id.id or False
                vals['reference'] = "P%dSO%d" % (line.order_id.partner_id.id,
                                                 line.order_id.id)
                vals['currency_id'] = line.order_id.pricelist_id.currency_id.id
                vals[
                    'fiscal_position'] = line.order_id.fiscal_position.id or line.order_id.partner_id.property_account_position.id
                vals[
                    'user_id'] = line.order_id.user_id and line.order_id.user_id.id or False
            else:
                #TODO : to improve. Thise test should be in default_get
                if partner.id not in partner_ids:
                    raise osv.except_osv(
                        _('Attention!'),
                        _('Le client à facturer doit être le même dans toutes les lignes'
                          ))

            # if line_part.percent2invoice == 0 and line_part.amount2invoice == 0 :
            #     continue
            # if line_part.percent2invoice != 0 and line_part.amount2invoice != 0 :
            #     raise osv.except_osv(_('Attention!'), _('Vous avez renseigné un montant et un taux à facturer sur une même ligne. \n Ce n\'est pas possible'))

            sale_order = line_part.sale_order_line_id.order_id
            if sale_order.id not in order_lines:
                order_lines[sale_order.id] = []
            order_lines[sale_order.id].append(line_part.sale_order_line_id.id)
            ctx['_partial_invoice'][
                line_part.sale_order_line_id.id] = line_part.amount_final

            if (not line.invoiced) and (line.state not in ('draft', 'cancel')):
                if line.order_id not in orders:
                    orders.append(line.order_id)
                    origin.append(line.order_id.name)
                line_id = sales_order_line_obj.invoice_line_create(cr,
                                                                   uid,
                                                                   [line.id],
                                                                   context=ctx)
                for lid in line_id:
                    invoice_line_ids.append(lid)

        vals['origin'] = '-'.join(origin)
        vals['type'] = 'out_invoice'
        vals['invoice_line'] = [(6, 0, invoice_line_ids)]
        vals['date_invoice'] = fields.date.today()

        inv_id = self.pool.get('account.invoice').create(cr, uid, vals)
        _logger.info('created invoice %d', inv_id)
        for order in orders:
            #            res = make_invoice(order, il)
            cr.execute(
                'INSERT INTO sale_order_invoice_rel \
                    (order_id,invoice_id) values (%s,%s)', (order.id, inv_id))
            flag = True
            data_sale = sales_order_obj.browse(cr,
                                               uid,
                                               order.id,
                                               context=context)
            for line in data_sale.order_line:
                if not line.invoiced:
                    flag = False
                    break
            if flag:
                line.order_id.write({'state': 'progress'})
                wf_service.trg_validate(uid, 'sale.order', order.id,
                                        'all_lines', cr)

        if not invoice_line_ids:
            raise osv.except_osv(
                _('Warning!'),
                _('Invoice cannot be created for this Sales Order Line due to one of the following reasons:\n1.The state of this sales order line is either "draft" or "cancel"!\n2.The Sales Order Line is Invoiced!'
                  ))
        if context.get('open_invoices', False):
            return self.open_invoices(cr, uid, ids, inv_id, context=context)
        return {'type': 'ir.actions.act_window_close'}
コード例 #2
0
 def holidays_validate(self, cr, uid, ids, context=None):
     self.check_holidays(cr, uid, ids, context=context)
     obj_emp = self.pool.get('hr.employee')
     ids2 = obj_emp.search(cr, uid, [('user_id', '=', uid)])
     manager = ids2 and ids2[0] or False
     self.write(cr, uid, ids, {'state': 'validate'})
     data_holiday = self.browse(cr, uid, ids)
     for record in data_holiday:
         if record.double_validation:
             self.write(cr, uid, [record.id], {'manager_id2': manager})
         else:
             self.write(cr, uid, [record.id], {'manager_id': manager})
         if record.holiday_type == 'employee' and record.type == 'remove':
             meeting_obj = self.pool.get('crm.meeting')
             meeting_vals = {
                 'name':
                 record.name or _('Leave Request'),
                 'categ_ids':
                 record.holiday_status_id.categ_id
                 and [(6, 0, [record.holiday_status_id.categ_id.id])] or [],
                 'duration':
                 record.number_of_days_temp * 8,
                 'description':
                 record.notes,
                 'user_id':
                 record.user_id.id,
                 'date':
                 record.date_from,
                 'end_date':
                 record.date_to,
                 'date_deadline':
                 record.date_to,
                 'state':
                 'open',  # to block that meeting date in the calendar
             }
             meeting_id = meeting_obj.create(cr, uid, meeting_vals)
             self._create_resource_leave(cr, uid, [record], context=context)
             self.write(cr, uid, ids, {'meeting_id': meeting_id})
         elif record.holiday_type == 'category':
             emp_ids = obj_emp.search(
                 cr, uid,
                 [('category_ids', 'child_of', [record.category_id.id])])
             leave_ids = []
             for emp in obj_emp.browse(cr, uid, emp_ids):
                 vals = {
                     'name': record.name,
                     'type': record.type,
                     'holiday_type': 'employee',
                     'holiday_status_id': record.holiday_status_id.id,
                     'date_from': record.date_from,
                     'date_to': record.date_to,
                     'notes': record.notes,
                     'number_of_days_temp': record.number_of_days_temp,
                     'parent_id': record.id,
                     'employee_id': emp.id
                 }
                 leave_ids.append(self.create(cr, uid, vals, context=None))
             wf_service = netsvc.LocalService("workflow")
             for leave_id in leave_ids:
                 wf_service.trg_validate(uid, 'hr.holidays', leave_id,
                                         'confirm', cr)
                 wf_service.trg_validate(uid, 'hr.holidays', leave_id,
                                         'validate', cr)
                 wf_service.trg_validate(uid, 'hr.holidays', leave_id,
                                         'second_validate', cr)
     return True
コード例 #3
0
    def write(self, cr, uid, ids, vals, context=None):
        #print '----------SO-------------------'
        #print vals, context
        context = context or {}
        if type(ids) != type([]):
            ids = [ids]

        if not context:
            wf_service = netsvc.LocalService("workflow")
            for order in self.browse(cr, uid, ids, context=context):
                new_vals = vals
                if not order.ic_create:
                    if order.purchase_id:
                        if 'state' in vals:
                            if vals['state'] == 'cancel':
                                wf_service.trg_validate(
                                    1, 'purchase.order', order.purchase_id.id,
                                    'purchase_cancel', cr)
                            elif vals['state'] in [
                                    'progress', 'manual'
                            ] and self._need_to_update_intercompany_object(
                                    cr, uid, order.id, context=context):
                                wf_service.trg_validate(
                                    1, 'purchase.order', order.purchase_id.id,
                                    'purchase_confirm', cr)
                    else:
                        res = self._need_to_create_intercompany_object(
                            cr, uid, order.id, context=context)
                        if res:
                            ic_id = self._generate_po_from_so(cr,
                                                              1,
                                                              order,
                                                              res,
                                                              context=context)
                            wf_service.trg_validate(1, 'purchase.order', ic_id,
                                                    'purchase_confirm', cr)
                            new_vals.update({
                                'purchase_id': ic_id,
                            })
                super(sale_order, self).write(cr,
                                              uid, [order.id],
                                              new_vals,
                                              context=context)

        elif len(vals) <= 1 and ('message_follower_ids' in vals):
            super(sale_order, self).write(cr, uid, ids, vals, context=context)

        elif context.get('force_ic_checking', True):
            po_pool = self.pool.get('purchase.order')
            wf_service = netsvc.LocalService("workflow")
            for order in self.browse(cr, uid, ids, context=context):
                new_vals = vals
                if 'is_locked' in new_vals:
                    if order.purchase_id:
                        po_pool.write(cr,
                                      uid, [order.purchase_id.id], {
                                          'sale_id': False,
                                      },
                                      context={'force_ic_checking': False})
                    new_vals.update({
                        'purchase_id': False,
                    })
                    super(sale_order, self).write(cr,
                                                  uid, [order.id],
                                                  new_vals,
                                                  context=context)
                elif not order.is_locked:
                    if not order.ic_create:
                        if order.purchase_id:
                            if 'state' in vals:
                                if vals['state'] == 'cancel':
                                    wf_service.trg_validate(
                                        uid, 'purchase.order',
                                        order.purchase_id.id,
                                        'purchase_cancel', cr)
                                elif vals['state'] in [
                                        'progress', 'manual'
                                ] and self._need_to_update_intercompany_object(
                                        cr, uid, order.id, context=context):
                                    wf_service.trg_validate(
                                        uid, 'purchase.order',
                                        order.purchase_id.id,
                                        'purchase_confirm', cr)

                            else:
                                #print ">>>>>>>> CANCEL PO"
                                super(sale_order, self).write(cr,
                                                              1, [order.id],
                                                              vals,
                                                              context=context)
                                wf_service.trg_validate(
                                    1, 'purchase.order', order.purchase_id.id,
                                    'purchase_cancel', cr)
                                cr.execute(
                                    "SELECT id FROM res_company WHERE partner_id=%s",
                                    (order.partner_id.id, ))
                                company_to = cr.fetchone()[0]
                                ic_id = self._generate_po_from_so(
                                    cr, 1, order, company_to, context=context)
                                new_vals = {}
                                new_vals.update({
                                    'purchase_id': ic_id,
                                })
                        else:
                            res = self._need_to_create_intercompany_object(
                                cr, uid, order.id, context=context)
                            if res:
                                ic_id = self._generate_po_from_so(
                                    cr, 1, order, res, context=context)
                                wf_service.trg_validate(
                                    1, 'purchase.order', ic_id,
                                    'purchase_confirm', cr)
                                new_vals.update({
                                    'purchase_id': ic_id,
                                })
                    super(sale_order, self).write(cr,
                                                  uid, [order.id],
                                                  new_vals,
                                                  context=context)
                else:
                    raise osv.except_osv(
                        _('Invalid Action!'),
                        _('You can not update this Sales Order, because it is Locked by Inter-Company process.'
                          ))
        else:
            super(sale_order, self).write(cr, uid, ids, vals, context=context)
        return True
コード例 #4
0
    def write(self, cr, uid, ids, vals, context=None):
        #print '----------PO-------------------'
        #print vals, context
        context = context or {}
        if type(ids) != type([]):
            ids = [ids]

        if not context:
            wf_service = netsvc.LocalService("workflow")
            for order in self.browse(cr, uid, ids, context=context):
                new_vals = vals
                if not order.ic_create:
                    if order.sale_id:
                        if 'state' in vals:
                            if vals['state'] == 'cancel':
                                wf_service.trg_validate(
                                    1, 'sale.order', order.sale_id.id,
                                    'cancel', cr)
                            elif vals[
                                    'state'] == 'approved' and self._need_to_update_intercompany_object(
                                        cr, uid, order.id, context=context):
                                wf_service.trg_validate(
                                    1, 'sale.order', order.sale_id.id,
                                    'order_confirm', cr)
                    else:
                        res = self._need_to_create_intercompany_object(
                            cr, uid, order.id, context=context)
                        if res:
                            ic_id = self._generate_so_from_po(cr,
                                                              1,
                                                              order,
                                                              res,
                                                              context=context)
                            wf_service.trg_validate(1, 'sale.order', ic_id,
                                                    'order_confirm', cr)
                            new_vals.update({
                                'sale_id': ic_id,
                            })
                super(purchase_order, self).write(cr,
                                                  uid, [order.id],
                                                  new_vals,
                                                  context=context)

        elif len(vals) <= 1 and ('message_follower_ids' in vals):
            super(purchase_order, self).write(cr,
                                              uid,
                                              ids,
                                              vals,
                                              context=context)

        elif context.get('force_ic_checking', True):
            so_pool = self.pool.get('sale.order')
            wf_service = netsvc.LocalService("workflow")
            for order in self.browse(cr, uid, ids, context=context):
                new_vals = vals
                if 'is_locked' in new_vals:  #if unlocked object need to break the IC links
                    if order.sale_id:
                        so_pool.write(cr,
                                      uid, [order.sale_id.id], {
                                          'purchase_id': False,
                                      },
                                      context={'force_ic_checking': False})
                    new_vals.update({
                        'sale_id': False,
                    })
                    super(purchase_order, self).write(cr,
                                                      uid, [order.id],
                                                      new_vals,
                                                      context=context)

                elif not order.is_locked:  # when locked, warning
                    if not order.ic_create:  # if the PO has not been generated from a SO through IC process
                        if order.sale_id:  # already have a SO linked
                            if 'state' in vals:  # update linked SO state
                                if vals['state'] == 'cancel':
                                    wf_service.trg_validate(
                                        1, 'sale.order', order.sale_id.id,
                                        'cancel', cr)
                                elif vals[
                                        'state'] == 'approved' and self._need_to_update_intercompany_object(
                                            cr, uid, order.id,
                                            context=context):
                                    wf_service.trg_validate(
                                        1, 'sale.order', order.sale_id.id,
                                        'order_confirm', cr)

                            else:  # cancel and re-create linked SO
                                #print ">>>>>>>> CANCEL SO"
                                super(purchase_order,
                                      self).write(cr,
                                                  uid, [order.id],
                                                  vals,
                                                  context=context)
                                wf_service.trg_validate(
                                    1, 'sale.order', order.sale_id.id,
                                    'cancel', cr)
                                cr.execute(
                                    "SELECT id FROM res_company WHERE partner_id=%s",
                                    (order.partner_id.id, ))
                                company_to = cr.fetchone()[0]
                                ic_id = self._generate_so_from_po(
                                    cr, 1, order, company_to, context=context)
                                new_vals = {}
                                new_vals.update({
                                    'sale_id': ic_id,
                                })
                        else:
                            res = self._need_to_create_intercompany_object(
                                cr, uid, order.id, context=context)
                            if res:  # if must create linked SO when confirmed
                                ic_id = self._generate_so_from_po(
                                    cr, 1, order, res, context=context)
                                wf_service.trg_validate(
                                    1, 'sale.order', ic_id, 'order_confirm',
                                    cr)
                                new_vals.update({
                                    'sale_id': ic_id,
                                })
                    super(purchase_order, self).write(cr,
                                                      uid, [order.id],
                                                      new_vals,
                                                      context=context)
                else:
                    raise osv.except_osv(
                        _('Invalid Action!'),
                        _('You can not update this Purchase Order, because it is Locked by Inter-Company process.'
                          ))
        else:
            super(purchase_order, self).write(cr,
                                              uid,
                                              ids,
                                              vals,
                                              context=context)
        return True
コード例 #5
0
 def _wkf_calculate_records(self, cr, uid, ids, context=None):
     self._calculate_records(cr, uid, ids, context, recalculate=False)
     wf_service = netsvc.LocalService("workflow")
     wf_service.trg_validate(uid, 'l10n.es.aeat.mod340.report', ids
                             and ids[0], 'calculate', cr)
コード例 #6
0
    def _calculate_records(self, cr, uid, ids, context=None, recalculate=True):
        report_obj = self.pool['l10n.es.aeat.mod340.report']
        mod340 = report_obj.browse(cr, uid, ids)[0]
        invoices340 = self.pool['l10n.es.aeat.mod340.issued']
        invoices340_rec = self.pool['l10n.es.aeat.mod340.received']
        period_obj = self.pool['account.period']
        issued_obj = self.pool['l10n.es.aeat.mod340.tax_line_issued']
        received_obj = self.pool['l10n.es.aeat.mod340.tax_line_received']
        mod340.write({
            'state':
            'calculated',
            'calculation_date':
            time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
        })
        if not mod340.company_id.partner_id.vat:
            raise orm.except_orm(mod340.company_id.partner_id.name,
                                 _('This company dont have NIF'))
        wf_service = netsvc.LocalService("workflow")
        wf_service.trg_validate(uid, 'l10n.es.aeat.mod347.report', ids
                                and ids[0], 'calculate', cr)
        code = '340' + mod340.fiscalyear_id.code + ''
        code += mod340.period_to.date_stop[5:7] + '0001'
        account_period_ids = period_obj.build_ctx_periods(
            cr, uid, mod340.period_from.id, mod340.period_to.id)
        if len(account_period_ids) is 0:
            raise orm.except_orm(
                _('Error'),
                _("The periods selected don't belong to the fiscal year %s") %
                (mod340.fiscalyear_id.name))

        # Limpieza de las facturas calculadas anteriormente
        del_ids = invoices340.search(cr, uid, [('mod340_id', '=', mod340.id)])
        if del_ids:
            invoices340.unlink(cr, uid, del_ids, context=context)
        del_ids = invoices340_rec.search(cr, uid,
                                         [('mod340_id', '=', mod340.id)])
        if del_ids:
            invoices340_rec.unlink(cr, uid, del_ids, context=context)
        domain = [('period_id', 'in', account_period_ids),
                  ('state', 'in', ('open', 'paid'))]
        invoice_obj = self.pool['account.invoice']
        invoice_ids = invoice_obj.search(cr, uid, domain, context=context)
        for invoice in invoice_obj.browse(cr, uid, invoice_ids, context):
            include = False
            for tax_line in invoice.tax_line:
                if tax_line.base_code_id and tax_line.base:
                    if tax_line.base_code_id.mod340 is True:
                        include = True
            if include is True:
                if invoice.partner_id.vat_type == '1':
                    if not invoice.partner_id.vat:
                        raise orm.except_orm(
                            _('La siguiente empresa no tiene asignado nif:'),
                            invoice.partner_id.name)
                country_code, nif = (re.match(r"([A-Z]{0,2})(.*)",
                                              invoice.partner_id.vat).groups())
                values = {
                    'mod340_id': mod340.id,
                    'partner_id': invoice.partner_id.id,
                    'partner_vat': nif,
                    'representative_vat': '',
                    'partner_country_code': country_code,
                    'invoice_id': invoice.id,
                    'base_tax': invoice.amount_untaxed,
                    'amount_tax': invoice.amount_tax,
                    'total': invoice.amount_total,
                    'date_invoice': invoice.date_invoice,
                }
                if invoice.type in ['out_refund', 'in_refund']:
                    values['base_tax'] *= -1
                    values['amount_tax'] *= -1
                    values['total'] *= -1
                if invoice.type in ['out_invoice', 'out_refund']:
                    invoice_created = invoices340.create(cr, uid, values)
                if invoice.type in ['in_invoice', 'in_refund']:
                    invoice_created = invoices340_rec.create(cr, uid, values)
                tot_tax_invoice = 0
                check_tax = 0
                check_base = 0
                # Add the invoices detail to the partner record
                for tax_line in invoice.tax_line:
                    if tax_line.base_code_id and tax_line.base:
                        if tax_line.base_code_id.mod340:
                            tax_percentage = tax_line.amount / tax_line.base
                            values = {
                                'name': tax_line.name,
                                'tax_percentage': tax_percentage,
                                'tax_amount': tax_line.tax_amount,
                                'base_amount': tax_line.base_amount,
                                'invoice_record_id': invoice_created,
                            }
                            if invoice.type in ("out_invoice", "out_refund"):
                                issued_obj.create(cr, uid, values)
                            if invoice.type in ("in_invoice", "in_refund"):
                                received_obj.create(cr, uid, values)
                            tot_tax_invoice += tax_line.tax_amount
                            check_tax += tax_line.tax_amount
                            if tax_percentage >= 0:
                                check_base += tax_line.base_amount
                if invoice.type in ['out_invoice', 'out_refund']:
                    invoices340.write(cr, uid, invoice_created,
                                      {'amount_tax': tot_tax_invoice})
                if invoice.type in ['in_invoice', 'in_refund']:
                    invoices340_rec.write(cr, uid, invoice_created,
                                          {'amount_tax': tot_tax_invoice})
                sign = 1
                if invoice.type in ('out_refund', 'in_refund'):
                    sign = -1
                if str(invoice.amount_untaxed * sign) != str(check_base):
                    raise orm.except_orm(
                        "REVIEW INVOICE",
                        _('Invoice  %s, Amount untaxed Lines %.2f do not '
                          'correspond to AmountUntaxed on Invoice %.2f') %
                        (invoice.number, check_base,
                         invoice.amount_untaxed * sign))

        if recalculate:
            mod340.write({
                'state':
                'calculated',
                'calculation_date':
                time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
            })
        return True
コード例 #7
0
    def action_renew(self, cr, uid, ids, context=None):
        if context == None:
            context = {}
        # cr = pooler.get_db(cr.dbname).cursor()
        pawn_id = context.get('active_id')
        pawn_obj = self.pool.get('pawn.order')
        pawn = pawn_obj.browse(cr, uid, pawn_id, context=context)
        state_bf_redeem = pawn.state
        # Trigger workflow
        # Redeem the current one
        wf_service = netsvc.LocalService("workflow")
        wf_service.trg_validate(uid, 'pawn.order', pawn_id, 'order_redeem', cr)
        # Interest
        wizard = self.browse(cr, uid, ids[0], context)
        date = wizard.date_renew
        # Warning if today > date_due
        #         if pawn.date_due and pawn.date_due < time.strftime('%Y-%m-%d'):
        #             raise osv.except_osv(
        #                 _('Cannot renew!'),
        #                 _('Today is over grace period end date.\n'
        #                   'Please use normal sales process for expired items.'))
        # Normal case, redeem after pawned
        if state_bf_redeem != 'expire':
            interest_amount = wizard.pay_interest_amount
            discount = wizard.discount
            addition = wizard.addition
            # Register Actual Interest
            pawn_obj.register_interest_paid(cr,
                                            uid,
                                            pawn_id,
                                            date,
                                            discount,
                                            addition,
                                            interest_amount,
                                            context=context)
            # Reverse Accrued Interest
            pawn_obj.action_move_reversed_accrued_interest_create(
                cr, uid, [pawn_id], context=context)
            # Inactive Accrued Interest that has not been posted yet.
            pawn_obj.update_active_accrued_interest(cr,
                                                    uid, [pawn_id],
                                                    False,
                                                    context=context)
        else:
            # Special Case redeem after expired.
            # No register interest, just full amount as sales receipt.
            redeem_amount = wizard.pawn_amount + wizard.pay_interest_amount
            pawn_obj.action_move_expired_redeem_create(cr,
                                                       uid,
                                                       pawn.id,
                                                       redeem_amount,
                                                       context=context)
            # Overwrite state to 'expire' (Very special case0
            pawn_obj.write(cr,
                           uid, [pawn.id], {'state': 'expire'},
                           context=context)
            pawn_obj._update_order_pawn_asset(cr,
                                              uid, [pawn.id],
                                              {'state': 'expire'},
                                              context=context)
            # Immediately set to for sales
            item_obj = self.pool.get('product.product')
            asset_ids = item_obj.search(cr,
                                        uid, [('order_id', 'in', [pawn.id]),
                                              ('parent_id', '=', False)],
                                        context=context)
            context.update({'allow_for_sale': True})
            item_obj.action_asset_sale(cr, uid, asset_ids, context=context)
            # Create Sales receipt
            item_ids = item_obj.search(cr,
                                       uid, [('parent_id', '=', asset_ids[0])],
                                       context=context)
            wizard_obj = self.pool.get('pawn.item.create.receipt')
            wizard_id = wizard_obj.create(cr,
                                          uid, {
                                              'partner_id': pawn.partner_id.id,
                                              'item_ids': [(6, 0, item_ids)]
                                          },
                                          context=context)
            res = wizard_obj.pawn_item_create_receipt(cr,
                                                      uid, [wizard_id],
                                                      context=context)
            # Update amount
            voucher_id = res['res_id']
            self.pool.get('account.voucher').write(cr, uid, [voucher_id],
                                                   {'amount': redeem_amount})
            # Validate Receipt
            wf_service.trg_validate(uid, 'account.voucher', voucher_id,
                                    'proforma_voucher', cr)

        # Update Redeem Date too.
        pawn_obj.write(cr, uid, [pawn_id], {'date_redeem': date})
        # Create the new Pawn by copying the existing one.
        wizard = self.browse(cr, uid, ids[0], context)
        default = {'parent_id': pawn_id, 'date_order': wizard.date_renew}
        new_pawn_id = pawn_obj.copy(cr, uid, pawn_id, default, context=context)
        amount_net = wizard.increase_pawn_amount - wizard.pay_interest_amount
        pawn_obj.write(cr,
                       uid, [new_pawn_id], {
                           'parent_id': pawn_id,
                           'amount_pawned': wizard.new_pawn_amount,
                           'amount_net': amount_net
                       },
                       context=context)
        # Write new pawn back to the original
        pawn_obj.write(cr,
                       uid, [pawn_id], {'child_id': new_pawn_id},
                       context=context)
        # Commit
        # cr.commit()
        # cr.close()
        # Redirection
        return self.open_pawn_order(cr, uid, new_pawn_id, context=context)
コード例 #8
0
    def compute_refund(self, cr, uid, ids, mode='refund', context=None):
        """
        @param ids: the account invoice refund’s ID or list of IDs
        """
        wzd_brw = self.browse(cr, uid, ids[0], context=context)
        inv_obj = self.pool.get('account.invoice')
        reconcile_obj = self.pool.get('account.move.reconcile')
        account_m_line_obj = self.pool.get('account.move.line')
        mod_obj = self.pool.get('ir.model.data')
        act_obj = self.pool.get('ir.actions.act_window')
        wf_service = netsvc.LocalService('workflow')
        inv_tax_obj = self.pool.get('account.invoice.tax')
        inv_line_obj = self.pool.get('account.invoice.line')
        res_users_obj = self.pool.get('res.users')
        if context is None:
            context = {}
        for form in self.read(cr, uid, ids, context=context):
            created_inv = []
            date = False
            period = False
            description = False
            nroctrl = False
            company = res_users_obj.browse(cr, uid, uid,
                                           context=context).company_id
            journal_brw = form.get('journal_id', False)
            for inv in inv_obj.browse(cr,
                                      uid,
                                      context.get('active_ids'),
                                      context=context):
                if inv.state in ['draft', 'proforma2', 'cancel']:
                    raise osv.except_osv(
                        _('Error !'),
                        _('Can not %s draft/proforma/cancel invoice.') %
                        (mode))
                if inv.reconciled and mode in ('cancel', 'modify'):
                    raise osv.except_osv(
                        _('Error !'),
                        _('Can not %s invoice which is already reconciled,'
                          ' invoice should be unreconciled first. You can only'
                          ' Refund this invoice') % (mode))
                period = form.get('period') and form.get('period')[0] or False
                if not period:
                    # Take period from the current date
                    period = self.pool.get('account.period').find(
                        cr, uid, context=context)
                    period = period and period[0] or False
                    if not period:
                        raise osv.except_osv(
                            _('No Pediod Defined'),
                            _('You have been left empty the period field that'
                              ' automatically fill with the current period.'
                              ' However there is not period defined for the'
                              ' current company. Please check in'
                              ' Accounting/Configuration/Periods'))
                    self.write(cr,
                               uid,
                               ids, {'period': period},
                               context=context)

                if not journal_brw:
                    journal_id = inv.journal_id.id
                else:
                    journal_id = journal_brw[0]

                if form['date']:
                    date = form['date']
                    if not form['period']:
                        cr.execute("select name from ir_model_fields \
                                            where model = 'account.period' \
                                            and name = 'company_id'")
                        result_query = cr.fetchone()
                        if result_query:
                            cr.execute(
                                "select p.id "
                                "from account_fiscalyear y, account_period p "
                                "where y.id=p.fiscalyear_id and date(%s)"
                                " between p.date_start AND p.date_stop and"
                                " y.company_id = %s limit 1"
                                "", (
                                    date,
                                    company.id,
                                ))
                        else:
                            cr.execute(
                                """SELECT id
                                        from account_period where date(%s)
                                        between date_start AND  date_stop  \
                                        limit 1 """, (date, ))
                        res = cr.fetchone()
                        if res:
                            period = res[0]
                else:
                    # Take current date
                    # date = inv.date_invoice
                    date = time.strftime('%Y-%m-%d')
                if form['description']:
                    description = form['description']
                else:
                    description = inv.name

                if inv.type in ('in_invoice', 'in_refund'):
                    if form['nro_ctrl']:
                        nroctrl = form['nro_ctrl']
                    else:
                        raise osv.except_osv(
                            _('Control Number !'),
                            _('Missing Control Number on Invoice Refund!'))

                if not period:
                    raise osv.except_osv(_('Data Insufficient !'),
                                         _('No Period found on Invoice!'))

                refund_id = inv_obj.refund(cr, uid, [inv.id], date, period,
                                           description, journal_id)

                refund = inv_obj.browse(cr, uid, refund_id[0], context=context)
                # Add parent invoice
                cr.execute(
                    "update account_invoice set date_due='%s',nro_ctrl='%s',"
                    " check_total='%s', parent_id=%s where id =%s" %
                    (date, nroctrl, inv.check_total, inv.id, refund.id))
                inv_obj.button_compute(cr, uid, refund_id)

                created_inv.append(refund_id[0])
                if mode in ('cancel', 'modify'):
                    movelines = inv.move_id.line_id
                    to_reconcile_ids = {}
                    for line in movelines:
                        if line.account_id.id == inv.account_id.id:
                            to_reconcile_ids[line.account_id.id] = [line.id]
                        if not isinstance(line.reconcile_id,
                                          osv.orm.browse_null):
                            reconcile_obj.unlink(cr, uid, line.reconcile_id.id)
                    wf_service.trg_validate(uid, 'account.invoice', refund.id,
                                            'invoice_open', cr)

                    refund = inv_obj.browse(cr,
                                            uid,
                                            refund_id[0],
                                            context=context)
                    self.cn_iva_validate(cr, uid, refund, context=context)

                    for tmpline in refund.move_id.line_id:
                        if tmpline.account_id.id == inv.account_id.id:
                            to_reconcile_ids[tmpline.account_id.id].append(
                                tmpline.id)
                    for account in to_reconcile_ids:
                        account_m_line_obj.reconcile(
                            cr,
                            uid,
                            to_reconcile_ids[account],
                            writeoff_period_id=period,
                            writeoff_journal_id=inv.journal_id.id,
                            writeoff_acc_id=inv.account_id.id)
                if mode == 'modify':
                    invoice = inv_obj.read(
                        cr,
                        uid, [inv.id], [
                            'name', 'type', 'number',
                            'supplier_invoice_number', 'comment', 'date_due',
                            'partner_id', 'partner_insite', 'partner_contact',
                            'partner_ref', 'payment_term', 'account_id',
                            'currency_id', 'invoice_line', 'tax_line',
                            'journal_id', 'period_id'
                        ],
                        context=context)
                    invoice = invoice[0]
                    del invoice['id']
                    invoice_lines = inv_line_obj.browse(
                        cr, uid, invoice['invoice_line'], context=context)

                    invoice_lines = inv_obj._refund_cleanup_lines(
                        cr, uid, invoice_lines)
                    tax_lines = inv_tax_obj.browse(cr,
                                                   uid,
                                                   invoice['tax_line'],
                                                   context=context)
                    tax_lines = inv_obj._refund_cleanup_lines(
                        cr, uid, tax_lines)
                    # Add origin value
                    orig = self._get_orig(cr, uid, inv,
                                          invoice['supplier_invoice_number'],
                                          context)
                    invoice.update({
                        'type': inv.type,
                        'date_invoice': date,
                        'state': 'draft',
                        'number': False,
                        'invoice_line': invoice_lines,
                        'tax_line': tax_lines,
                        'period_id': period,
                        'name': description,
                        'origin': orig,
                    })
                    for field in ('partner_id', 'account_id', 'currency_id',
                                  'payment_term', 'journal_id'):
                        invoice[field] = invoice[field] and invoice[field][0]
                    inv_id = inv_obj.create(cr, uid, invoice, {})
                    if inv.payment_term.id:
                        data = inv_obj.onchange_payment_term_date_invoice(
                            cr, uid, [inv_id], inv.payment_term.id, date)
                        if 'value' in data and data['value']:
                            inv_obj.write(cr, uid, [inv_id], data['value'])
                    created_inv.append(inv_id)

                    new_inv_brw = inv_obj.browse(cr,
                                                 uid,
                                                 created_inv[1],
                                                 context=context)
                    inv_obj.write(cr,
                                  uid,
                                  created_inv[0], {
                                      'name': wzd_brw.description,
                                      'origin': new_inv_brw.origin
                                  },
                                  context=context)
                    inv_obj.write(cr,
                                  uid,
                                  created_inv[1], {
                                      'origin': inv.origin,
                                      'name': wzd_brw.description
                                  },
                                  context=context)
                if inv.type in ('out_invoice', 'out_refund'):
                    xml_id = 'action_invoice_tree3'
                    # if hasattr(inv, 'sale_ids'):
                    # for i in inv.sale_ids:
                    # cr.execute('insert into sale_order_invoice_rel
                    # (order_id,invoice_id) values (%s,%s)', (i.id,
                    # refund_id[0]))
                else:
                    xml_id = 'action_invoice_tree4'
                result = mod_obj.get_object_reference(cr, uid, 'account',
                                                      xml_id)
                xml_id = result and result[1] or False
                result = act_obj.read(cr, uid, xml_id, context=context)
                invoice_domain = ast.literal_eval(result['domain'])
                invoice_domain.append(('id', 'in', created_inv))
                result['domain'] = invoice_domain

                if wzd_brw.filter_refund == 'cancel':
                    orig = self._get_orig(cr, uid, inv,
                                          inv.supplier_invoice_number, context)
                    inv_obj.write(cr,
                                  uid,
                                  created_inv[0], {
                                      'origin': orig,
                                      'name': wzd_brw.description
                                  },
                                  context=context)

                elif wzd_brw.filter_refund == 'refund':
                    orig = self._get_orig(cr, uid, inv,
                                          inv.supplier_invoice_number, context)
                    inv_obj.write(cr,
                                  uid,
                                  created_inv[0], {
                                      'origin': inv.origin,
                                      'name': wzd_brw.description
                                  },
                                  context=context)
            return result
コード例 #9
0
 def initialize_workflow_instance(self, cr, uid, context=None):
     wf_service = netsvc.LocalService("workflow")
     line_ids = self.pool.get('mrp.production.workcenter.line').search(cr, uid, [], context=context)
     for line_id in line_ids:
         wf_service.trg_create(uid, 'mrp.production.workcenter.line', line_id, cr)
     return True
コード例 #10
0
ファイル: mrp_production.py プロジェクト: mbenyoub/server
    def action_produce(self,
                       cr,
                       uid,
                       production_id,
                       production_qty,
                       production_mode,
                       context=None):
        """ To produce final product based on production mode (consume/consume&produce).
        If Production mode is consume, all stock move lines of raw materials will be done/consumed.
        If Production mode is consume & produce, all stock move lines of raw materials will be done/consumed
        and stock move lines of final product will be also done/produced.
        @param production_id: the ID of mrp.production object
        @param production_qty: specify qty to produce
        @param production_mode: specify production mode (consume/consume&produce).
        @return: True
        
        ##Changed line, where comparing mrp.product.line and stock.move
        """
        stock_mov_obj = self.pool.get('stock.move')
        production = self.browse(cr, uid, production_id, context=context)

        produced_qty = 0
        for produced_product in production.move_created_ids2:
            if (produced_product.scrapped) or (produced_product.product_id.id
                                               != production.product_id.id):
                continue
            produced_qty += produced_product.product_qty
        if production_mode in ['consume', 'consume_produce']:
            consumed_data = {}

            # Calculate already consumed qtys
            for consumed in production.move_lines2:
                if consumed.scrapped:
                    continue
                if not consumed_data.get(consumed.product_id.id, False):
                    consumed_data[consumed.product_id.id] = 0
                consumed_data[consumed.product_id.id] += consumed.product_qty

            # Find product qty to be consumed and consume it
            for scheduled in production.product_lines:

                # total qty of consumed product we need after this consumption
                total_consume = ((production_qty + produced_qty) *
                                 scheduled.product_qty /
                                 production.product_qty)

                # qty available for consume and produce
                qty_avail = scheduled.product_qty - consumed_data.get(
                    scheduled.product_id.id, 0.0)

                if qty_avail <= 0.0:
                    # there will be nothing to consume for this raw material
                    continue

                raw_product = [
                    move for move in production.move_lines
                    if (move.product_id.id == scheduled.product_id.id
                        and move.product_qty == scheduled.product_qty)
                ]
                if raw_product:
                    # qtys we have to consume
                    qty = total_consume - consumed_data.get(
                        scheduled.product_id.id, 0.0)
                    if float_compare(qty,
                                     qty_avail,
                                     precision_rounding=scheduled.product_id.
                                     uom_id.rounding) == 1:
                        # if qtys we have to consume is more than qtys available to consume
                        prod_name = scheduled.product_id.name_get()[0][1]
                        raise osv.except_osv(
                            _('Warning!'),
                            _('You are going to consume total %s quantities of "%s".\nBut you can only consume up to total %s quantities.'
                              ) % (qty, prod_name, qty_avail))
                    if qty <= 0.0:
                        # we already have more qtys consumed than we need
                        continue

                    raw_product[0].action_consume(
                        qty, raw_product[0].location_id.id, context=context)

        if production_mode == 'consume_produce':
            # To produce remaining qty of final product
            #vals = {'state':'confirmed'}
            #final_product_todo = [x.id for x in production.move_created_ids]
            #stock_mov_obj.write(cr, uid, final_product_todo, vals)
            #stock_mov_obj.action_confirm(cr, uid, final_product_todo, context)
            produced_products = {}
            for produced_product in production.move_created_ids2:
                if produced_product.scrapped:
                    continue
                if not produced_products.get(produced_product.product_id.id,
                                             False):
                    produced_products[produced_product.product_id.id] = 0
                produced_products[produced_product.product_id.
                                  id] += produced_product.product_qty

            for produce_product in production.move_created_ids:
                produced_qty = produced_products.get(
                    produce_product.product_id.id, 0)
                subproduct_factor = self._get_subproduct_factor(
                    cr,
                    uid,
                    production.id,
                    produce_product.id,
                    context=context)
                rest_qty = (subproduct_factor *
                            production.product_qty) - produced_qty

                if rest_qty < production_qty:
                    prod_name = produce_product.product_id.name_get()[0][1]
                    raise osv.except_osv(
                        _('Warning!'),
                        _('You are going to produce total %s quantities of "%s".\nBut you can only produce up to total %s quantities.'
                          ) % (production_qty, prod_name, rest_qty))
                if rest_qty > 0:
                    stock_mov_obj.action_consume(
                        cr,
                        uid, [produce_product.id],
                        (subproduct_factor * production_qty),
                        context=context)

        for raw_product in production.move_lines2:
            new_parent_ids = []
            parent_move_ids = [x.id for x in raw_product.move_history_ids]
            for final_product in production.move_created_ids2:
                if final_product.id not in parent_move_ids:
                    new_parent_ids.append(final_product.id)
            for new_parent_id in new_parent_ids:
                stock_mov_obj.write(cr, uid, [raw_product.id],
                                    {'move_history_ids': [(4, new_parent_id)]})

        wf_service = netsvc.LocalService("workflow")
        wf_service.trg_validate(uid, 'mrp.production', production_id,
                                'button_produce_done', cr)
        return True
コード例 #11
0
    def implement_penalty(self, cr, uid, ids, context=None):
        """
        Create Record line in hr_allowance_deduction_exception object.
        
        @return: True
        """
        print "---------------------context", context
        degree_obj = self.pool.get('hr.salary.degree')
        bonuses_obj = self.pool.get('hr.salary.bonuses')
        process_obj = self.pool.get('hr.process.archive')
        employee_exception_line_obj = self.pool.get(
            'hr.allowance.deduction.exception')
        termination_pool = self.pool.get('hr.employment.termination')
        dismissal_pool = self.pool.get('hr.dismissal')
        wf_service = netsvc.LocalService("workflow")
        ref_process = ''

        for rec in self.browse(cr, uid, ids, context=context):
            for rec1 in rec.punishment_id:
                if rec1.penalty:
                    print "-----------------------penalty"
                    emp_line = {
                        'code': rec.employee_id.emp_code,
                        'employee_id': rec.employee_id.id,
                        'start_date': rec.start_date,
                        'end_date': rec.end_date,
                        'allow_deduct_id': rec1.allow_deduct.id,
                        'amount': rec.penalty_amount,
                        'types': 'deduct',
                        'action': 'special',
                    }
                    exception_id = employee_exception_line_obj.create(
                        cr, uid, emp_line, context=context)
                    ref_process = 'hr.allowance.deduction.exception' + ',' + str(
                        exception_id)
                if rec1.ref_process == 'termination':
                    dissmissal = dismissal_pool.search(
                        cr,
                        uid, [('punishment_id', '=', rec1.id)],
                        context=context)
                    if not dissmissal:
                        raise osv.except_osv(
                            _('Configuration Error'),
                            _("There is no dismissal reason linked to this punishment, kindly check  dismissal reason configurations!"
                              ))
                    id = termination_pool.create(
                        cr,
                        uid, {
                            'employee_id':
                            rec.employee_id.id,
                            'dismissal_date':
                            rec.decision_date,
                            'dismissal_type':
                            dissmissal[0],
                            'comments':
                            _('This employee has been dismiss according to accounting board decision for making %s violation'
                              ) % (rec.violation_id.name)
                        },
                        context=context)
                    ref_process = 'hr.employment.termination,%s' % (id, )
                    if context:
                        context.pop("default_type")
                        context.pop("default_operation_type")
                    termination_pool.termination(cr,
                                                 uid, [id],
                                                 context=context)
                    termination_pool.calculation(cr,
                                                 uid, [id],
                                                 False,
                                                 context=context)
                    termination_pool.transfer(cr, uid, [id], context=context)
                if rec1.ref_process == 'process':
                    print "---------------------process"
                    vals = {
                        'code': rec.employee_id.code,
                        'employee_id': rec.employee_id.id,
                        'date': rec.start_date,
                        'approve_date': time.strftime('%Y-%m-%d'),
                        'employee_salary_scale': rec.employee_id.payroll_id.id,
                        'comments': 'Punishment',
                    }
                    degree_id = degree_obj.search(
                        cr,
                        uid, [('sequence', '=',
                               rec.employee_id.degree_id.sequence + 1)],
                        context=context)

                    bonus_id = bonuses_obj.search(
                        cr,
                        uid, [('degree_id', 'in', degree_id)],
                        order='sequence',
                        limit=1,
                        context=context)
                    if not degree_id or not bonus_id:
                        raise orm.except_orm(
                            _('Warning'),
                            _('This Punishment Not possible: '
                              'Unable to determine the degre and bonus'))
                    vals.update({
                        'reference':
                        'hr.salary.degree' + ',' + str(degree_id[0]),
                        'previous':
                        rec.employee_id.degree_id.name,
                    })
                    process_id = process_obj.create(cr,
                                                    uid,
                                                    vals,
                                                    context=context)
                    vals.update({
                        'reference':
                        'hr.salary.bonuses' + ',' + str(bonus_id[0]),
                        'previous':
                        rec.employee_id.bonus_id.name,
                        'associated_id':
                        process_id
                    })
                    process_obj.create(cr, uid, vals, context=context)
                    wf_service.trg_validate(uid, 'hr.process.archive',
                                            process_id, 'approve', cr)
                    ref_process = 'hr.process.archive' + ',' + str(process_id)
                if rec1.ref_process in ('suspend', 'procedural_suspend'):
                    emp_obj = self.pool.get('hr.employee')
                    wf_service.trg_validate(uid, 'hr.employee',
                                            rec.employee_id.id, 'approve', cr)
                    emp_obj.write(cr, uid, [rec.employee_id.id],
                                  {'state': 'suspend'})
        return self.write(cr,
                          uid,
                          ids, {
                              'state': 'implement',
                              'ref_process': ref_process
                          },
                          context=context)
コード例 #12
0
    def create_from_ui(self, cr, uid, orders, context=None):
        #_logger.info("orders: %r", orders)
        order_ids = []
        for tmp_order in orders:
            print "********* archivo temporal data orden ************ ", tmp_order[
                'data']

            order = tmp_order['data']
            vals = {
                'name': order['name'],
                'user_id': order['user_id'] or False,
                'session_id': order['pos_session_id'],
                'lines': order['lines'],
                'pos_reference': order['name'],
            }
            if order.get('partner_id', False):
                vals['partner_id'] = order['partner_id'] or False

            order_id = self.create(cr, uid, vals, context)

            for payments in order['statement_ids']:
                payment = payments[2]

                # Valida que el pago a registrar no venga de un credito
                journal = self.pool.get('account.journal').browse(
                    cr, uid, payment['journal_id'], context=context)
                if journal.self_apply_credit:
                    continue

                self.add_payment(
                    cr,
                    uid,
                    order_id, {
                        'amount': payment['amount'] or 0.0,
                        'payment_date': payment['name'],
                        'statement_id': payment['statement_id'],
                        'payment_name': payment.get('note', False),
                        'journal': payment['journal_id']
                    },
                    context=context)

            if order['amount_return']:
                session = self.pool.get('pos.session').browse(
                    cr, uid, order['pos_session_id'], context=context)
                cash_journal = session.cash_journal_id
                cash_statement = False
                if not cash_journal:
                    cash_journal_ids = filter(
                        lambda st: st.journal_id.type == 'cash',
                        session.statement_ids)
                    if not len(cash_journal_ids):
                        raise osv.except_osv(
                            _('error!'),
                            _("No cash statement found for this session. Unable to record returned cash."
                              ))
                    cash_journal = cash_journal_ids[0].journal_id
                self.add_payment(
                    cr,
                    uid,
                    order_id, {
                        'amount': -order['amount_return'],
                        'payment_date': time.strftime('%Y-%m-%d %H:%M:%S'),
                        'payment_name': _('return'),
                        'journal': cash_journal.id,
                    },
                    context=context)
            order_ids.append(order_id)
            wf_service = netsvc.LocalService("workflow")
            wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
        return order_ids
コード例 #13
0
    def cancel_account_move(self, cr, uid, ids, context=None,
                            invoice_ids=False):
        '''
            Cancel invoices to delete account move
            @param invoice_ids, ids list of invoices to method apply
            @param ids, ids of wizard if called from this
        '''
        if context is None:
            context = {}
        invo_obj = self.pool.get('account.invoice')

        journal_obj = self.pool.get('account.journal')
        invo_ids = []
        iva_ids = []
        islr_ids = []
        journal_ids = []
        wf_service = netsvc.LocalService("workflow")
        print "context", context
        if not invoice_ids:
            invo_brw = self.browse(cr, uid, ids, context=context)
            invo_brw = invo_brw[0].invoice_ids
            for invo in invo_brw:
                invo_ids.append(invo.id)
                hasattr(invo, 'islr_wh_doc_id') and invo.islr_wh_doc_id and\
                    islr_ids.append(invo.islr_wh_doc_id.id)
                hasattr(invo, 'wh_iva_id') and invo.wh_iva_id and\
                    iva_ids.append(invo.wh_iva_id.id)
                invo.journal_id and journal_ids.append(invo.journal_id.id)

                hasattr(invo, 'islr_wh_doc_id') and invo.islr_wh_doc_id and\
                    invo.islr_wh_doc_id.journal_id and \
                    journal_ids.append(invo.islr_wh_doc_id.journal_id.id)

                hasattr(invo, 'wh_iva_id') and invo.wh_iva_id and \
                    invo.wh_iva_id.journal_id and \
                    journal_ids.append(invo.wh_iva_id.journal_id.id)

        else:
            invo_brw = invo_obj.browse(cr, uid, invoice_ids, context=context)
            for invo in invo_brw:
                invo_ids.append(invo.id)
                hasattr(invo, 'islr_wh_doc_id') and invo.islr_wh_doc_id and\
                    islr_ids.append(invo.islr_wh_doc_id.id)
                hasattr(invo, 'wh_iva_id') and invo.wh_iva_id and\
                    iva_ids.append(invo.wh_iva_id.id)
                invo.journal_id and journal_ids.append(invo.journal_id.id)

                hasattr(invo, 'islr_wh_doc_id') and invo.islr_wh_doc_id and\
                    invo.islr_wh_doc_id.journal_id and \
                    journal_ids.append(invo.islr_wh_doc_id.journal_id.id)

                hasattr(invo, 'wh_iva_id') and invo.wh_iva_id and\
                    invo.wh_iva_id.journal_id and \
                    journal_ids.append(invo.wh_iva_id.journal_id.id)

        hasattr(journal_obj.browse(cr, uid, journal_ids[0], context=context),
                'update_posted') and \
            journal_obj.write(cr, uid, journal_ids, {
                              'update_posted': True}, context=context)
        if invo_ids:
            if iva_ids and context.get('iva'):
                [cr.execute(
                    "update wkf_instance set state='active' where res_id =%s" %
                    i) for i in iva_ids]

                len(iva_ids) == 1 and wf_service.trg_validate(uid,
                            'account.wh.iva', iva_ids[0], 'cancel', cr) or \
                    [wf_service.trg_validate(
                     uid, 'account.wh.iva', i, 'cancel', cr) for i in iva_ids]

            if islr_ids and context.get('islr'):

                [cr.execute(
                    "update wkf_instance set state='active' where res_id =%s" %
                    i) for i in islr_ids]

                len(islr_ids) == 1 and wf_service.trg_validate(uid,
                            'islr.wh.doc', islr_ids[0], 'act_cancel', cr) or \
                    [wf_service.trg_validate(
                        uid, 'islr.wh.doc', i, 'act_cancel', cr)
                        for i in islr_ids]

            names = [invo.nro_ctrl for invo in invo_brw if invo.payment_ids]

            if names:
                raise osv.except_osv(_('Invalid action !'), _(
                    "Impossible invoice(s) cancel %s  because is/are paid!"
                    % (' '.join(names))))
            invo_obj.action_cancel(cr, uid, invo_ids, context=context)  # correccion estaba llegando tupla () al unlink
            invo_obj.write(cr, uid, invo_ids, {
                           'cancel_true': True}, context=context)
            hasattr(journal_obj.browse(cr, uid, journal_ids[0],
                                       context=context), 'update_posted') and \
                journal_obj.write(cr, uid, journal_ids, {
                                  'update_posted': False}, context=context)

        return True
コード例 #14
0
    def button_confirm_cash(self, cr, uid, ids, context=None):
        statement = self.browse(cr, uid, ids)[0]
        if statement.journal_id.is_cjc and context:
            wf_service = netsvc.LocalService("workflow")
            # invoiced = []
            uninvoiced = []
            for statement in self.browse(cr, uid, ids):
                for line in statement.line_ids:
                    # if line.invoice_id:
                    #     invoiced.append(line.invoice_id.id)
                    if not line.invoice_id and line.amount < 0:
                        uninvoiced.append(line)

            # for inv_id in invoiced:
            # wf_service.trg_validate(uid, 'account.invoice', inv_id, 'invoice_open', cr)

            journal = statement.journal_id
            minor_journal = journal.gastos_journal_id
            minor_partner = minor_journal.special_partner
            minor_product = minor_journal.special_product

            vals = {}
            vals.update({
                u'account_id':
                journal.default_credit_account_id.id,
                u'check_total':
                0,
                u'child_ids': [[6, False, []]],
                u'comment':
                "Gasto menor generado por caja chica",
                u'company_id':
                1,
                u'currency_id':
                journal.company_id.currency_id.id,
                u'date_due':
                False,
                u'date_invoice':
                statement.date,
                u'fiscal_position':
                minor_partner.property_account_position.id,
                u'internal_number':
                False,
                u'journal_id':
                minor_journal.id,
                u'message_follower_ids':
                False,
                u'message_ids':
                False,
                u'name':
                False,
                u'ncf_required':
                False,
                u'origin':
                statement.name,
                u'parent_id':
                False,
                u'partner_bank_id':
                False,
                u'partner_id':
                minor_partner.id,
                u'payment_term':
                False,
                u'period_id':
                statement.period_id.id,
                u'reference':
                False,
                u'reference_type':
                "02",
                u'supplier_invoice_number':
                False,
                u'tax_line': [],
                u'user_id':
                uid,
                u'pay_to':
                statement.journal_id.pay_to.id,
                u'invoice_line': []
            })
            if uninvoiced:
                if not minor_product.property_account_expense.id and statement.journal_id.is_cjc:
                    raise ValidationError(
                        u"En el diario de gasto menor seleccionado para esta caja chica "
                        u"el producto {} utilizado por defecto no tiene la cuenta de gasto asignada!"
                        .format(minor_product.name))
                line_ids = []

                for line in uninvoiced:
                    line.account_id = journal.default_credit_account_id
                    line_ids.append(line.id)
                    line_list = [0, False]
                    line_dict = {}
                    line_dict.update({
                        u'account_analytic_id':
                        False,
                        u'account_id':
                        minor_product.property_account_expense.id,
                        u'asset_category_id':
                        False,
                        u'discount':
                        0,
                        u'invoice_line_tax_id': [[
                            6, False,
                            [t.id for t in minor_product.supplier_taxes_id]
                        ]],
                        u'name':
                        line.name,
                        u'price_unit':
                        abs(line.amount),
                        u'product_id':
                        minor_product.id,
                        u'quantity':
                        1,
                        u'uos_id':
                        1
                    })
                    line_list.append(line_dict)
                    vals["invoice_line"].append(line_list)

                if statement.journal_id.is_cjc:
                    context = {
                        u'default_type': u'in_invoice',
                        u'journal_type': u'purchase',
                        u"minor": True
                    }
                inv_id = self.pool.get("account.invoice").create(
                    cr, uid, vals, context=context)
                inv = self.pool.get("account.invoice").browse(cr, uid, inv_id)
                inv.check_total = inv.amount_total
                wf_service.trg_validate(uid, 'account.invoice', inv_id,
                                        'invoice_open', cr)
                self.pool.get("account.bank.statement.line").write(
                    cr, uid, line_ids, {
                        "invoice_id": inv_id,
                        "partner_id": minor_partner.id,
                        "ref": inv.number
                    })

        res = super(account_cash_statement,
                    self).button_confirm_bank(cr, uid, ids, context=context)
        if statement.journal_id.is_cjc and context:
            for move in statement.move_line_ids:
                if move.credit > 0:
                    self.pool.get("account.move.line").write(
                        cr, uid, move.id,
                        {"partner_id": statement.journal_id.pay_to.id})

            for statement in self.browse(cr, uid, ids):
                for line in statement.line_ids:

                    number = line.invoice_id.number
                    account_id = line.account_id.id
                    partner_id = line.partner_id.id
                    cjc_journal = line.journal_id.id
                    inv_journal = line.invoice_id.journal_id.id
                    move_line_ids = []
                    move_line_ids += self.pool.get("account.move.line").search(
                        cr, uid, [('ref', '=', number),
                                  ('account_id', '=', account_id),
                                  ('partner_id', '=', partner_id),
                                  ('journal_id', '=', cjc_journal),
                                  ('debit', '>', 0)])
                    move_line_ids += self.pool.get("account.move.line").search(
                        cr, uid, [('ref', '=', number),
                                  ('account_id', '=', account_id),
                                  ('partner_id', '=', partner_id),
                                  ('journal_id', '=', inv_journal),
                                  ('credit', '>', 0)])

                    try:
                        self.pool.get("account.move.line.reconcile"
                                      ).trans_rec_reconcile_full(
                                          cr, uid, ids,
                                          {"active_ids": move_line_ids})
                    except except_orm as e:
                        if e.value.startswith("El apunte ya est"):
                            pass
                        else:
                            raise e

        return res
コード例 #15
0
    def action_confirm_mrp_production_order(self, cr, uid, ids, context=None):
        """ Write confirmed weight
        """
        if context is None:
            context = {}

        wiz_proxy = self.browse(
            cr, uid, ids, context=context)[0]
        current_lavoration_id = context.get("active_id", 0)

        # ---------------------------------------------------------------------
        #                          Initial setup:
        # ---------------------------------------------------------------------
        # get parameters
        parameter = self.get_parameter(cr, uid, context=context)
        wf_service = netsvc.LocalService("workflow")
        error_prefix = "#ERR"  # TODO configuration area?

        # Interchange file:
        file_cl, file_cl_upd, file_sl = self.get_interchange_files(
            cr, uid, parameter, context=context)

        # XMLRPC server:
        mx_server = self.get_xmlrpc_server(cr, uid, parameter, context=context)

        # ---------------------------------------------------------------------
        #                               Load pool
        # ---------------------------------------------------------------------
        lavoration_pool = self.pool.get("mrp.production.workcenter.line")
        product_pool = self.pool.get('product.product')
        load_pool = self.pool.get('mrp.production.workcenter.load')

        lavoration_browse = lavoration_pool.browse(
            cr, uid, current_lavoration_id, context=context)

        # Only if not to close have a partial or fully load:
        # 1. First close: all material are unloaded from stock accounting
        # 2. From second to last: all product are loaded with unload package
        # 3. Last: also correct product price
        if wiz_proxy.state == 'product':
            # -----------------------------------------------------------------
            #                      CL  (lavoration load)
            # -----------------------------------------------------------------
            # Verify that if is the last load no lavoration are open:
            if not wiz_proxy.partial:
                for l in lavoration_browse.production_id.workcenter_lines:
                    if l.state not in ('done', 'cancel'):  # not closed
                        raise osv.except_osv(
                            _('Last lavoration:'),
                            _('When is the last lavoration all lavoration must be in closed state!'))
            if lavoration_browse.production_id.accounting_state in ('cancel'):
                raise osv.except_osv(
                    _('Production error:'),
                    _('Could not add other extra load (production cancelled)!')
                )
            if wiz_proxy.package_id and not wiz_proxy.ul_qty:
                raise osv.except_osv(
                    _('Package error:'),
                    _('If package is present quantity is mandatory!'))
            if wiz_proxy.pallet_product_id and not wiz_proxy.pallet_qty:
                raise osv.except_osv(
                    _('Pallet error:'),
                    _('If pallet is present quantity is mandatory!'))

            # Create movement in list:
            product_qty = wiz_proxy.real_product_qty or 0.0
            wrong = wiz_proxy.wrong
            recycle = wiz_proxy.recycle
            recycle_product_id = wiz_proxy.recycle_product_id
            package_id = wiz_proxy.package_id.id \
                if wiz_proxy.package_id else False
            price = 0.0
            # TODO create a function for compute: sum ( q. x std. cost)
            load_id = load_pool.create(cr, uid, {
                'product_qty': product_qty, # only the wrote total
                'line_id': lavoration_browse.id,
                'partial': wiz_proxy.partial,
                'package_id': package_id,
                'ul_qty': wiz_proxy.ul_qty,
                'pallet_product_id':
                    wiz_proxy.pallet_product_id.id
                    if wiz_proxy.pallet_product_id else False,
                'pallet_qty': wiz_proxy.pallet_qty or 0.0,
                'recycle': recycle,
                'recycle_product_id':
                    recycle_product_id.id
                    if recycle_product_id else False,
                'wrong': wrong,
                'wrong_comment': wiz_proxy.wrong_comment,
            })
            # TODO crearla in funzione della produzione
            sequence = load_pool.browse(
                cr, uid, load_id, context=context).sequence
            # reload record for get sequence value

            # TODO manage recycle product!!!!! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

            # [(1)Famiglia-(6)Prodotto-(1).Pezzatura-(1)Versione]-
            # [(5)Partita-#(2)SequenzaCarico]-[(10)Imballo]
            product_code = "%-8s%-2s%-10s%-10s" % (
                wiz_proxy.product_id.default_code,  # Product code
                lavoration_browse.workcenter_id.code[:2],  # Workcenter
                "%06d#%01d" % (
                    int(lavoration_browse.production_id.name[3:]),
                    sequence,
                ),    # Job <<<< TODO use production (test, production is 5)
                wiz_proxy.package_id.code if package_id else "",  # Package
            )
            load_pool.write(cr, uid, load_id, {
                'product_code': product_code}, context=context)

            # Write load on accounting:
            # TODO potrebbe generare problemi se annullassero carichi o cose
            # del genere!!!
            # Better: reload from dbmirror (but in real time)
            # Now update accounting_qty on db for speed up
            product_pool.write(
                cr, uid, lavoration_browse.production_id.product_id.id,
                {'accounting_qty': (
                    lavoration_browse.production_id.product_id.accounting_qty or 0.0) + (wiz_proxy.real_product_qty or 0.0),
            }, context=context)

            # Export CL for product with new generated code:
            try:
                f_cl = open(file_cl, "w")
            except:
                raise osv.except_osv(
                    _('Transit file!'),
                    _('Problem accessing file: %s (maybe open in accounting program)!') % file_cl)

            if wrong: # if wrong new code is generated ((recycle code = code with R in 8th position)
                f_cl.write("%-35s%10.2f%10.2f\r\n" % (
                    "%sR%s" % (product_code[:7],
                    product_code[8:]),
                    product_qty,
                    price))
            else:
                f_cl.write("%-35s%10.2f%10.2f\r\n" % (
                    product_code, product_qty, price))

            # TODO mode in product (end movement)
            convert_load_id = {}  # list for convert CL code in load.id
            # for load in lavoration_browse.load_ids:

            # -----------------------------------------------------
            # Export SL form package/pallet used in loaded products
            # -----------------------------------------------------
            if wiz_proxy.package_id and wiz_proxy.ul_qty:
                f_cl.write(
                    "%-10s%-25s%10.2f%-10s\r\n" % (  # TODO 10 extra space
                        wiz_proxy.package_id.linked_product_id.default_code,
                        " " * 25,  # lavoration_browse.name[4:],
                        - wiz_proxy.ul_qty,
                        lavoration_browse.accounting_sl_code,
                        # " " * 10, # no value
                    ))
            else:
                pass  # TODO raise error if no package? (no if wrong!)
            if wiz_proxy.pallet_product_id and wiz_proxy.pallet_qty:
                f_cl.write(
                    "%-10s%-25s%10.2f%-10s\r\n" % ( # TODO 10 extra space
                        wiz_proxy.pallet_product_id.default_code,
                        " " * 25,  # lavoration_browse.name[4:],
                        - wiz_proxy.pallet_qty,
                        lavoration_browse.accounting_sl_code,
                        # " " * 10, # no value
                    ))
            else:
                pass
            f_cl.close()

            # -----------------------------------------------------------------
            #                         Load CL for product
            # -----------------------------------------------------------------
            try:
                if parameter.production_demo:  # Demo mode:
                    accounting_cl_code = 'DEMOCL000'
                else:
                    try:
                        accounting_cl_code = mx_server.sprix("CL")
                    except:
                        raise osv.except_osv(
                            _('Import CL error!'),
                            _('XMLRPC error calling import CL procedure'), )

                    # test if there's an error during importation:
                    # stat with: #ERR
                    if accounting_cl_code.startswith(error_prefix):
                        raise osv.except_osv(
                            _('Import CL error!'),
                            _('Error from accounting:\n%s') %
                            accounting_cl_code[len(error_prefix):],
                        )

                error = (
                    _('Update OpenERP with CL error!'),
                    _('Cannot write in OpenERP CL number for this load!'),
                )
                load_pool.write(cr, uid, load_id, {'accounting_cl_code': accounting_cl_code, }, context=context)

                # --------------------------------
                # Update lavoration with new info:
                # --------------------------------
                # TODO portare l'informazione sulla produzione qui non ha più
                # senso con i carichi sballati
                total = 0.0  # net production total

                # Partial (calculated every load on all production)
                for l in lavoration_browse.production_id.workcenter_lines:
                    for partial in l.load_ids:
                        total += partial.product_qty or 0.0

                # TODO togliere i commenti nei log e metterli magari nella
                # lavorazione per sapere come sono stati calcolati
                _logger.info(_("Production real total: %s") % (total, ))
                # data = {'real_product_qty': total}

                # Last unload document (extra op. needed)
                if not wiz_proxy.partial:
                    # TODO togliere il load_confirmed
                    # data['load_confirmed'] = True
                    # No other loads are permitted!
                    # ---------------------------------------------------------
                    #                     CL update price file
                    # ---------------------------------------------------------
                    try:
                        f_cl_upd = open(file_cl_upd, "w")
                    except:
                        raise osv.except_osv(
                            _('Transit file!'),
                            _('Problem accessing file: %s (maybe open in accounting program)!') % (
                                file_cl_upd))
                    unload_cost_total = 0.0

                    # ------------------
                    # Lavoration K cost:
                    # ------------------
                    try:
                        cost_line = lavoration_browse.workcenter_id.\
                                        cost_product_id.standard_price or 0.0
                    except:
                        cost_line = 0.0

                    if not cost_line:
                        raise osv.except_osv(
                            _('Calculate lavoration cost!'),
                            _('Error calculating lavoration cost, verifiy if the workcenter has product linked'), )

                    unload_cost_total = cost_line * total
                    _logger.info(_("Lavoration %s [%s]") % (
                        cost_line, unload_cost_total, ))

                    # ----------------------------------------------
                    # All unload cost of materials (all production):
                    # ----------------------------------------------
                    for lavoration in lavoration_browse.production_id.workcenter_lines:
                        for unload in lavoration.bom_material_ids:
                            try:
                                unload_cost_total += unload.product_id.standard_price * unload.quantity
                            except:
                                _logger.error(_("Error calculating unload lavoration"))
                    _logger.info(_("With materials [%s]") % (unload_cost_total, ))

                    # ------------------------------
                    # All unload package and pallet:
                    # ------------------------------
                    for l in lavoration_browse.production_id.workcenter_lines:
                        for load in l.load_ids:
                            try:
                                # Package:
                                if load.package_id: # there's pallet
                                    unload_cost_total += \
                                        load.package_id.linked_product_id.standard_price * load.ul_qty
                                    _logger.info(_("Package cost %s [%s]") % (
                                        load.package_id.linked_product_id.standard_price,
                                        load.ul_qty,
                                    ))
                            except:
                                _logger.error(_("Error calculating package price"))

                            try:
                                # Pallet:
                                if load.pallet_product_id:  # there's pallet
                                    unload_cost_total += load.pallet_product_id.standard_price * load.pallet_qty
                                    _logger.info(_("Pallet cost %s [%s]") % (
                                        load.pallet_product_id.standard_price,
                                        load.pallet_qty,
                                    ))
                            except:
                                _logger.error(_("Error calculating pallet price"))

                    unload_cost = unload_cost_total / total
                    _logger.info(_("With package  %s [unit.: %s]") % (
                        unload_cost_total, unload_cost, ))

                    # Update all production with value calculated: #TODO serve?
                    for l in lavoration_browse.production_id.workcenter_lines:
                        for load in l.load_ids:
                            load_pool.write(cr, uid, load.id, {
                                'accounting_cost': unload_cost * load.product_qty,
                            }, context=context)

                            # Export CL for update product price:
                            if not load.accounting_cl_code:
                                raise osv.except_osv(
                                    _('CL list!'),
                                    _('Error CL without number finded!'), )

                            accounting_cl_code = load.accounting_cl_code.strip()
                            f_cl_upd.write(
                                "%-6s%10.5f\r\n" % (
                                    accounting_cl_code,
                                    unload_cost, ), # unit
                                )
                            convert_load_id[accounting_cl_code] = load.id
                            # TODO problema con il file di ritorno !!!!!!!!!!!!!!!

                    # Temporary update accounting_qty on db for speed up (till new synd for product state with correct value)
                    # TODO Verificare perchè dovrebbe essere già stato tolto alla creazione della CL!!
                    #product_pool.write(cr, uid, unload.product_id.id, {'accounting_qty':(unload.accounting_qty or 0.0) - (unload.quantity or 0.0),}, context=context)
                    # TODO Vedere per scarico imballaggi
                    f_cl_upd.close()

                    # ---------------------------------------------------------
                    #                   CL update for product cost
                    # ---------------------------------------------------------
                    error = (
                        _('Update CL error!'),
                        _('XMLRPC for calling update CL method'), )

                    if not parameter.production_demo: # Demo mode:
                        res_list = mx_server.sprix("CLW") # testare per verificare i prezzi   >>> list of tuple [(1000, True),(2000, False)] >> (cl_id, updated)
                        if not res_list:
                            raise osv.except_osv(
                                _('Update CL price error!'),
                                _('Error launchind update CL price command'),
                            )
                        error = (
                            _('Update loaded CL price error!'),
                            _('Error during confirm the load or price for product in accounting program!'),
                        )
                        for (key, res) in res_list:
                            load_id = convert_load_id[key]
                            if res:  # if True update succesfully
                                load_pool.write(
                                    cr, uid, load_id,
                                    {'accounting_cost_confirmed': True},
                                    context=context)
                            else:
                                pass  # TODO raise error?

                    # ---------------------------------------------------------
                    #            Real workflow operation (only last load)
                    # ---------------------------------------------------------
                    # TODO Non occorre più verificare togliee questa parte:
                    # Close production order:
                    # if lavoration_browse.production_id.accounting_state in ('draft', 'production'):
                    #    if lavoration_browse.production_id.accounting_state in ('production'):
                    #        all_closed = True
                    #        for lavoration in lavoration_browse.production_id.workcenter_lines:
                    #            if lavoration.state not in ('done','cancel'):
                    #                all_closed = False
                    #                break
                    #        if all_closed:
                    wf_service.trg_validate(
                        uid, 'mrp.production',
                        lavoration_browse.production_id.id,
                        'trigger_accounting_close',
                        cr)

                # togliere: scriveva il totale carito e il load_confirmed
                #lavoration_pool.write(cr, uid, [lavoration_browse.id], data, context=context)
            except:
                raise osv.except_osv(_("Generic error"), "%s" % (sys.exc_info(), )) #error[0], "%s [%s]" % (error[1], sys.exc_info()) )

        else:  # state == 'material' >> unload all material and package:
            # -----------------------------------------------------------------
            #                              SL Document
            # -----------------------------------------------------------------
            try:  # SL file:
                f_sl = open(file_sl, "w")

                for unload in lavoration_browse.bom_material_ids:
                    # Export SL for material used for entire production:
                    f_sl.write("%-10s%-25s%10.2f\r\n" % (
                        unload.product_id.default_code,
                        lavoration_browse.name[4:],
                        unload.quantity))
                    try:
                        # Now update accounting_qty on db for speed up
                        product_pool.write(cr, uid, [unload.product_id.id], {
                            'accounting_qty': (unload.product_id.accounting_qty or 0.0) - (unload.quantity or 0.0), },
                        context=context)
                    except:
                        pass  # no error raise if problems
                f_sl.close()
            except:
                raise osv.except_osv(
                    _('Transit file SL:'),
                    _('Problem accessing file: %s (maybe open in accounting program or error during export)!') % (file_sl),
                )

            # -----------------------------------------------------------------
            #                      XMLRPC call for import SL
            # -----------------------------------------------------------------
            try: # an error here could mean that the document is created in accounting program #TODO manage this problem
                if parameter.production_demo:
                    accounting_sl_code = "DEMOSL000"
                else:
                    # ---------------------------------------------------------
                    #               SL for material and package
                    # ---------------------------------------------------------
                    try:
                        accounting_sl_code = mx_server.sprix("SL")
                    except:
                        raise osv.except_osv(
                        _('Import SL error!'),
                        _('XMLRPC error calling import SL procedure'), )

                    # Test if there's an error during importation:
                    if accounting_sl_code.startswith(error_prefix): #  stat with: #ERR
                        raise osv.except_osv(
                            _('Import SL error!'),
                            _('Error from accounting:\n%s') % (
                                accounting_sl_code[4:], ))

                error = (
                    _('Update SL error!'),
                    _('Error updating yet created SL link in OpenERP'),
                )
                lavoration_pool.write(
                    cr, uid, [current_lavoration_id],
                    {
                        'accounting_sl_code': accounting_sl_code,
                        'unload_confirmed': True,
                        # TODO non dovrebbe più servire # Next "confirm" is for prod.
                    },
                    context=context)

                try:  # If not error till now close WF for this lavoration:
                    wf_service.trg_validate(
                        uid, 'mrp.production.workcenter.line',
                        current_lavoration_id, 'button_done', cr)
                except:
                    raise osv.except_osv(
                    _('Workflow error:'),
                    _('Error closing lavoration!'), )
            except:
                raise osv.except_osv(*error)
        return {'type': 'ir.actions.act_window_close'}