Exemplo n.º 1
0
    def create_financial_claim(self, cr, uid, ids, context=None):
        """ 
        Workflow function to create a financial claim and change 
        state to done.
 
        @return: Boolean True
        """
        cost = 0.0
        account_journal_obj = self.pool.get('account.journal')
        account_obj = self.pool.get('account.account')
        voucher_obj = self.pool.get('account.voucher')
        voucher_line_obj = self.pool.get('account.voucher.line')
        affairs_account_obj = self.pool.get('admin_affairs.account')
        affairs_model_obj = self.pool.get('admin.affairs.model')
        for hotel_record in self.browse(cr, uid, ids, context=context):
            affairs_model_ids = affairs_model_obj.search(
                cr, uid, [('model', '=', 'hotel.service')], context=context)
            affairs_account_ids = affairs_account_obj.search(
                cr,
                uid, [('model_id', '=', affairs_model_ids[0])],
                context=context)
            if not affairs_account_ids:
                raise osv.except_osv(
                    _('Error'),
                    _("Please enter the hotel service accounting configuration"
                      ))
            affairs_account = affairs_account_obj.browse(
                cr, uid, affairs_account_ids[0], context=context)
            journal_ids = account_journal_obj.search(
                cr,
                uid, [('company_id', '=', hotel_record.company_id.id),
                      ('name', '=', hotel_record.jou_cat)],
                context=context)
            journal_id = journal_ids and journal_ids[
                0] or affairs_account.journal_id.id
            order = hotel_record.service_type
            # Creating Voucher / Ratitication
            voucher_id = voucher_obj.create(
                cr,
                uid,
                {
                    'amount':
                    hotel_record.cost,
                    #'amount_in_word':amount_to_text_ar(hotel_record.cost),
                    'type':
                    'ratification',
                    'date':
                    time.strftime('%Y-%m-%d'),
                    'partner_id':
                    hotel_record.partner_id.id,
                    'account_id':
                    hotel_record.partner_id.property_account_payable.id,
                    'journal_id':
                    journal_id,
                    'department_id':
                    hotel_record.department_id.id,
                    'state':
                    'draft',
                    'notes':
                    hotel_record.notes,
                    'narration':
                    'Hotel service No : '
                },
                context={})
            for order_record in order:
                account_ids = account_obj.search(
                    cr,
                    uid, [('company_id', '=', hotel_record.company_id.id),
                          ('code', '=', str(order_record.catg_id.code))],
                    context=context)
                account_id = account_ids[0]
                # Creating Voucher / Ratitication
                voucher_line_dict = {
                    'voucher_id':
                    voucher_id,
                    'account_analytic_id':
                    hotel_record.department_id.analytic_account_id.id,
                    'amount':
                    order_record.cost_service,
                    'type':
                    'dr',
                    'journal_id':
                    journal_id,
                    'name':
                    order_record.name,
                }
                if account_id:
                    voucher_line_dict.update({'account_id': account_id})
                voucher_line_obj.create(cr,
                                        uid,
                                        voucher_line_dict,
                                        context=context)
            #################### update workflow state###############
            voucher_state = 'draft'
            if hotel_record.company_id.affairs_voucher_state:
                voucher_state = hotel_record.company_id.affairs_voucher_state
            if voucher_id:
                wf_service = netsvc.LocalService("workflow")
                wf_service.trg_validate(uid, 'account.voucher', voucher_id,
                                        voucher_state, cr)
                voucher_obj.write(
                    cr, uid, voucher_id, {
                        'type': 'ratification',
                        'ratification': True,
                        'state': voucher_state
                    }, context)
            # Selecting Voucher Number / Refernece
            #voucher_number = voucher_obj.browse(cr,uid,voucher_id,context=context).number
            self.write(cr,
                       uid,
                       hotel_record.id, {
                           'state': 'done',
                           'voucher_no': voucher_id
                       },
                       context=context)
            copy_attachments(self, cr, uid, [hotel_record.id], 'hotel.service',
                             voucher_id, 'account.voucher', context)
        return True
Exemplo n.º 2
0
    def run(self, cr, uid, ids, context={}):
        logger = netsvc.Logger()
        for action in self.browse(cr, uid, ids, context):
            obj_pool = self.pool.get(action.model_id.model)
            obj = obj_pool.browse(cr,
                                  uid,
                                  context['active_id'],
                                  context=context)
            cxt = {
                'context': context,
                'object': obj,
                'time': time,
                'cr': cr,
                'pool': self.pool,
                'uid': uid
            }
            expr = eval(str(action.condition), cxt)
            if not expr:
                continue

            if action.state == 'client_action':
                if not action.action_id:
                    raise osv.except_osv(
                        _('Error'), _("Please specify an action to launch !"))
                return self.pool.get(action.action_id.type)\
                    .read(cr, uid, action.action_id.id, context=context)

            if action.state == 'code':
                if config['server_actions_allow_code']:
                    localdict = {
                        'self': self.pool.get(action.model_id.model),
                        'context': context,
                        'time': time,
                        'ids': ids,
                        'cr': cr,
                        'uid': uid,
                        'object': obj,
                        'obj': obj,
                    }
                    eval(action.code, localdict, mode="exec")
                    if 'action' in localdict:
                        return localdict['action']
                else:
                    netsvc.Logger().notifyChannel(
                        self._name, netsvc.LOG_ERROR,
                        "%s is a `code` server action, but "
                        "it isn't allowed in this configuration.\n\n"
                        "See server options to enable it" % action)

            if action.state == 'email':
                user = config['email_from']
                address = str(action.email)
                try:
                    address = eval(str(action.email), cxt)
                except:
                    pass

                if not address:
                    logger.notifyChannel(
                        'email', netsvc.LOG_INFO,
                        'Partner Email address not Specified!')
                    continue
                if not user:
                    raise osv.except_osv(
                        _('Error'),
                        _("Please specify server option --email-from !"))

                subject = self.merge_message(cr, uid, action.subject, action,
                                             context)
                body = self.merge_message(cr, uid, action.message, action,
                                          context)

                if tools.email_send(user, [address],
                                    subject,
                                    body,
                                    debug=False,
                                    subtype='html') == True:
                    logger.notifyChannel(
                        'email', netsvc.LOG_INFO,
                        'Email successfully send to : %s' % (address))
                else:
                    logger.notifyChannel(
                        'email', netsvc.LOG_ERROR,
                        'Failed to send email to : %s' % (address))

            if action.state == 'trigger':
                wf_service = netsvc.LocalService("workflow")
                model = action.wkf_model_id.model
                obj_pool = self.pool.get(action.model_id.model)
                res_id = self.pool.get(action.model_id.model).read(
                    cr, uid, [context.get('active_id')],
                    [action.trigger_obj_id.name])
                id = res_id[0][action.trigger_obj_id.name]
                wf_service.trg_validate(uid, model, int(id),
                                        action.trigger_name, cr)

            if action.state == 'sms':
                #TODO: set the user and password from the system
                # for the sms gateway user / password
                # USE smsclient module from extra-addons
                logger.notifyChannel(
                    'sms', netsvc.LOG_ERROR,
                    'SMS Facility has not been implemented yet. Use smsclient module!'
                )

            if action.state == 'other':
                res = []
                for act in action.child_ids:
                    context['active_id'] = context['active_ids'][0]
                    result = self.run(cr, uid, [act.id], context)
                    if result:
                        res.append(result)

                return res

            if action.state == 'loop':
                obj_pool = self.pool.get(action.model_id.model)
                obj = obj_pool.browse(cr,
                                      uid,
                                      context['active_id'],
                                      context=context)
                cxt = {
                    'context': context,
                    'object': obj,
                    'time': time,
                    'cr': cr,
                    'pool': self.pool,
                    'uid': uid
                }
                expr = eval(str(action.expression), cxt)
                context['object'] = obj
                for i in expr:
                    context['active_id'] = i.id
                    result = self.run(cr, uid, [action.loop_action.id],
                                      context)

            if action.state == 'object_write':
                res = {}
                for exp in action.fields_lines:
                    euq = exp.value
                    if exp.type == 'equation':
                        obj_pool = self.pool.get(action.model_id.model)
                        obj = obj_pool.browse(cr,
                                              uid,
                                              context['active_id'],
                                              context=context)
                        cxt = {'context': context, 'object': obj, 'time': time}
                        expr = eval(euq, cxt)
                    else:
                        expr = exp.value
                    res[exp.col1.name] = expr

                if not action.write_id:
                    if not action.srcmodel_id:
                        obj_pool = self.pool.get(action.model_id.model)
                        obj_pool.write(cr, uid, [context.get('active_id')],
                                       res)
                    else:
                        write_id = context.get('active_id')
                        obj_pool = self.pool.get(action.srcmodel_id.model)
                        obj_pool.write(cr, uid, [write_id], res)

                elif action.write_id:
                    obj_pool = self.pool.get(action.srcmodel_id.model)
                    rec = self.pool.get(action.model_id.model).browse(
                        cr, uid, context.get('active_id'))
                    id = eval(action.write_id, {'object': rec})
                    try:
                        id = int(id)
                    except:
                        raise osv.except_osv(
                            _('Error'),
                            _("Problem in configuration `Record Id` in Server Action!"
                              ))

                    if type(id) != type(1):
                        raise osv.except_osv(
                            _('Error'),
                            _("Problem in configuration `Record Id` in Server Action!"
                              ))
                    write_id = id
                    obj_pool.write(cr, uid, [write_id], res)

            if action.state == 'object_create':
                res = {}
                for exp in action.fields_lines:
                    euq = exp.value
                    if exp.type == 'equation':
                        obj_pool = self.pool.get(action.model_id.model)
                        obj = obj_pool.browse(cr,
                                              uid,
                                              context['active_id'],
                                              context=context)
                        expr = eval(euq, {
                            'context': context,
                            'object': obj,
                            'time': time
                        })
                    else:
                        expr = exp.value
                    res[exp.col1.name] = expr

                obj_pool = None
                res_id = False
                obj_pool = self.pool.get(action.srcmodel_id.model)
                res_id = obj_pool.create(cr, uid, res)
                if action.record_id:
                    self.pool.get(action.model_id.model).write(
                        cr, uid, [context.get('active_id')],
                        {action.record_id.name: res_id})

            if action.state == 'object_copy':
                res = {}
                for exp in action.fields_lines:
                    euq = exp.value
                    if exp.type == 'equation':
                        obj_pool = self.pool.get(action.model_id.model)
                        obj = obj_pool.browse(cr,
                                              uid,
                                              context['active_id'],
                                              context=context)
                        expr = eval(euq, {
                            'context': context,
                            'object': obj,
                            'time': time
                        })
                    else:
                        expr = exp.value
                    res[exp.col1.name] = expr

                obj_pool = None
                res_id = False

                model = action.copy_object.split(',')[0]
                cid = action.copy_object.split(',')[1]
                obj_pool = self.pool.get(model)
                res_id = obj_pool.copy(cr, uid, int(cid), res)

        return False
    def generate_email(self, cr, uid, template_id, res_id, context=None):
        """This is a copy of generate_email from email.template, with a patch as below.
        """
        if context is None:
            context = {}
        report_xml_pool = self.pool.get('ir.actions.report.xml')
        template = self.get_email_template(cr, uid, template_id, res_id, context)
        values = {}
        for field in ['subject', 'body_html', 'email_from',
                      'email_to', 'email_recipients', 'email_cc', 'reply_to']:
            values[field] = self.render_template(cr, uid, getattr(template, field),
                                                 template.model, res_id, context=context) \
                                                 or False
        if template.user_signature:
            signature = self.pool.get('res.users').browse(cr, uid, uid, context).signature
            values['body_html'] = tools.append_content_to_html(values['body_html'], signature)

        if values['body_html']:
            values['body'] = tools.html_sanitize(values['body_html'])

        values.update(mail_server_id=template.mail_server_id.id or False,
                      auto_delete=template.auto_delete,
                      model=template.model,
                      res_id=res_id or False)

        attachments = []
        # Add report in attachments
        if template.report_template:
            report_name = self.render_template(cr, uid, template.report_name, template.model, res_id, context=context)
            report_service = 'report.' + report_xml_pool.browse(cr, uid, template.report_template.id, context).report_name
            # Ensure report is rendered using template's language
            ctx = context.copy()
            if template.lang:
                ctx['lang'] = self.render_template(cr, uid, template.lang, template.model, res_id, context)

            # Start of Patch.

#           service = netsvc.LocalService(report_service)
#           (result, format) = service.create(cr, uid, [res_id], {'model': template.model}, ctx)

            if not report_xml_pool.browse(cr, uid, template.report_template.id, context).is_pentaho_report:
                # Standard service call for non-Pentaho reports
                service = netsvc.LocalService(report_service)
                (result, format) = service.create(cr, uid, [res_id], {'model': template.model}, ctx)
            else:
                # Call the report as a duplicate of the current user to remove the user concurrency issue.
                # NOTE: This works HOWEVER, if the temp user is in the in the 'portal' or 'anonymous' security groups
                #       then rendering the Pentaho report may fail because the user is denied read access to res.partner.
                #       See security rule 'res_partner: read access on my partner'.
                crtemp = pooler.get_db(cr.dbname).cursor()

                #Remove default_partner_id set by search view that could duplicate user with existing partner!
                # Use copied context, to ensure we don't affect any processing outside of this method's scope.
                ctx.pop('default_partner_id', None)

                user_obj = self.pool.get('res.users')
                existing_uids = user_obj.search(crtemp, SUPERUSER_ID, [('login', '=', "%s (copy)" % user_obj.browse(crtemp, SUPERUSER_ID, uid, context=ctx).login)], context=ctx)
                if existing_uids:
                    self._unlink_user_and_partner(crtemp, uid, existing_uids, context=ctx)

                new_uid = user_obj.copy(crtemp, SUPERUSER_ID, uid, default={}, context=ctx)
                crtemp.commit()

                service = netsvc.LocalService(report_service)
                (result, format) = service.create(crtemp, new_uid, [res_id], {'model': template.model}, ctx)
                crtemp.commit()
                crtemp.close()

                crtemp = pooler.get_db(cr.dbname).cursor()

                self._unlink_user_and_partner(crtemp, uid, [new_uid], context=ctx)

                crtemp.commit()
                crtemp.close()

            # End of Patch

            result = base64.b64encode(result)
            if not report_name:
                report_name = report_service
            ext = "." + format
            if not report_name.endswith(ext):
                report_name += ext
            attachments.append((report_name, result))

        # Add template attachments
        for attach in template.attachment_ids:
            attachments.append((attach.datas_fname, attach.datas))

        values['attachments'] = attachments
        return values
Exemplo n.º 4
0
 def import_csv(self, cr, uid, ids, context):
     '''
     Code to import csv and generate a sale order,confirm the order,prepare a delivery order
     and also a draft invoice
     '''
     sale_obj = self.pool.get('sale.order')
     obj_saleorder_line = self.pool.get('sale.order.line')
     picking_obj = self.pool.get('stock.picking')
     move_obj = self.pool.get('stock.move')
     partner_obj = self.pool.get('res.partner')
     location_obj = self.pool.get('stock.location')
     data = self.browse(cr, uid, ids[0])
     if not data.csv_file:
         raise osv.except_osv(_('CSV Error !'),
                              _('Please select a .csv file'))
     product_inv_data = base64.decodestring(data.csv_file).split("\r")
     loc_id = active_id = ''
     if len(product_inv_data) == 1 and product_inv_data[0].find('\n') != -1:
         product_inv_data = product_inv_data[0].split('\n')
     for i in range(0, len(product_inv_data)):
         product_inv_data_lines = product_inv_data[i]
         if i == 0:
             active_id = context.get('active_id')
             obj_stock_location = location_obj.browse(cr, uid, active_id)
             partner_id = obj_stock_location.partner_id.id
             if not partner_id:
                 raise osv.except_osv(
                     _('Partner info Missing !'),
                     _('Please select a Proper Partner for the Location'))
             user_id = partner_obj.browse(cr, uid, partner_id).user_id
             supplier_data = partner_obj.browse(cr,
                                                uid,
                                                partner_id,
                                                context=context)
             pricelist_id = supplier_data.property_product_pricelist and supplier_data.property_product_pricelist.id or False
             if obj_stock_location.partner_id.property_payment_term.id:
                 payment_term = obj_stock_location.partner_id.property_payment_term.id
             else:
                 raise osv.except_osv(
                     _('Payment Term Missing !'),
                     _('Please select a Payment Term for the customer'))
             gen_sale_id = sale_obj.create(
                 cr, uid, {
                     'partner_id': partner_id,
                     'partner_invoice_id': partner_id,
                     'order_policy': 'picking',
                     'partner_shipping_id': partner_id,
                     'pricelist_id': pricelist_id,
                     'origin': obj_stock_location.name,
                     'note': obj_stock_location.name,
                     'payment_term': payment_term,
                     'user_id': user_id and user_id.id or uid,
                 })
         else:
             product_single_line = product_inv_data_lines.split(',')
             prod_single_line = product_single_line[0]
             if prod_single_line == '\n':
                 continue
             if prod_single_line and prod_single_line != '':
                 loc_id = product_single_line[10]
                 move_id = int(product_single_line[-4])
                 obj_each_internal_move = move_obj.browse(cr, uid, move_id)
                 if int(prod_single_line
                        ) > obj_each_internal_move.rem_product_qty:
                     raise osv.except_osv(
                         _('Exceeding Quantity !'),
                         _('Meer verkocht dan de voorraad'))
                 obj_saleorder_line.create(
                     cr, uid, {
                         'product_id': obj_each_internal_move.product_id.id,
                         'product_uom':
                         obj_each_internal_move.product_uom.id,
                         'name': obj_each_internal_move.product_id.name,
                         'line_consignment_price':
                         obj_each_internal_move.consignment_price,
                         'price_unit':
                         obj_each_internal_move.consignment_price,
                         'order_id': gen_sale_id,
                         'product_uom_qty': prod_single_line,
                         'stock_move_id': move_id
                     })
     sale_obj.action_invoice_create(
         cr,
         uid, [gen_sale_id],
         grouped=False,
         states=['draft'],
         date_invoice=time.strftime('%Y-%m-%d %H:%M:%S'),
         context=None)
     netsvc.LocalService("workflow").trg_validate(
         uid, 'sale.order', gen_sale_id, 'order_confirm',
         cr)  # to invoke a workflow to confirm the sale order
     picking_id = picking_obj.search(cr, uid,
                                     [('sale_id', '=', gen_sale_id)])
     self.pool.get('stock.picking.out').write(cr, uid, picking_id,
                                              {'invoice_state': 'invoiced'})
     order_rec = sale_obj.browse(cr, uid, gen_sale_id, context=context)
     for i in move_obj.search(
             cr, uid,
         [('origin', '=', order_rec.name)]):  #changes made by hitesh
         move_obj.write(cr, uid, i, {'location_id': loc_id})
     if picking_obj.action_done(cr, uid, picking_id):
         order_rec.write({'shipped': True})
     sale_obj.write(cr, uid, [gen_sale_id],
                    {'state': 'done'})  ###new_server_update
     if active_id:
         location_obj.consignment_gross_total(cr,
                                              uid, [active_id],
                                              context=None)
     return True
Exemplo n.º 5
0
    def work_validate(self, cr, uid, ids, context=None):
        val = self.browse(cr, uid, ids, context={})[0]
        if val.type == 'pabrikasi':
            material_id = self.pool.get('stock.picking').create(
                cr, uid, {
                    'name':
                    self.pool.get('ir.sequence').get(cr, uid,
                                                     'stock.picking.internal'),
                    'origin':
                    val.name,
                    'type':
                    'internal',
                    'move_type':
                    'one',
                    'state':
                    'auto',
                    'date':
                    val.date,
                    'auto_picking':
                    True,
                    'company_id':
                    1,
                })

            goods_id = self.pool.get('stock.picking').create(
                cr, uid, {
                    'name':
                    self.pool.get('ir.sequence').get(cr, uid,
                                                     'stock.picking.internal'),
                    'origin':
                    val.name,
                    'type':
                    'internal',
                    'move_type':
                    'one',
                    'state':
                    'auto',
                    'date':
                    val.date,
                    'auto_picking':
                    True,
                    'company_id':
                    1,
                })

            for x in val.material_lines:
                self.pool.get('stock.move').create(
                    cr, uid, {
                        'name':
                        x.product_id.default_code + x.product_id.name_template,
                        'picking_id': material_id,
                        'product_id': x.product_id.id,
                        'product_qty': x.product_qty,
                        'product_uom': x.product_uom.id,
                        'date': val.date,
                        'location_id': val.location_src_id.id,
                        'location_dest_id': 7,
                        'state': 'waiting',
                        'company_id': 1
                    })

            for x in val.perintah_lines:
                self.pool.get('stock.move').create(
                    cr, uid, {
                        'name':
                        x.product_id.default_code + x.product_id.name_template,
                        'picking_id': goods_id,
                        'product_id': x.product_id.id,
                        'product_qty': x.product_qty,
                        'product_uom': x.product_uom.id,
                        'date': val.date,
                        'location_id': 7,
                        'location_dest_id': val.location_dest_id.id,
                        'state': 'waiting',
                        'company_id': 1
                    })

            wf_service = netsvc.LocalService("workflow")
            wf_service.trg_validate(uid, 'stock.picking', goods_id,
                                    'button_confirm', cr)
            wf_service.trg_validate(uid, 'stock.picking', material_id,
                                    'button_confirm', cr)

        self.write(
            cr, uid, ids, {
                'state': 'done',
                'approver': self.pool.get('res.users').browse(cr, uid, uid).id
            })
        return True
Exemplo n.º 6
0
    def generate_email(self, cr, uid, template_id, res_id, context=None):
        """Generates an email from the template for given (model, res_id) pair.

           :param template_id: id of the template to render.
           :param res_id: id of the record to use for rendering the template (model
                          is taken from template definition)
           :returns: a dict containing all relevant fields for creating a new
                     mail.message entry, with the addition one additional
                     special key ``attachments`` containing a list of
        """
        if context is None:
            context = {}
        values = {
                  'subject': False,
                  'body_text': False,
                  'body_html': False,
                  'email_from': False,
                  'email_to': False,
                  'email_cc': False,
                  'email_bcc': False,
                  'reply_to': False,
                  'auto_delete': False,
                  'model': False,
                  'res_id': False,
                  'mail_server_id': False,
                  'attachments': False,
                  'attachment_ids': False,
                  'message_id': False,
                  'state': 'outgoing',
                  'subtype': 'plain',
        }
        if not template_id:
            return values

        report_xml_pool = self.pool.get('ir.actions.report.xml')
        template = self.get_email_template(cr, uid, template_id, res_id, context)
        template_context = self._prepare_render_template_context(cr, uid, template.model, res_id, context)

        for field in ['subject', 'body_text', 'body_html', 'email_from',
                      'email_to', 'email_cc', 'email_bcc', 'reply_to',
                      'message_id']:
            values[field] = self.render_template(cr, uid, getattr(template, field),
                                                 template.model, res_id, context=template_context) \
                                                 or False

        if values['body_html']:
            values.update(subtype='html')

        if template.user_signature:
            signature = self.pool.get('res.users').browse(cr, uid, uid, context).signature
            if signature:
                values['body_text'] += '\n\n' + signature

        values.update(mail_server_id = template.mail_server_id.id or False,
                      auto_delete = template.auto_delete,
                      model=template.model,
                      res_id=res_id or False)

        attachments = {}
        # Add report as a Document
        if template.report_template:
            report_name = self.render_template(cr, uid, template.report_name, template.model, res_id, context=context)
            report_service = 'report.' + report_xml_pool.browse(cr, uid, template.report_template.id, context).report_name
            # Ensure report is rendered using template's language
            ctx = context.copy()
            if template.lang:
                ctx['lang'] = self.render_template(cr, uid, template.lang, template.model, res_id, context)
            service = netsvc.LocalService(report_service)
            (result, format) = service.create(cr, uid, [res_id], {'model': template.model}, ctx)
            result = base64.b64encode(result)
            if not report_name:
                report_name = report_service
            ext = "." + format
            if not report_name.endswith(ext):
                report_name += ext
            attachments[report_name] = result

        # Add document attachments
        for attach in template.attachment_ids:
            # keep the bytes as fetched from the db, base64 encoded
            attachments[attach.datas_fname] = attach.datas

        values['attachments'] = attachments
        return values
Exemplo n.º 7
0
 def _execute(self, db, uid, wiz_id, datas, action, context):
     self.wiz_datas[wiz_id].update(datas)
     wiz = netsvc.LocalService('wizard.'+self.wiz_name[wiz_id])
     return wiz.execute(db, uid, self.wiz_datas[wiz_id], action, context)
Exemplo n.º 8
0
    def reorganized_picking(self, cr, uid, id, context):
        #TODO this wizard have to work and used only for the outgoing picking. Add some check
        picking_obj = self.pool.get('stock.picking')
        move_obj = self.pool.get('stock.move')
        wf_service = netsvc.LocalService("workflow")
        wizard = self.browse(cr, uid, id, context=context)[0]
        if wizard.picking_option == 'selected':
            picking_ids = context['active_ids']
            if picking_obj.search(
                    cr, uid,
                [['id', 'in', picking_ids], ['type', 'in', ['out', 'in']]]):
                raise osv.except_osv(
                    _('Error !'),
                    _('Incomming or Outgoing picking can not be merge'))
        else:
            #the INT is hardcoded :S not clean at all but in V6 outgoing and delivery picking have no difference :S
            #picking_ids = picking_obj.search(cr, uid, [['state', '=', 'assigned'], ['type', '=', 'out'], ['name', 'ilike', 'INT%']])
            picking_ids = picking_obj.search(
                cr, uid,
                [['state', '=', 'assigned'], ['type', '=', 'internal']])

        move_ids = move_obj.search(cr,
                                   uid, [['picking_id', 'in', picking_ids]],
                                   context=context)

        res = {}
        res2 = []
        for move in move_obj.browse(cr, uid, move_ids, context=context):
            product = move.product_id
            if res.get(product.id, False):
                res[product.id] += [move.id]
            else:
                res[product.id] = [move.id]
                res2 += [(product.loc_rack, product.loc_row, product.id)]

        res2.sort()
        step = int(
            round(
                len(res2) / (wizard.number_of_output_picking * 1.0) + 0.4999,
                0))
        count = 0
        while res2 and count < 1000:
            picking_id = picking_obj.create(cr,
                                            uid, {
                                                'type': 'internal',
                                                'origin': 'MERGE'
                                            },
                                            context=context)
            move_ids = []
            for val in res2[0:step]:
                move_ids += res[val[2]]
            move_obj.write(cr,
                           uid,
                           move_ids, {'picking_id': picking_id},
                           context=context)
            res2 = res2[step:]
            count += 1
            wf_service.trg_validate(uid, 'stock.picking', picking_id,
                                    'button_confirm', cr)
        picking_obj.unlink(cr, uid, picking_ids, context=context)

        return {'type': 'ir.actions.act_window_close'}
Exemplo n.º 9
0
    def add_payment(self, cr, uid, order_id, data, context=None):
        """Create a new payment for the order"""
        statement_obj = self.pool.get('account.bank.statement')
        statement_line_obj = self.pool.get('account.bank.statement.line')
        prod_obj = self.pool.get('product.product')
        property_obj = self.pool.get('ir.property')
        curr_c = self.pool.get('res.users').browse(cr,
                                                   uid,
                                                   uid,
                                                   context=context).company_id
        curr_company = curr_c.id
        order = self.browse(cr, uid, order_id, context=context)
        ids_new = []
        args = {
            'amount': data['amount'],
        }
        if 'payment_date' in data.keys():
            args['date'] = data['payment_date']
        args['name'] = order.name
        if data.get('payment_name', False):
            args['name'] = args['name'] + ': ' + data['payment_name']
        account_def = property_obj.get(cr,
                                       uid,
                                       'property_account_receivable',
                                       'res.partner',
                                       context=context)
        args['account_id'] = (order.partner_id and order.partner_id.property_account_receivable \
                             and order.partner_id.property_account_receivable.id) or (account_def and account_def.id) or False
        args['partner_id'] = order.partner_id and order.partner_id.id or None

        if not args['account_id']:
            if not args['partner_id']:
                msg = _(
                    'There is no receivable account defined to make payment')
            else:
                msg = _(
                    'There is no receivable account defined to make payment for the partner: "%s" (id:%d)'
                ) % (
                    order.partner_id.name,
                    order.partner_id.id,
                )
            raise osv.except_osv(_('Configuration Error !'), msg)

        statement_id = statement_obj.search(
            cr,
            uid, [('journal_id', '=', int(data['journal'])),
                  ('company_id', '=', curr_company), ('user_id', '=', uid),
                  ('state', '=', 'open')],
            context=context)
        if len(statement_id) == 0:
            raise osv.except_osv(_('Error !'),
                                 _('You have to open at least one cashbox'))
        if statement_id:
            statement_id = statement_id[0]
        args['statement_id'] = statement_id
        args['pos_statement_id'] = order_id
        args['journal_id'] = int(data['journal'])
        args['type'] = 'customer'
        args['ref'] = order.name
        statement_line_obj.create(cr, uid, args, context=context)
        ids_new.append(statement_id)

        wf_service = netsvc.LocalService("workflow")
        wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
        wf_service.trg_write(uid, 'pos.order', order_id, cr)

        return statement_id
Exemplo n.º 10
0
    def send_mail_vehicle_insurance_report(self, cr, uid, ids, context=None):
        email_template_obj = self.pool.get('email.template')
        template_ids = email_template_obj.search(
            cr,
            uid, [('model_id.model', '=', 'fleet.vehicle')],
            context=context)
        if not template_ids:
            return True  #raise osv.except_osv(_('Warning!'), _('There are no Template configured for sending mail'))
        values = email_template_obj.generate_email(cr,
                                                   uid,
                                                   template_ids[0],
                                                   ids,
                                                   context=context)
        values['res_id'] = False
        mail_mail_obj = self.pool.get('mail.mail')
        msg_id = mail_mail_obj.create(cr, uid, values, context=context)

        attachment_obj = self.pool.get('ir.attachment')
        ir_actions_report = self.pool.get('ir.actions.report.xml')

        matching_reports = ir_actions_report.search(
            cr, uid, [('report_name', '=',
                       'fleet.vehicle.expired_insurance.report.webkit')])
        if not matching_reports:
            return True  #raise osv.except_osv(_('Warning!'), _('There is no Report to send'))

        report = ir_actions_report.browse(cr, uid, matching_reports[0])
        report_service = 'report.' + report.report_name
        service = netsvc.LocalService(report_service)
        date = self.pool.get('fleet.vehicle.expired_insurance')._get_date(
            cr, uid, ids)
        vehicle_ids = self.search(
            cr,
            uid, [('insurance_policy_expiration', "<=", date)],
            order='insurance_policy_expiration desc')
        if not vehicle_ids:
            return True  #raise osv.except_osv(_('Warning!'), _('There are no records to print'))

        (result, format) = service.create(cr,
                                          uid,
                                          vehicle_ids, {
                                              'model': 'fleet.vehicle',
                                              'count': len(vehicle_ids),
                                              'date': date
                                          },
                                          context=context)

        result = base64.b64encode(result)
        file_name = _('Expire_or_to_expire_Vehicle_Insurance_Policies')
        file_name += ".pdf"
        attachment_id = attachment_obj.create(cr,
                                              uid, {
                                                  'name': file_name,
                                                  'datas': result,
                                                  'datas_fname': file_name,
                                                  'res_model': self._name,
                                                  'res_id': msg_id,
                                                  'type': 'binary'
                                              },
                                              context=context)

        if msg_id and attachment_id:
            mail_mail_obj.write(cr,
                                uid,
                                msg_id,
                                {'attachment_ids': [(6, 0, [attachment_id])]},
                                context=context)
            mail_mail_obj.send(cr, uid, [msg_id], context=context)
        return True
Exemplo n.º 11
0
 def _action_explode(self, cr, uid, move, context=None):
     """ Explodes pickings.
     @param move: Stock moves
     @return: True
     """
     bom_obj = self.pool.get('mrp.bom')
     move_obj = self.pool.get('stock.move')
     procurement_obj = self.pool.get('procurement.order')
     product_obj = self.pool.get('product.product')
     wf_service = netsvc.LocalService("workflow")
     if move.product_id.supply_method == 'produce' and move.product_id.procure_method == 'make_to_order':
         bis = bom_obj.search(cr, uid, [
             ('product_id','=',move.product_id.id),
             ('bom_id','=',False),
             ('type','=','phantom')])
         if bis:
             factor = move.product_qty
             bom_point = bom_obj.browse(cr, uid, bis[0], context=context)
             res = bom_obj._bom_explode(cr, uid, bom_point, factor, [])
             dest = move.product_id.product_tmpl_id.property_stock_production.id
             state = 'confirmed'
             if move.state == 'assigned':
                 state = 'assigned'
             for line in res[0]:                    
                 valdef = {
                     'picking_id': move.picking_id.id,
                     'product_id': line['product_id'],
                     'product_uom': line['product_uom'],
                     'product_qty': line['product_qty'],
                     'product_uos': line['product_uos'],
                     'product_uos_qty': line['product_uos_qty'],
                     'move_dest_id': move.id,
                     'state': state,
                     'name': line['name'],
                     'location_dest_id': dest,
                     'move_history_ids': [(6,0,[move.id])],
                     'move_history_ids2': [(6,0,[])],
                     'procurements': [],
                 }
                 mid = move_obj.copy(cr, uid, move.id, default=valdef)
                 prodobj = product_obj.browse(cr, uid, line['product_id'], context=context)
                 proc_id = procurement_obj.create(cr, uid, {
                     'name': (move.picking_id.origin or ''),
                     'origin': (move.picking_id.origin or ''),
                     'date_planned': move.date,
                     'product_id': line['product_id'],
                     'product_qty': line['product_qty'],
                     'product_uom': line['product_uom'],
                     'product_uos_qty': line['product_uos'] and line['product_uos_qty'] or False,
                     'product_uos':  line['product_uos'],
                     'location_id': move.location_id.id,
                     'procure_method': prodobj.procure_method,
                     'move_id': mid,
                 })
                 wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr)
             move_obj.write(cr, uid, [move.id], {
                 'location_id': move.location_dest_id.id,
                 'auto_validate': True,
                 'picking_id': False,
                 'state': 'waiting'
             })
             for m in procurement_obj.search(cr, uid, [('move_id','=',move.id)], context):
                 wf_service.trg_validate(uid, 'procurement.order', m, 'button_wait_done', cr)
     return True
Exemplo n.º 12
0
    def run(self, cr, uid, ids, context=None):
        """
        Creates / removes FYC entries
        """

        pool = self.pool
        active_id = context and context.get('active_id', False) or False
        if not active_id:
            raise osv.except_osv(_('Error'), _('No active ID found'))
        # Read the object
        fyc = pool.get('account_fiscal_year_closing.fyc').browse(cr, uid, active_id, context=context)
        # Check for invalid period moves if needed
        if fyc.force_recreation_period_moves:
            self._force_recreation_period_moves(cr, uid, fyc, context)
            fyc.write({'force_recreation_period_moves': False})
            return {'type': 'ir.actions.act_window_close'}
        if fyc.check_invalid_period_moves:
            self._check_invalid_period_moves(cr, uid, fyc, context)
        # Check for draft moves if needed
        if fyc.check_draft_moves:
            self._check_draft_moves(cr, uid, fyc, context)
        # Check for unbalanced moves if needed
        if fyc.check_unbalanced_moves:
            self._check_unbalanced_moves(cr, uid, fyc, context)
        # Create L&P move if needed
        if fyc.create_loss_and_profit and not fyc.loss_and_profit_move_id:
            self.create_closing_move(cr, uid, 'loss_and_profit', fyc, context)
        # Remove the L&P move if needed
        if (not fyc.create_loss_and_profit) and fyc.loss_and_profit_move_id:
            self.remove_move(cr, uid, 'loss_and_profit', fyc, context)
        # Refresh the cached fyc object
        fyc = pool.get('account_fiscal_year_closing.fyc').browse(cr, uid, active_id, context=context)
        # Create the Net L&P move if needed
        if fyc.create_net_loss_and_profit and not fyc.net_loss_and_profit_move_id:
            self.create_closing_move(cr, uid, 'net_loss_and_profit', fyc, context)
        # Remove the Net L&P move if needed
        if (not fyc.create_net_loss_and_profit) and fyc.net_loss_and_profit_move_id:
            self.remove_move(cr, uid, 'net_loss_and_profit', fyc, context)
        # Refresh the cached fyc object
        fyc = pool.get('account_fiscal_year_closing.fyc').browse(cr, uid, active_id, context=context)
        # Create the closing move if needed
        if fyc.create_closing and not fyc.closing_move_id:
            self.create_closing_move(cr, uid, 'close', fyc, context)
        # Remove the closing move if needed
        if (not fyc.create_closing) and fyc.closing_move_id:
            self.remove_move(cr, uid, 'close', fyc, context)
        # Refresh the cached fyc object
        fyc = pool.get('account_fiscal_year_closing.fyc').browse(cr, uid, active_id, context=context)
        # Create the opening move if needed
        if fyc.create_opening and not fyc.opening_move_id:
            self.create_opening_move(cr, uid, 'open', fyc, context)
        # Remove the opening move if needed
        if (not fyc.create_opening) and fyc.opening_move_id:
            self.remove_move(cr, uid, 'open', fyc, context)
        # Set the fyc as done (if not in cancel_mode)
        if not fyc.create_opening and not fyc.create_closing and not not fyc.create_net_loss_and_profit and not fyc.create_loss_and_profit:
            wf_service = netsvc.LocalService("workflow")
            wf_service.trg_validate(uid, 'account_fiscal_year_closing.fyc', fyc.id, 'cancel', cr)
        else:
            wf_service = netsvc.LocalService("workflow")
            wf_service.trg_validate(uid, 'account_fiscal_year_closing.fyc', fyc.id, 'run', cr)

        return {'type': 'ir.actions.act_window_close'}
Exemplo n.º 13
0
 def send_conf_mail(self, cr, uid, ids, context=None):
     for id in ids:
         obj = self.browse(cr, uid, id)
         if obj and obj.address_id and obj.address_id.email:
             email_temp_obj = self.pool.get('email.template')
             template_id = email_temp_obj.search(
                 cr,
                 uid, [('object_name.model', '=', 'stock.picking'),
                       ('ship_mail', '=', True)],
                 context=context)
             if template_id:
                 template_obj_list = email_temp_obj.browse(
                     cr, uid, template_id)
                 for template_obj in template_obj_list:
                     subj = self.get_value(obj, template_obj,
                                           'def_subject') or ''
                     vals = {
                         'email_to':
                         self.get_value(cr, uid, obj, template_obj.def_to,
                                        context) or '',
                         'body_text':
                         self.get_value(cr, uid, obj,
                                        template_obj.def_body_text) or '',
                         'body_html':
                         self.get_value(cr, uid, obj,
                                        template_obj.def_body_html) or '',
                         'account_id':
                         template_obj.from_account.id,
                         'folder':
                         'outbox',
                         'state':
                         'na',
                         'subject':
                         self.get_value(cr, uid, obj,
                                        template_obj.def_subject) or '',
                         'email_cc':
                         self.get_value(cr, uid, obj, template_obj.def_cc)
                         or '',
                         'email_bcc':
                         self.get_value(cr, uid, obj, template_obj.def_bcc)
                         or '',
                         'email_from':
                         template_obj.from_account.email_id or '',
                         'reply_to':
                         self.get_value(cr, uid, obj, template_obj.reply_to)
                         or '',
                         'date_mail':
                         time.strftime('%Y-%m-%d %H:%M:%S'),
                     }
                     if vals['email_to'] and vals['account_id']:
                         mail_id = self.pool.get(
                             'email_template.mailbox').create(
                                 cr, uid, vals, context=context)
                         data = {}
                         data['model'] = 'stock.picking'
                         if template_obj.report_template:
                             reportname = 'report.' + self.pool.get(
                                 'ir.actions.report.xml').read(
                                     cr,
                                     uid,
                                     template_obj.report_template.id,
                                     ['report_name'],
                                     context=context)['report_name']
                             service = netsvc.LocalService(reportname)
                             (result,
                              format) = service.create(cr,
                                                       uid, [id],
                                                       data,
                                                       context=context)
                             email_temp_obj._add_attachment(
                                 cr,
                                 uid,
                                 mail_id,
                                 subj,
                                 base64.b64encode(result),
                                 template_obj.file_name or 'Order.pdf',
                                 context=context)
     return True
    def action_invoice_ship_create(self, cr, uid, ids, *args):
        wf_service = netsvc.LocalService("workflow")
        picking_id = False
        move_obj = self.pool.get('stock.move')
        proc_obj = self.pool.get('procurement.order')
        company = self.pool.get('res.users').browse(cr, uid, uid).company_id
        for order in self.browse(cr, uid, ids, context={}):
            if order.type=='out_invoice' and not order.x_so and not order.origin:
                proc_ids = []
                output_id = self.pool.get('res.users').browse(cr, uid, uid).shop.warehouse_id.lot_output_id.id
                location_id = self.pool.get('res.users').browse(cr, uid, uid).location.id
                picking_id = False
                for line in order.invoice_line:
                    proc_id = False
                    date_planned = datetime.now() + relativedelta(0.0)
                    date_planned= date_planned.strftime('%Y-%m-%d %H:%M:%S')
                    move_id = False
                    if line.product_id and line.product_id.product_tmpl_id.type in ('product', 'consu'):
                        if not picking_id:
                            pick_name = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out')
                            picking_id = self.pool.get('stock.picking').create(cr, uid, {
                                'name': pick_name,
                                'origin': order.number,
                                'type': 'out',
                                'state': 'auto',
                                'move_type': 'direct',
                                'address_id': order.address_invoice_id.id,
                                'invoice_state': 'none',
                                'company_id': order.company_id.id,
                            })
                        move_id = self.pool.get('stock.move').create(cr, uid, {
                            'name': line.name[:64],
                            'discount':line.discount,
                            'picking_id': picking_id,
                            'product_id': line.product_id.id,
                            'date': date_planned,
                            'date_expected': date_planned,
                            'product_qty': line.quantity,
                            'product_uom': line.uos_id.id,
                            'product_uos_qty': line.quantity,
                            'product_uos': line.uos_id.id,
                            'address_id': order.address_invoice_id.id,
                            'location_id': line.location.id or location_id,
                            'location_dest_id': output_id,
                            'tracking_id': False,
                            'state': 'draft',
                            #'state': 'waiting',
                            'company_id': order.company_id.id,
                        })

                        proc_ids.append(proc_id)

                val = {}

                if picking_id:
                    wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)

                #for proc_id in proc_ids:
                #    wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr)

                val['shipped'] = False

                self.write(cr, uid, [order.id], val)
        return True
Exemplo n.º 15
0
    def do_mail(self, cr, uid, ids, context=None):
        mod_obj = self.pool.get('ir.model.data')
        move_obj = self.pool.get('account.move.line')
        user_obj = self.pool.get('res.users')
        line_obj = self.pool.get('account_followup.stat')

        if context is None:
            context = {}
        data = self.read(cr, uid, ids, [], context=context)[0]
        model_data_ids = mod_obj.search(
            cr,
            uid, [('model', '=', 'ir.ui.view'),
                  ('name', '=', 'view_account_followup_print_all_msg')],
            context=context)
        resource_id = mod_obj.read(cr,
                                   uid,
                                   model_data_ids,
                                   fields=['res_id'],
                                   context=context)[0]['res_id']
        if data['email_conf']:
            msg_sent = ''
            msg_unsent = ''
            data_user = user_obj.browse(cr, uid, uid, context=context)
            line_ids = line_obj.search(
                cr, uid, [('partner_id', 'in', data['partner_ids'])])
            move_lines = line_obj.browse(cr, uid, line_ids, context=context)
            partners = []
            dict_lines = {}
            for line in move_lines:
                if line.partner_id.id not in dict_lines.keys():
                    partners.append(line.partner_id)
                    dict_lines[line.partner_id.id] = [line]
                else:
                    dict_lines[line.partner_id.id].append(line)
            for partner in partners:
                ids_lines = move_obj.search(
                    cr, uid, [('partner_id', '=', partner.id),
                              ('reconcile_id', '=', False),
                              ('account_id.type', 'in', ['receivable'])])
                data_lines = move_obj.browse(cr,
                                             uid,
                                             ids_lines,
                                             context=context)
                followup_data = dict_lines[partner.id]
                dest = False
                if partner.address:
                    for adr in partner.address:
                        if adr.type == 'contact':
                            if adr.email:
                                dest = [adr.email]
                        if (not dest) and adr.type == 'default':
                            if adr.email:
                                dest = [adr.email]
                src = tools.config.options['email_from']
                if not data['partner_lang']:
                    body = data['email_body']
                else:
                    cxt = context.copy()
                    cxt['lang'] = partner.lang
                    body = user_obj.browse(
                        cr, uid, uid, context=cxt).company_id.follow_up_msg
                total_amt = 0.0
                for followup_dt in followup_data:
                    total_amt += followup_dt.debit - followup_dt.credit
                move_line = ''
                subtotal_due = 0.0
                subtotal_paid = 0.0
                subtotal_maturity = 0.0
                balance = 0.0
                l = '--------------------------------------------------------------------------------------------------------------------------'
                head = l + '\n' + 'Date'.rjust(
                    10) + '\t' + 'Description'.rjust(10) + '\t' + 'Ref'.rjust(
                        10) + '\t' + 'Due date'.rjust(10) + '\t' + 'Due'.rjust(
                            10
                        ) + '\t' + 'Paid'.rjust(10) + '\t' + 'Maturity'.rjust(
                            10) + '\t' + 'Litigation'.rjust(10) + '\n' + l
                for i in data_lines:
                    maturity = 0.00
                    if i.date_maturity < time.strftime('%Y-%m-%d') and (
                            i.debit - i.credit):
                        maturity = i.debit - i.credit
                    subtotal_due = subtotal_due + i.debit
                    subtotal_paid = subtotal_paid + i.credit
                    subtotal_maturity = subtotal_maturity + int(maturity)
                    balance = balance + (i.debit - i.credit)
                    move_line = move_line + (i.date).rjust(10) + '\t' + (
                        i.name).rjust(10) + '\t' + (
                            i.ref or '').rjust(10) + '\t' + (
                                i.date_maturity or '').rjust(10) + '\t' + str(
                                    i.debit).rjust(10) + '\t' + str(
                                        i.credit).rjust(10) + '\t' + str(
                                            maturity).rjust(10) + '\t' + str(
                                                i.blocked).rjust(10) + '\n'
                move_line = move_line + l + '\n' + '\t\t\t' + 'Sub total'.rjust(
                    35) + '\t' + (str(subtotal_due) or '').rjust(10) + '\t' + (
                        str(subtotal_paid) or '').rjust(10) + '\t' + (
                            str(subtotal_maturity) or '').rjust(10) + '\n'
                move_line = move_line + '\t\t\t' + 'Balance'.rjust(
                    33) + '\t' + str(balance).rjust(10) + '\n' + l
                val = {
                    'partner_name': partner.name,
                    'followup_amount': total_amt,
                    'user_signature': data_user.name,
                    'company_name': data_user.company_id.name,
                    'company_currency': data_user.company_id.currency_id.name,
                    'line': move_line,
                    'heading': head,
                    'date': time.strftime('%Y-%m-%d'),
                }
                body = body % val
                sub = tools.ustr(data['email_subject'])
                msg = ''
                if dest:
                    try:
                        data_dict = {'form': {'partner_ids': [partner.id]}}
                        datax, frmt = netsvc.LocalService(
                            'report.account_followup.followup.print').create(
                                cr, uid, [], data_dict, {})
                        fname = 'followup-' + str(partner.name) + '.' + frmt
                        attach = [(fname, datax)]
                        tools.email_send(src, dest, sub, body, attach=attach)
                        msg_sent += partner.name + '\n'
                    except Exception, e:
                        raise osv.except_osv('Error !', e)
                else:
                    msg += partner.name + '\n'
                    msg_unsent += msg
            if not msg_unsent:
                summary = _(
                    "All E-mails have been successfully sent to Partners:.\n\n"
                ) + msg_sent
            else:
                msg_unsent = _(
                    "E-Mail not sent to following Partners, Email not available !\n\n"
                ) + msg_unsent
                msg_sent = msg_sent and _(
                    "\n\nE-Mail sent to following Partners successfully. !\n\n"
                ) + msg_sent
                line = '=========================================================================='
                summary = msg_unsent + line + msg_sent
            context.update({'summary': summary})
Exemplo n.º 16
0
    def action_invoice(self, cr, uid, ids, context=None):
        wf_service = netsvc.LocalService("workflow")
        inv_ref = self.pool.get('account.invoice')
        inv_line_ref = self.pool.get('account.invoice.line')
        product_obj = self.pool.get('product.product')
        inv_ids = []

        for order in self.pool.get('pos.order').browse(cr,
                                                       uid,
                                                       ids,
                                                       context=context):
            if order.invoice_id:
                inv_ids.append(order.invoice_id.id)
                continue

            if not order.partner_id:
                raise osv.except_osv(
                    _('Error'), _('Please provide a partner for the sale.'))

            acc = order.partner_id.property_account_receivable.id
            inv = {
                'name': order.name,
                'origin': order.name,
                'account_id': acc,
                'journal_id': order.sale_journal.id or None,
                'type': 'out_invoice',
                'reference': order.name,
                'partner_id': order.partner_id.id,
                'comment': order.note or '',
                'currency_id': order.pricelist_id.currency_id.
                id,  # considering partner's sale pricelist's currency
            }
            inv.update(
                inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice',
                                            order.partner_id.id)['value'])
            if not inv.get('account_id', None):
                inv['account_id'] = acc
            inv_id = inv_ref.create(cr, uid, inv, context=context)

            self.write(cr,
                       uid, [order.id], {
                           'invoice_id': inv_id,
                           'state': 'invoiced'
                       },
                       context=context)
            inv_ids.append(inv_id)
            for line in order.lines:
                inv_line = {
                    'invoice_id': inv_id,
                    'product_id': line.product_id.id,
                    'quantity': line.qty,
                }
                inv_name = product_obj.name_get(cr,
                                                uid, [line.product_id.id],
                                                context=context)[0][1]
                inv_line.update(
                    inv_line_ref.product_id_change(
                        cr,
                        uid, [],
                        line.product_id.id,
                        line.product_id.uom_id.id,
                        line.qty,
                        partner_id=order.partner_id.id,
                        fposition_id=order.partner_id.
                        property_account_position.id)['value'])
                if line.product_id.description_sale:
                    inv_line['note'] = line.product_id.description_sale
                inv_line['price_unit'] = line.price_unit
                inv_line['discount'] = line.discount
                inv_line['name'] = inv_name
                inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
                    and [(6, 0, inv_line['invoice_line_tax_id'])] or []
                inv_line_ref.create(cr, uid, inv_line, context=context)
            inv_ref.button_reset_taxes(cr, uid, [inv_id], context=context)
            wf_service.trg_validate(uid, 'pos.order', order.id, 'invoice', cr)

        if not inv_ids: return {}

        mod_obj = self.pool.get('ir.model.data')
        res = mod_obj.get_object_reference(cr, uid, 'account', 'invoice_form')
        res_id = res and res[1] or False
        return {
            'name': _('Customer Invoice'),
            'view_type': 'form',
            'view_mode': 'form',
            'view_id': [res_id],
            'res_model': 'account.invoice',
            'context': "{'type':'out_invoice'}",
            'type': 'ir.actions.act_window',
            'nodestroy': True,
            'target': 'current',
            'res_id': inv_ids and inv_ids[0] or False,
        }
    def compute_debit(self, cr, uid, ids, context=None):
        """
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param ids: the account invoice refund’s ID or list of IDs

        """
        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.browse(cr, uid, ids, context=context):
            created_inv = []
            date = False
            period = False
            description = False
            company = res_users_obj.browse(cr, uid, uid,
                                           context=context).company_id
            journal_id = form.journal_id.id
            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 create a debit note from '
                          'draft/proforma/cancel invoice.'))
                if inv.reconciled and mode in ('cancel', 'modify'):
                    raise osv.except_osv(
                        _('Error!'),
                        _('Cannot %s invoice which is already reconciled, '
                          'invoice should be unreconciled first. You can only '
                          'refund this invoice.') % (mode))
                if form.period.id:
                    period = form.period.id
                else:
                    # Take period from the current date
                    # period = inv.period_id and inv.period_id.id or False
                    period = self._get_period(cr, uid, context)

                if not journal_id:
                    journal_id = inv.journal_id.id

                if form.date:
                    date = form.date
                    if not form.period.id:
                        cr.execute("select name from ir_model_fields \
                                            where model = 'account.period' \
                                            and name = 'company_id'")
                        result_query = cr.fetchone()
                        if result_query:
                            # in multi company mode
                            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:
                            # in mono company mode
                            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:
                    date = inv.date_invoice
                if form.description:
                    description = form.description
                else:
                    description = inv.name

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

                # we get original data of invoice to create a new invoice that
                # is the copy of the original
                invoice = inv_obj.read(
                    cr,
                    uid, [inv.id], [
                        'name', 'type', 'number', 'reference', '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,
                                                              context=context)
                tax_lines = inv_tax_obj.browse(cr,
                                               uid,
                                               invoice['tax_line'],
                                               context=context)
                tax_lines = inv_obj._refund_cleanup_lines(cr,
                                                          uid,
                                                          tax_lines,
                                                          context=context)
                # Add origin, parent and comment values
                orig = self._get_orig(cr, uid, inv, invoice['reference'],
                                      context)
                invoice.update({
                    'type': inv.type == 'in_invoice' and 'in_refund' or\
                            inv.type == 'out_invoice' and 'out_refund',
                    'date_invoice': date,
                    'state': 'draft',
                    'number': False,
                    'invoice_line': invoice_lines,
                    'tax_line': tax_lines,
                    'period_id': period,
                    'parent_id': inv.id,
                    'name': description,
                    'origin': orig,
                    'comment': form['comment']
                })
                # take the id part of the tuple returned for many2one fields
                for field in ('partner_id', 'account_id', 'currency_id',
                              'payment_term', 'journal_id'):
                    invoice[field] = invoice[field] and invoice[field][0]
                # create the new invoice
                inv_id = inv_obj.create(cr, uid, invoice, {})
                # we compute due date
                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)
            # we get the view id
            xml_id = (inv.type == 'out_refund') and 'action_invoice_tree1' or \
                     (inv.type == 'in_refund') and 'action_invoice_tree2' or \
                     (inv.type == 'out_invoice') and 'action_invoice_tree3' or \
                     (inv.type == 'in_invoice') and 'action_invoice_tree4'
            # we get the model
            result = mod_obj.get_object_reference(cr, uid, 'account', xml_id)
            id = result and result[1] or False
            # we read the act window
            result = act_obj.read(cr, uid, id, context=context)
            # we add the new invoices into domain list
            invoice_domain = eval(result['domain'])
            invoice_domain.append(('id', 'in', created_inv))
            result['domain'] = invoice_domain
            return result
Exemplo n.º 18
0
    def action_produce_assign_product(self, cr, uid, ids, context={}):
        produce_id = False
        company = self.pool.get('res.users').browse(cr, uid, uid,
                                                    context).company_id
        for procurement in self.browse(cr, uid, ids):
            res_id = procurement.move_id.id
            loc_id = procurement.location_id.id
            newdate = DateTime.strptime(
                procurement.date_planned,
                '%Y-%m-%d %H:%M:%S') - DateTime.RelativeDateTime(
                    days=procurement.product_id.product_tmpl_id.produce_delay
                    or 0.0)
            newdate = newdate - DateTime.RelativeDateTime(
                days=company.manufacturing_lead)

            ## Smile's changes
            ## FIXME sale order line could be copied natively to the production order
            sale_order_line_id = self.pool.get('sale.order.line').search(
                cr, uid, [('procurement_id', '=', procurement.id)])

            if sale_order_line_id:
                sale_order_line_id = sale_order_line_id[0]
            else:
                sale_order_line_id = False
            produce_id = self.pool.get('mrp.production').create(
                cr, uid, {
                    'origin':
                    procurement.origin,
                    'product_id':
                    procurement.product_id.id,
                    'product_qty':
                    procurement.product_qty,
                    'product_uom':
                    procurement.product_uom.id,
                    'product_uos_qty':
                    procurement.product_uos and procurement.product_uos_qty
                    or False,
                    'product_uos':
                    procurement.product_uos and procurement.product_uos.id
                    or False,
                    'location_src_id':
                    procurement.location_id.id,
                    'location_dest_id':
                    procurement.location_id.id,
                    'bom_id':
                    procurement.bom_id and procurement.bom_id.id or False,
                    'date_planned':
                    newdate.strftime('%Y-%m-%d %H:%M:%S'),
                    'move_prod_id':
                    res_id,
                    'sale_order_line_id':
                    sale_order_line_id,
                })
            self.pool.get('sale.order.line').write(
                cr, uid, sale_order_line_id, {'mrp_production_id': produce_id})
            ## End Smile's changes

            self.write(cr, uid, [procurement.id], {'state': 'running'})
            bom_result = self.pool.get('mrp.production').action_compute(
                cr,
                uid, [produce_id],
                properties=[x.id for x in procurement.property_ids])
            wf_service = netsvc.LocalService("workflow")
            wf_service.trg_validate(uid, 'mrp.production', produce_id,
                                    'button_confirm', cr)
        return produce_id
Exemplo n.º 19
0
    def import_model(self,
                     cr,
                     uid,
                     sock,
                     remote_config,
                     remote_uid,
                     model_id,
                     ref_ids=[],
                     exc_field=None):
        #global imported_records
        #global warning_text
        #global print_log
        results = []
        model_name = self.pool.get("migration.import_models").browse(
            cr, uid, model_id, {}).name.model
        old_model_name = self.pool.get("migration.import_models").browse(
            cr, uid, model_id, {}).old_name.model or model_name
        domain = self.pool.get("migration.import_models").browse(
            cr, uid, model_id, {}).domain
        model_obj = self.pool.get(model_name)
        if self.print_log:
            print "Import_model:", model_name
            #print imported_records
            for i in self.imported_records:
                print i + ':', len(self.imported_records[i])
        model_field_ids = map(
            int,
            self.pool.get("migration.import_models").browse(
                cr, uid, model_id, {}).field)
        many2one_fields = {}
        one2many_fields = {}
        many2many_fields = {}
        selection_fields = {}
        other_fields = []
        old2new_fields = {}
        im_ids = self.pool.get("migration.import_models").search(cr, uid, [])
        model_names_list = [
            x.name.model
            for x in self.pool.get("migration.import_models").browse(
                cr, uid, im_ids, {})
        ]
        for model_field in self.pool.get("migration.model_fields").browse(
                cr, uid, model_field_ids, {}):
            if model_field.old_name:
                curr_field = model_field.old_name
            else:
                curr_field = model_field.name

            if model_field.name:
                old2new_fields[
                    model_field.old_name.name
                    or model_field.name.name] = model_field.name.name
            elif model_field.old_name.name:
                old2new_fields[model_field.old_name.name] = False

            if curr_field.ttype == 'many2one':
                many2one_fields[curr_field.name] = curr_field.relation
            elif curr_field.ttype == 'one2many':
                one2many_fields[curr_field.name] = curr_field.relation
            elif curr_field.ttype == 'many2many':
                many2many_fields[curr_field.name] = curr_field.relation
            elif model_field.name.ttype == 'selection':
                if isinstance(
                        model_obj._columns[model_field.name.name].selection,
                    (tuple, list)):
                    selection_fields[curr_field.name] = [
                        x[0] for x in model_obj._columns[
                            model_field.name.name].selection
                    ]
                else:
                    other_fields.append(curr_field.name)
            else:
                other_fields.append(curr_field.name)

            if model_field.name.relation and model_field.name.relation != 'NULL' and model_field.name.relation not in model_names_list:
                msg_text = 'Warning! Object "' + model_name + '" have relation field \'' + model_field.name.name + '\' which related to object "' + model_field.name.relation + '", this field was not filled because related object\'s model is not added in Import Model list.\n\n'
                if msg_text not in self.warning_text:
                    self.warning_text.append(msg_text)
            fields_list = many2one_fields.keys() + one2many_fields.keys(
            ) + many2many_fields.keys() + selection_fields.keys(
            ) + other_fields
        active_field = sock.execute(remote_config['db_name'], remote_uid,
                                    remote_config['password'],
                                    'ir.model.fields', 'search',
                                    [('model', '=', old_model_name),
                                     ('name', '=', 'active')])
        rec_ids = sock.execute(remote_config['db_name'], remote_uid,
                               remote_config['password'], old_model_name,
                               'search', [])
        if active_field:
            rec_ids += sock.execute(remote_config['db_name'], remote_uid,
                                    remote_config['password'], old_model_name,
                                    'search', [('active', '!=', True)])
        if ref_ids and type(ref_ids) != list: ref_ids = [ref_ids]
        #print fields_list
        for model_data in sock.execute(remote_config['db_name'], remote_uid,
                                       remote_config['password'],
                                       old_model_name, 'read', ref_ids
                                       or rec_ids, fields_list):
            #print "Before:",model_data
            old_values = model_data.copy()  # save old values
            search_old = self.search_old(sock=sock,
                                         db_name=remote_config['db_name'],
                                         uid=remote_uid,
                                         password=remote_config['password'])
            read_old = self.read_old(sock=sock,
                                     db_name=remote_config['db_name'],
                                     uid=remote_uid,
                                     password=remote_config['password'])
            if domain:
                filter_data = {
                    "fields": model_data,
                    "self": self,
                    "cr": cr,
                    "uid": uid
                }
                exec domain in filter_data
                if not filter_data.get('is_valid', False):
                    continue
            ######## Remove fields which not exist in new data base
            for k in model_data.keys():
                if k != 'id' and k not in fields_list:
                    del model_data[k]
            #######################################################
            #if model_data.get(exc_field, False): del model_data[exc_field]
            for md in model_data:
                if md in many2one_fields and model_data[md]:
                    if isinstance(model_data[md], list):
                        ref = model_data[md][0]
                    else:
                        ref = model_data[md]
                    rel_model_name = many2one_fields[md]
                    ##### Search imported records ID and if current record ID is in imported records list, then use this ID #####
                    imr = self.imported_records.get(rel_model_name, {})
                    if imr.get(ref, False):
                        model_data[md] = imr[ref]
                        continue
                    elif old2new_fields[md]:
                        if not model_obj._columns[
                                old2new_fields[md]].required and ref in imr:
                            model_data[md] = False
                            continue
                    else:
                        if ref in imr:
                            model_data[md] = False
                            continue
                    #elif not model_obj._columns[old2new_fields[md]].required and ref in imr:
                    #elif ref in imr:
                    #    model_data[md] = False
                    #    continue
                    #############################################################################################################
                    rel_model_id = self.pool.get("ir.model").search(
                        cr, uid, [('model', '=', rel_model_name)], limit=1)
                    rel_import_model_id = self.pool.get(
                        "migration.import_models").search(
                            cr, uid, [('name', '=', rel_model_id)], limit=1)
                    if rel_import_model_id:
                        if exc_field:
                            rel_field = md
                        else:
                            rel_field = None
                        res = self.import_model(cr, uid, sock, remote_config,
                                                remote_uid,
                                                rel_import_model_id[0], ref,
                                                rel_field)
                        if res:
                            model_data[md] = res[0]['id']
                        else:
                            model_data[md] = False
                    else:
                        model_data[md] = False
                elif md in one2many_fields:
                    rel_model_name = one2many_fields[md]
                    if not model_data[md] or model_obj._columns[
                            old2new_fields[md]]._fields_id == exc_field or set(
                                self.imported_records.get(
                                    rel_model_name, {})).issuperset(
                                        set(model_data[md])):
                        model_data[md] = None
                        continue
                    ref_list = model_data[md]
                    refs = []
                    res_data = []
                    rel_model_id = self.pool.get("ir.model").search(
                        cr, uid, [('model', '=', rel_model_name)], limit=1)
                    rel_import_model_id = self.pool.get(
                        "migration.import_models").search(
                            cr, uid, [('name', '=', rel_model_id)], limit=1)
                    if rel_import_model_id and ref_list:
                        rel_field = model_obj._columns[
                            old2new_fields[md]]._fields_id

                        rel_model_ids = self.imported_records.setdefault(
                            rel_model_name, {})
                        for ref in ref_list:
                            if not rel_model_ids.get(ref):
                                rel_model_ids[ref] = False
                        self.imported_records[rel_model_name] = rel_model_ids

                        if len(ref_list) == 2 and type(
                                ref_list[1]) in (str, unicode):
                            ref_list = ref_list[0]
                        res = self.import_model(cr, uid, sock, remote_config,
                                                remote_uid,
                                                rel_import_model_id[0],
                                                ref_list, rel_field)
                        #res_data += [(0,0,r) for r in res]
                        res_data = [(6, 0, [r['id'] for r in res])]
                        model_data[md] = res_data
                    else:
                        model_data[md] = False
                elif md in many2many_fields:
                    ref_list = model_data[md]
                    rel_model_name = many2many_fields[md]
                    refs = []
                    rec_list = []
                    for ref in ref_list:
                        if self.imported_records.get(rel_model_name,
                                                     {}).get(ref, False):
                            rec_list.append(
                                self.imported_records[rel_model_name][ref])
                        else:
                            refs.append(ref)
                    res_data = []
                    if rec_list:
                        res_data += [(6, 0, rec_list)]
                        #res_data += [(0,0,r) for r in rec_list]
                    else:
                        res_data = []
                    rel_model_id = self.pool.get("ir.model").search(
                        cr, uid, [('model', '=', rel_model_name)], limit=1)
                    rel_import_model_id = self.pool.get(
                        "migration.import_models").search(
                            cr, uid, [('name', '=', rel_model_id)], limit=1)
                    if rel_import_model_id and refs:
                        res_new = self.import_model(cr, uid, sock,
                                                    remote_config, remote_uid,
                                                    rel_import_model_id[0],
                                                    refs)
                        #res_data += [(0,0,r) for r in res_new]
                        res_data += [(6, 0, [r['id'] for r in res_new])]
                    model_data[md] = res_data
                else:
                    pass

            localspace = {
                "fields": model_data,
                "self": self,
                "cr": cr,
                "uid": uid,
                "old_values": old_values,
                "search_old": search_old,
                "read_old": read_old,
                "mapping": self.imported_records
            }
            ######## Fill fields with Python constructor ############
            for mf in self.pool.get("migration.model_fields").browse(
                    cr, uid, model_field_ids, {}):
                if mf.used_field_value:
                    try:
                        exec mf.field_value in localspace
                    except Exception, e:
                        try:
                            msg_error = str(e)
                        except:
                            msg_error = _('Unknown')
                        msg_text = _(
                            'Error! Object "%s" has Python code error in field "%s".\nException arised: %s\n\n'
                        ) % (model_name, mf.field_name, msg_error)
                        self.warning_text.append(msg_text)
                        raise
                    model_data[mf.old_name.name
                               or mf.name.name] = localspace.get('value')
            #########################################################
            for md in model_data:
                if md in selection_fields:
                    if model_data[md] not in selection_fields[md]:
                        defaults = self.pool.get(model_name)._defaults
                        if md in defaults:
                            model_data[md] = defaults[md]
                        else:
                            model_data[md] = selection_fields[md][0]
            old_id = model_data['id']
            if self.imported_records.get(model_name, {}).get(old_id, False):
                results.append({
                    'id':
                    self.imported_records.get(model_name, {}).get(old_id)
                })
                continue
            ref_list = self.imported_records.setdefault(model_name, {})
            ref_list[old_id] = False
            self.imported_records[model_name] = ref_list

            del model_data['id']
            #### Replace old field names to new field names
            mdata_final = {}
            for md in model_data:
                if old2new_fields.get(md, False):
                    mdata_final[old2new_fields[md]] = model_data[md]
            ###############################################
            #print "After:",mdata_final
            #res_id = super(pool.get(model_name).__class__, pool.get(model_name)).create(cr, uid, mdata_final)
            res_id = create(self.pool.get(model_name), cr, uid, mdata_final)
            ref_list[old_id] = res_id
            self.imported_records[model_name] = ref_list
            mdata_final['id'] = res_id
            results.append(mdata_final)

            ############# Workflow ############
            if self.pool.get("migration.import_models").browse(
                    cr, uid, model_id, {}).workflow:
                print "Workflow: ", model_name, res_id
                wf_service = netsvc.LocalService("workflow")
                wf_service.trg_create(uid, model_name, res_id, cr)
Exemplo n.º 20
0
    def split_invoice(self, cr, uid, ids):
        '''
        Split the invoice when the lines exceed the maximum set for the company
        '''
        for inv in self.browse(cr, uid, ids):
            inv_id = False
            if inv.company_id.lines_invoice < 1:
                raise osv.except_osv(
                    _('Error !'),
                    _('Please set an invoice lines value in:\nAdministration->Company->Configuration->Invoice lines'
                      ))
            if inv.type in ["out_invoice", "out_refund"]:
                if len(inv.invoice_line) > inv.company_id.lines_invoice:
                    lst = []
                    invoice = self.read(cr, uid, inv.id, [
                        'name', 'type', 'number', 'reference', 'comment',
                        'date_due', 'partner_id', 'address_contact_id',
                        'address_invoice_id', 'partner_contact',
                        'partner_insite', 'partner_ref', 'payment_term',
                        'account_id', 'currency_id', 'invoice_line',
                        'tax_line', 'journal_id', 'period_id', 'user_id'
                    ])
                    invoice.update({
                        'state': 'draft',
                        'number': False,
                        'invoice_line': [],
                        'tax_line': [],
                    })
                    # take the id part of the tuple returned for many2one fields
                    for field in ('address_contact_id', 'address_invoice_id',
                                  'partner_id', 'account_id', 'currency_id',
                                  'payment_term', 'journal_id', 'period_id',
                                  'user_id'):
                        invoice[field] = invoice[field] and invoice[field][0]

                    if hasattr(inv, 'sale_ids'):
                        if self.browse(cr, uid, inv.id, context={}).sale_ids:
                            invoice.update({
                                'sale_ids': [(6, 0, [
                                    i.id for i in self.browse(
                                        cr, uid, inv.id, context={}).sale_ids
                                ])]
                            })

                    inv_id = self.create(cr, uid, invoice)
                    cont = 0
                    lst = inv.invoice_line
                    while cont < inv.company_id.lines_invoice:
                        lst.pop(0)
                        cont += 1
                    for il in lst:
                        self.pool.get('account.invoice.line').write(
                            cr, uid, il.id, {'invoice_id': inv_id})
                    self.button_compute(cr, uid, [inv.id], set_total=True)
            if inv_id:
                wf_service = netsvc.LocalService("workflow")
                self.button_compute(cr, uid, [inv_id], set_total=True)


#                wf_service.trg_validate(uid, 'account.invoice', inv_id, 'invoice_open', cr)
        return True
Exemplo n.º 21
0
    def set_state_locked(self, cr, uid, ids, context=None):

        #
        # XXX - Someone who cares about DST should update this code to handle it.
        #

        wkf_service = netsvc.LocalService('workflow')
        attendance_obj = self.pool.get('hr.attendance')
        detail_obj = self.pool.get('hr.schedule.detail')
        holiday_obj = self.pool.get('hr.holidays')
        for period in self.browse(cr, uid, ids, context=context):
            utc_tz = timezone('UTC')
            dt = datetime.strptime(period.date_start, '%Y-%m-%d %H:%M:%S')
            utcDtStart = utc_tz.localize(dt, is_dst=False)
            dt = datetime.strptime(period.date_end, '%Y-%m-%d %H:%M:%S')
            utcDtEnd = utc_tz.localize(dt, is_dst=False)
            for contract in period.schedule_id.contract_ids:
                employee = contract.employee_id

                # Lock sign-in and sign-out attendance records
                punch_ids = attendance_obj.search(cr, uid, [
                    ('employee_id', '=', employee.id),
                    '&', (
                        'name', '>=', utcDtStart.strftime('%Y-%m-%d %H:%M:%S')),
                    ('name', '<=', utcDtEnd.strftime(
                        '%Y-%m-%d %H:%M:%S')),
                ], order='name', context=context)
                for pid in punch_ids:
                    wkf_service.trg_validate(
                        uid, 'hr.attendance', pid, 'signal_lock', cr)

                # Lock schedules
                detail_ids = detail_obj.search(cr, uid, [
                    ('schedule_id.employee_id', '=', employee.id),
                    '&', (
                        'date_start', '>=', utcDtStart.strftime('%Y-%m-%d %H:%M:%S')),
                    ('date_start', '<=', utcDtEnd.strftime(
                        '%Y-%m-%d %H:%M:%S')),
                ], order='date_start', context=context)
                for did in detail_ids:
                    wkf_service.trg_validate(
                        uid, 'hr.schedule.detail', did, 'signal_lock', cr)

                # Lock holidays/leaves that end in the current period
                holiday_ids = holiday_obj.search(cr, uid, [
                    ('employee_id', '=', employee.id),
                    '&', (
                        'date_to', '>=', utcDtStart.strftime('%Y-%m-%d %H:%M:%S')),
                    ('date_to', '<=', utcDtEnd.strftime(
                        '%Y-%m-%d %H:%M:%S')),
                ],
                    context=context)
                for hid in holiday_ids:
                    holiday_obj.write(
                        cr, uid, [hid], {'payroll_period_state': 'locked'},
                        context=context)

            self.write(cr, uid, period.id, {
                       'state': 'locked'}, context=context)

        return True
Exemplo n.º 22
0
    def _fixup_created_picking(self, cr, uid, ids, line_moves, remain_moves,
                               context):
        move_obj = self.pool.get('stock.move')
        line_obj = self.pool.get('purchase.order.line')
        procurement_obj = self.pool.get('procurement.order')
        wf_service = netsvc.LocalService("workflow")

        proc_to_po = {}
        for purchase in self.browse(cr, uid, ids, context=context):
            # Get list of all procurements which are linked to this PO
            proc_ids = procurement_obj.search(
                cr,
                uid, [('purchase_id', '=', purchase.order_edit_id.id),
                      ('purchase_id', '!=', False),
                      ('state', 'not in', ('done', 'cancel'))],
                context=context)
            proc_to_po[purchase] = proc_ids

            # Remove PO line for all procurements so they all revert back to MTS, or confirmed MTO
            procurement_obj.write(cr, uid, proc_ids, {'purchase_id': False})

        # 3. Finish fixing the pickings
        res = super(PurchaseOrder,
                    self)._fixup_created_picking(cr,
                                                 uid,
                                                 ids,
                                                 line_moves,
                                                 remain_moves,
                                                 context=context)

        for purchase, proc_ids in proc_to_po.iteritems():
            # For each procurement attempt to allocate to this PO
            for proc in procurement_obj.browse(cr,
                                               uid,
                                               proc_ids,
                                               context=context):
                cr.execute('SAVEPOINT procurement')
                failed = False
                try:
                    if proc.state == 'exception':
                        wf_service.trg_validate(uid, 'procurement.order',
                                                proc.id, 'button_restart', cr)
                    wf_service.trg_validate(uid, 'procurement.order', proc.id,
                                            'button_check', cr)
                    procurement_obj.write(cr,
                                          uid, [proc.id],
                                          {'purchase_id': purchase.id},
                                          context=context)
                except osv.except_osv:
                    failed = True
                    cr.execute('ROLLBACK TO SAVEPOINT procurement')
                else:
                    cr.execute('RELEASE SAVEPOINT procurement')

                # For each failed allocation, if the sale line type is MTO, reset the procurement and change back to MTO
                if failed and proc.move_id.sale_line_id and proc.move_id.sale_line_id.type == 'make_to_order':
                    proc.refresh()
                    if proc.state == 'exception':
                        wf_service.trg_validate(uid, 'procurement.order',
                                                proc.id, 'button_restart', cr)
                    proc.write({'procure_method': 'make_to_order'},
                               context=context)
                    wf_service.trg_validate(
                        uid, 'procurement.order', proc.id, 'button_check', cr
                    )  # TODO: Assert we are in the correct workflow step here

        return res
Exemplo n.º 23
0
 def make_mo(self, cr, uid, ids, context=None):
     """ Make Manufacturing(production) order from procurement
     @return: New created Production Orders procurement wise 
     """
     res = {}
     company = self.pool.get('res.users').browse(cr, uid, uid,
                                                 context).company_id
     production_obj = self.pool.get('mrp.production')
     move_obj = self.pool.get('stock.move')
     wf_service = netsvc.LocalService("workflow")
     procurement_obj = self.pool.get('procurement.order')
     for procurement in procurement_obj.browse(cr,
                                               uid,
                                               ids,
                                               context=context):
         res_id = procurement.move_id.id
         loc_id = procurement.location_id.id
         newdate = datetime.strptime(
             procurement.date_planned, '%Y-%m-%d %H:%M:%S') - relativedelta(
                 days=procurement.product_id.product_tmpl_id.produce_delay
                 or 0.0)
         newdate = newdate - relativedelta(days=company.manufacturing_lead)
         produce_id = production_obj.create(
             cr, uid, {
                 'origin':
                 procurement.origin,
                 'product_id':
                 procurement.product_id.id,
                 'product_qty':
                 procurement.product_qty,
                 'product_uom':
                 procurement.product_uom.id,
                 'product_uos_qty':
                 procurement.product_uos and procurement.product_uos_qty
                 or False,
                 'product_uos':
                 procurement.product_uos and procurement.product_uos.id
                 or False,
                 'location_src_id':
                 procurement.location_id.id,
                 'location_dest_id':
                 procurement.location_id.id,
                 'bom_id':
                 procurement.bom_id and procurement.bom_id.id or False,
                 'date_planned':
                 newdate.strftime('%Y-%m-%d %H:%M:%S'),
                 'move_prod_id':
                 res_id,
                 'company_id':
                 procurement.company_id.id,
             })
         res[procurement.id] = produce_id
         self.write(cr, uid, [procurement.id], {'state': 'running'})
         bom_result = production_obj.action_compute(
             cr,
             uid, [produce_id],
             properties=[x.id for x in procurement.property_ids])
         wf_service.trg_validate(uid, 'mrp.production', produce_id,
                                 'button_confirm', cr)
         move_obj.write(cr, uid, [res_id],
                        {'location_id': procurement.location_id.id})
     return res
Exemplo n.º 24
0
    def action_reopen(self, cr, uid, ids, context=None):
        """ Changes SO from to draft.
        @return: True
        """
        _logger = logging.getLogger(__name__)

        _logger.debug('FGF purchase_order action reopen %s' % (ids))
        self.allow_reopen(cr, uid, ids, context=context)
        account_invoice_obj = self.pool['account.invoice']
        stock_picking_obj = self.pool['stock.picking']
        stock_move_obj = self.pool['stock.move']
        report_xml_obj = self.pool['ir.actions.report.xml']
        attachment_obj = self.pool['ir.attachment']
        order_line_obj = self.pool['purchase.order.line']

        now = ' ' + _('Invalid') + time.strftime(' [%Y%m%d %H%M%S]')
        for order in self.browse(cr, uid, ids, context):

            if order.invoice_ids:
                for inv in order.invoice_ids:
                    account_invoice_obj.action_reopen(cr, uid, [inv.id], context=context)
                    if inv.journal_id.update_posted:
                        _logger.debug('FGF purchase_order reopen cancel invoice %s' % (ids))
                        account_invoice_obj.action_cancel(cr, uid, [inv.id], context=context)
                    else:
                        _logger.debug('FGF purchase_order reopen cancel 2 invoice %s' % (ids))
                        account_invoice_obj.write(cr, uid, [inv.id], {'state': 'cancel', 'move_id': False}, context)

            if order.picking_ids:
                for pick in order.picking_ids:
                    _logger.debug('FGF purchase_order reopen picking %s' % (pick.name))
                    stock_picking_obj.action_reopen(cr, uid, [pick.id], context=context)
                    stock_picking_obj.write(cr, uid, [pick.id], {'state': 'cancel'}, context)
                    if pick.move_lines:
                        move_ids = []
                        for m in pick.move_lines:
                            move_ids.append(m.id)
                        stock_move_obj.write(cr, uid, move_ids, {'state': 'cancel'}, context=context)

                        #stock_picking_obj.action_cancel(cr, uid, [pick.id])
            else:
                pick = False

            # for some reason datas_fname has .pdf.pdf extension
            report_ids = report_xml_obj.search(cr, uid, [
                ('model', '=', 'purchase.order'),
                ('attachment', '!=', False)
            ], context=context)

            for report in report_xml_obj.browse(cr, uid, report_ids, context):
                if pick and report.attachment:
                    aname = report.attachment.replace('object', 'pick')
                    if eval(aname):
                        aname = eval(aname) + '.pdf'
                        attachment_ids = attachment_obj.search(cr, uid, [
                            ('res_model', '=', 'purchase.order'),
                            ('datas_fname', '=', aname),
                            ('res_id', '=', order.id)
                        ], context=context)
                        for a in attachment_obj.browse(cr, uid, attachment_ids, context):
                            vals = {
                                'name': a.name.replace('.pdf', now + '.pdf'),
                                'datas_fname': a.datas_fname.replace('.pdf.pdf', now + '.pdf.pdf')
                            }
                            attachment_obj.write(cr, uid, a.id, vals, context)

            self.write(cr, uid, order.id, {'state': 'draft'}, context)
            line_ids = []
            for line in order.order_line:
                line_ids.append(line.id)
            order_line_obj.write(cr, uid, line_ids, {'state': 'draft'}, context)

            wf_service = netsvc.LocalService("workflow")
            wf_service.trg_delete(uid, 'purchase.order', order.id, cr)
            wf_service.trg_create(uid, 'purchase.order', order.id, cr)
        #self.log_purchase(cr, uid, ids, context=context)

        return True
Exemplo n.º 25
0
    def _compute_refund(self, cr, uid, data, mode, context):
        form = data['form']
        pool = pooler.get_pool(cr.dbname)
        reconcile_obj = pool.get('account.move.reconcile')
        account_m_line_obj = pool.get('account.move.line')
        created_inv = []
        date = False
        period = False
        description = False
        for inv in pool.get('account.invoice').browse(cr, uid, data['ids']):
            #if inv.state == 'draft':
            #    raise wizard.except_wizard(_('Error !'), _('Can not %s draft invoice.') % (mode))
            if form['period']:
                period = form['period']
            else:
                period = inv.period_id.id

            if form['date']:
                date = form['date']
                if not form['period']:
                    try:
                        #we try in multy company mode
                        cr.execute("""SELECT id
                                      from account_period where date('%s')
                                      between date_start AND  date_stop and company_id = %s limit 1 """
                                   %
                                   (form['date'], pool.get('res.users').browse(
                                       cr, uid, uid).company_id.id))
                    except:
                        #we try in mono company mode
                        cr.execute("""SELECT id
                                      from account_period where date('%s')
                                      between date_start AND  date_stop  limit 1 """
                                   % (form['date'], ))
                    res = cr.fetchone()
                    if res:
                        period = res[0]

            else:
                date = inv.date_invoice

            #if form['description'] :
            #    description = form['description']
            #else:
            description = inv.name
            refund_id = pool.get('account.invoice').refund(
                cr, uid, [inv.id], date, period, description)
            refund = pool.get('account.invoice').browse(cr, uid, refund_id[0])
            # we compute due date
            #!!!due date = date inv date on formdate
            pool.get('account.invoice').write(cr, uid, [refund.id], {
                'date_due': date,
                'check_total': inv.check_total
            })

            created_inv.append(refund_id[0])
            #if inv is paid we unreconcile
            if mode in ('cancel', 'modify'):
                movelines = inv.move_id.line_id
                #we unreconcile the lines
                to_reconcile_ids = {}
                for line in movelines:
                    #if the account of the line is the as the one in the invoice
                    #we reconcile
                    if line.account_id.id == inv.account_id.id:
                        to_reconcile_ids[line.account_id.id] = [line.id]
                    if type(line.reconcile_id) != osv.orm.browse_null:
                        reconcile_obj.unlink(cr, uid, line.reconcile_id.id)
                #we advance the workflow of the refund to open
                wf_service = netsvc.LocalService('workflow')
                wf_service.trg_validate(uid, 'account.invoice', refund.id,
                                        'invoice_open', cr)
                #we reload the browse record
                refund = pool.get('account.invoice').browse(
                    cr, uid, refund_id[0])
                #we match the line to reconcile
                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)
                #we create a new invoice that is the copy of the original
                if mode == 'modify':
                    invoice = pool.get('account.invoice').read(
                        cr, uid, [inv.id], [
                            'name', 'type', 'number', 'reference', 'comment',
                            'date_due', 'partner_id', 'address_contact_id',
                            'address_invoice_id', 'partner_insite',
                            'partner_contact', 'partner_ref', 'payment_term',
                            'account_id', 'currency_id', 'invoice_line',
                            'tax_line', 'journal_id', 'period_id'
                        ])
                    invoice = invoice[0]
                    del invoice['id']
                    invoice_lines = pool.get('account.invoice.line').read(
                        cr, uid, invoice['invoice_line'])
                    invoice_lines = pool.get(
                        'account.invoice')._refund_cleanup_lines(invoice_lines)
                    tax_lines = pool.get('account.invoice.tax').read(
                        cr, uid, invoice['tax_line'])
                    tax_lines = pool.get(
                        'account.invoice')._refund_cleanup_lines(tax_lines)

                    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
                    })

                    #take the id part of the tuple returned for many2one fields
                    for field in ('address_contact_id', 'address_invoice_id',
                                  'partner_id', 'account_id', 'currency_id',
                                  'payment_term', 'journal_id'):
                        invoice[field] = invoice[field] and invoice[field][0]

                    # create the new invoice
                    inv_id = pool.get('account.invoice').create(
                        cr, uid, invoice, {})
                    # we compute due date
                    if inv.payment_term.id:
                        data = pool.get('account.invoice'
                                        ).onchange_payment_term_date_invoice(
                                            cr, uid, [inv_id],
                                            inv.payment_term.id, date)
                        if 'value' in data and data['value']:
                            pool.get('account.invoice').write(
                                cr, uid, [inv_id], data['value'])
                    created_inv.append(inv_id)

        #we get the view id
        mod_obj = pool.get('ir.model.data')
        act_obj = pool.get('ir.actions.act_window')
        if inv.type == 'out_invoice':
            xml_id = 'action_invoice_tree5'
        elif inv.type == 'in_invoice':
            xml_id = 'action_invoice_tree8'
        elif type == 'out_refund':
            xml_id = 'action_invoice_tree10'
        else:
            xml_id = 'action_invoice_tree12'
        #we get the model
        result = mod_obj._get_id(cr, uid, 'account', xml_id)
        id = mod_obj.read(cr, uid, result, ['res_id'])['res_id']
        # we read the act window
        result = act_obj.read(cr, uid, id)
        result['res_id'] = created_inv

        return result
Exemplo n.º 26
0
    def action_confirm(self, cr, uid, ids, context=None):
        """ Confirms production order.
        @return: Newly generated Shipment Id.
        """
        if not context:
            context={}
        shipment_id = False
        wf_service = netsvc.LocalService("workflow")
        uncompute_ids = filter(lambda x:x, [not x.product_lines and x.id or False for x in self.browse(cr, uid, ids, context=context)])
        self.action_compute(cr, uid, uncompute_ids, context=context)
        move_obj = self.pool.get('stock.move')
        picking_obj = self.pool.get('stock.picking')
        
        
        for production in self.browse(cr, uid, ids, context=context):
            if not production.inverse_production:
                shipment_id = super(mrp_production,self).action_confirm(cr, uid, ids, context=context)
            else:
                if not production.prodlot_id:
                    raise osv.except_osv(_('Inverse Production Error'), _("You must define one lot"))  
                shipment_id = self._make_production_internal_shipment(cr, uid, production, context=context)
                
                for bom2 in production.bom_id.bom_lines:
                    if not bom2.product_id.uos_id:
                        raise osv.except_osv(_('Inverse Production Error'),  _('You must define the unit of sale for product %s.') % (bom2.product_id.name,))
    
                    produce_move_id = self._make_production_produce_line2(cr, uid, production, bom2.product_id,context=context)
                    move = move_obj.browse(cr,uid,produce_move_id,context=context)
                    if move.product_id.uos_id.id <> move.product_id.uom_id.id:
                        move_obj.write(cr,uid,[move.id],{'product_uos': move.product_id.uos_id.id,
                                                         'product_uos_qty': 1})
                    
                    # Take routing location as a Source Location.
                    source_location_id = production.location_src_id.id
                    if production.bom_id.routing_id and production.bom_id.routing_id.location_id:
                        source_location_id = production.bom_id.routing_id.location_id.id
        
                    for line in production.product_lines:
                        consume_move_id = self._make_production_consume_line(cr, uid, line, produce_move_id, source_location_id=source_location_id, context=context)
                        shipment_move_id = self._make_production_internal_shipment_line(cr, uid, line, shipment_id, consume_move_id,\
                                         destination_location_id=source_location_id, context=context)
                        self._make_production_line_procurement(cr, uid, line, shipment_move_id, context=context)
                        
                picking = picking_obj.browse(cr,uid,shipment_id)
                count = 0
                if picking.move_lines:
                    for move in picking.move_lines:
                        count = count + 1
                        
                res = production.product_qty % count
                qty = production.product_qty / count
                if res == 0:
                    for move in picking.move_lines:
                        move_obj.write(cr,uid,[move.id],{'product_qty': qty})
                        if move.move_dest_id:
                            move_obj.write(cr,uid,[move.move_dest_id.id],{'product_qty': qty})
                            
                else:
                    count2 = 0
                    assigned = 0
                    for move in picking.move_lines:
                        count2 = count2 + 1
                        if count == count2:
                            new_qty = production.product_qty - assigned
                            move_obj.write(cr,uid,[move.id],{'product_qty': new_qty})
                            if move.move_dest_id:
                                move_obj.write(cr,uid,[move.move_dest_id.id],{'product_qty': qty})
                        else:
                            assigned = assigned + qty
                            move_obj.write(cr,uid,[move.id],{'product_qty': qty})
                            if move.move_dest_id:
                                move_obj.write(cr,uid,[move.move_dest_id.id],{'product_qty': qty})

                 
                wf_service.trg_validate(uid, 'stock.picking', shipment_id, 'button_confirm', cr)
                production.write({'state':'confirmed'}, context=context)
                message = _("Manufacturing order '%s' is scheduled for the %s.") % (
                    production.name,
                    datetime.strptime(production.date_planned,'%Y-%m-%d %H:%M:%S').strftime('%m/%d/%Y'),
                )
                self.log(cr, uid, production.id, message)
        
        return shipment_id
Exemplo n.º 27
0
 def action_po_assign(self,cr, uid, ids):
     res = super(mrp_procurement,self).action_po_assign(cr, uid, ids)
     wf_service = netsvc.LocalService("workflow")
     wf_service.trg_validate(uid, 'purchase.order', res, 'purchase_confirm', cr)
     wf_service.trg_validate(uid, 'purchase.order', res, 'purchase_approve', cr)
     return res
Exemplo n.º 28
0
    def save_to_mailbox(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        def get_end_value(id, value):
            if len(context['src_rec_ids']) > 1: # Multiple Mail: Gets value from the template
                return self.get_value(cr, uid, template, value, context, id)
            else:
                return value

        mail_ids = []
        template = self._get_template(cr, uid, context)
        screen_vals = self.read(cr, uid, ids[0], [], context)
        if isinstance(screen_vals, list): # Solves a bug in v5.0.16
            screen_vals = screen_vals[0]
        report_record_ids = context['src_rec_ids'][:]
        if screen_vals['single_email'] and len(context['src_rec_ids']) > 1:
            # We send a single email for several records
            context['src_rec_ids'] = context['src_rec_ids'][:1]

        for id in context['src_rec_ids']:
            accounts = self.pool.get('poweremail.core_accounts').read(cr, uid, screen_vals['from'], context=context)
            vals = {
                'pem_from': tools.ustr(accounts['name']) + "<" + tools.ustr(accounts['email_id']) + ">",
                'pem_to': get_end_value(id, screen_vals['to']),
                'pem_cc': get_end_value(id, screen_vals['cc']),
                'pem_bcc': get_end_value(id, screen_vals['bcc']),
                'pem_subject': get_end_value(id, screen_vals['subject']),
                'pem_body_text': get_end_value(id, screen_vals['body_text']),
                'pem_body_html': get_end_value(id, screen_vals['body_html']),
                'pem_account_id': screen_vals['from'],
                'state':'na',
                'mail_type':'multipart/alternative' #Options:'multipart/mixed','multipart/alternative','text/plain','text/html'
            }
            if screen_vals['signature']:
                signature = self.pool.get('res.users').read(cr, uid, uid, ['signature'], context)['signature']
                if signature:
                    vals['pem_body_text'] = tools.ustr(vals['pem_body_text'] or '') + '\n--\n' + signature
                    vals['pem_body_html'] = tools.ustr(vals['pem_body_html'] or '') + signature

            attachment_ids = []

            #Create partly the mail and later update attachments
            mail_id = self.pool.get('poweremail.mailbox').create(cr, uid, vals, context)
            mail_ids.append(mail_id)
            if template.report_template:
                reportname = 'report.' + self.pool.get('ir.actions.report.xml').read(cr, uid, template.report_template.id, ['report_name'], context)['report_name']
                data = {}
                data['model'] = self.pool.get('ir.model').browse(cr, uid, screen_vals['rel_model'], context).model

                # Ensure report is rendered using template's language. If not found, user's launguage is used.
                ctx = context.copy()
                if template.lang:
                    ctx['lang'] = self.get_value(cr, uid, template, template.lang, context, id)
                    lang = self.get_value(cr, uid, template, template.lang, context, id)
                    if len(self.pool.get('res.lang').search(cr, uid, [('name','=',lang)], context = context)):
                        ctx['lang'] = lang
                if not ctx.get('lang', False) or ctx['lang'] == 'False':
                    ctx['lang'] = self.pool.get('res.users').read(cr, uid, uid, ['context_lang'], context)['context_lang']
                service = netsvc.LocalService(reportname)
                if screen_vals['single_email'] and len(report_record_ids) > 1:
                    # The optional attachment will be generated as a single file for all these records
                    (result, format) = service.create(cr, uid, report_record_ids, data, ctx)
                else:
                    (result, format) = service.create(cr, uid, [id], data, ctx)
                attachment_id = self.pool.get('ir.attachment').create(cr, uid, {
                    'name': _('%s (Email Attachment)') % tools.ustr(vals['pem_subject']),
                    'datas': base64.b64encode(result),
                    'datas_fname': tools.ustr(get_end_value(id, screen_vals['report']) or _('Report')) + "." + format,
                    'description': vals['pem_body_text'] or _("No Description"),
                    'res_model': 'poweremail.mailbox',
                    'res_id': mail_id
                }, context)
                attachment_ids.append( attachment_id )

            # Add document attachments
            for attachment_id in screen_vals.get('attachment_ids',[]):
                new_id = self.pool.get('ir.attachment').copy(cr, uid, attachment_id, {
                    'res_model': 'poweremail.mailbox',
                    'res_id': mail_id,
                }, context)
                attachment_ids.append( new_id )

            if attachment_ids:
                self.pool.get('poweremail.mailbox').write(cr, uid, mail_id, {
                    'pem_attachments_ids': [[6, 0, attachment_ids]],
                    'mail_type': 'multipart/mixed'
                }, context)

            # Create a partner event
            if template.partner_event and self._get_template_value(cr, uid, 'partner_event', context):
                name = vals['pem_subject']
                if isinstance(name, str):
                    name = unicode(name, 'utf-8')
                if len(name) > 64:
                    name = name[:61] + '...'

                model = res_id = False
                if template.report_template and self.pool.get('res.request.link').search(cr, uid, [('object','=',data['model'])], context=context):
                    model = data['model']
                    res_id = id
                elif attachment_ids and self.pool.get('res.request.link').search(cr, uid, [('object','=','ir.attachment')], context=context):
                    model = 'ir.attachment'
                    res_id = attachment_ids[0]

                cr.execute("SELECT state from ir_module_module where state='installed' and name = 'mail_gateway'")
                mail_gateway = cr.fetchall()
                if mail_gateway:
                    values = {
                        'history': True,
                        'name': name,
                        'date': time.strftime('%Y-%m-%d %H:%M:%S'),
                        'user_id': uid,
                        'email_from': vals['pem_from'] or None,
                        'email_to': vals['pem_to'] or None,
                        'email_cc': vals['pem_cc'] or None,
                        'email_bcc': vals['pem_bcc'] or None,
                        'message_id': mail_id,
                        'description': vals['pem_body_text'] and vals['pem_body_text'] or vals['pem_body_html'],
                        'partner_id': self.get_value(cr, uid, template, template.partner_event, context, id),
                        'model': model,
                        'res_id': res_id,
                    }
                    self.pool.get('mailgate.message').create(cr, uid, values, context)
        return mail_ids
Exemplo n.º 29
0
    def sale_order_confirmated(self, cr, uid, ids, context=None):
        sale_order_obj = self.pool['sale.order']
        sale_order_line_obj = self.pool['sale.order.line']
        sale_order_confirm_line_obj = self.pool['sale.order.confirm.line']
        wf_service = netsvc.LocalService("workflow")
        
        sale_order_confirm_data = self.read(cr, uid, ids[0], [
            'order_date',
            'sale_order_id',
            'new_sale_order',
            'confirm_line',
            'client_order_ref',
            'order_date',
            'partner_shipping_id',
            'confirm_line_qty'
        ])
        new_order_id = False

        if sale_order_confirm_data['new_sale_order'] or not sale_order_confirm_data['confirm_line_qty'] == len(sale_order_confirm_data['confirm_line']):
            old_sale_order_data = sale_order_obj.read(cr, uid, sale_order_confirm_data['sale_order_id'], ['shop_id', 'partner_id', 'partner_order_id', 'partner_invoice_id', 'pricelist_id', 'sale_version_id', 'version', 'name', 'order_policy', 'picking_policy', 'invoice_quantity', 'section_id', 'categ_id'])
            new_sale_order = {}
            for key in ('shop_id', 'partner_id', 'partner_order_id', 'partner_invoice_id', 'pricelist_id', 'contact_id'):
                new_sale_order[key] = old_sale_order_data.get(key, False) and old_sale_order_data[key][0] or False
            for key in ('picking_policy', 'order_policy', 'invoice_quantity'):
                new_sale_order[key] = old_sale_order_data.get(key, False)
            
            if not old_sale_order_data['sale_version_id']:
                old_sale_order_name = old_sale_order_data['name'] + u" V.2"
                old_sale_order_data['version'] = 2
                new_sale_order['sale_version_id'] = old_sale_order_data['id']
            else:
                old_sale_order_name = old_sale_order_data['name'].split('V')[0] + u"V." + ustr(old_sale_order_data['version'] + 1)
                new_sale_order['sale_version_id'] = old_sale_order_data['sale_version_id'][0]
            
            new_sale_order.update({
                'version': old_sale_order_data['version'] + 1,
                'name': old_sale_order_name,
                'client_order_ref': sale_order_confirm_data['client_order_ref'],
                'date_confirm': sale_order_confirm_data['order_date'],
                'partner_shipping_id': sale_order_confirm_data['partner_shipping_id'][0]
            })
            # qui creo il nuovo sale.order
            context['versioning'] = True
            new_order_id = sale_order_obj.create(cr, uid, new_sale_order, context=context)

            # sequence = 10
            for sale_order_confirm_line_id in sale_order_confirm_data['confirm_line']:
                sale_order_confirm_line_data = sale_order_confirm_line_obj.browse(cr, uid, sale_order_confirm_line_id)
                sale_order_line_vals = self.get_sale_order_line_vals(cr, uid, new_order_id, sale_order_confirm_line_data, context)
                sale_order_line_obj.create(cr, uid, sale_order_line_vals, context=context)

            wf_service.trg_validate(uid, 'sale.order', new_order_id, 'order_confirm', cr)
            # wf_service.trg_validate(uid, 'sale.order', sale_order_confirm_data['sale_order_id'], 'cancel', cr)
            sale_order_obj.write(cr, uid, sale_order_confirm_data['sale_order_id'], {'active': False})

            view_ids = self.pool['ir.model.data'].get_object_reference(cr, uid, 'sale', 'view_order_form')
            return {
                'type': 'ir.actions.act_window',
                'name': 'Sale Order',
                'view_type': 'form',
                'view_mode': 'form',
                'view_id': view_ids and view_ids[1] or False,
                'res_model': 'sale.order',
                'nodestroy': True,
                'target': 'current',
                'res_id': new_order_id,
            }
        else:
            sale_order_obj.write(cr, uid, sale_order_confirm_data['sale_order_id'], {
                'customer_validation': True,
                'client_order_ref': sale_order_confirm_data['client_order_ref'],
                'partner_shipping_id': sale_order_confirm_data['partner_shipping_id'][0]
            }, context)

            wf_service.trg_validate(uid, 'sale.order', sale_order_confirm_data['sale_order_id'], 'order_confirm', cr)
            # need to write after validation
            sale_order_obj.write(cr, uid, sale_order_confirm_data['sale_order_id'], {
                'date_confirm': sale_order_confirm_data['order_date'],
            }, context)
            return {
                'type': 'ir.actions.act_window_close'
            }
Exemplo n.º 30
0
    def action_ship_create(self, cr, uid, ids, *args, **argv):
        # args: Group or not picking. Ej: (0,)
        # argv: Picking from lines. Ej: {'lines_ids': {2: [1], 3: [2, 3]}}
        picking_id = False
        for order in self.browse(cr, uid, ids, context={}):
            output_id = order.shop_id.warehouse_id.lot_output_id.id
            if args and (args[0] == 0):  # Agrupa o no los albaranes
                picking_id = False  # 0: No agrupar        1: Agrupar
            if argv and (len(argv['lines_ids']) >
                         0):  # Picking from sale order lines
                lines_ids = argv['lines_ids'][order.id]
                browse_lines = self.pool.get('sale.order.line').browse(
                    cr, uid, lines_ids, context={})
            else:
                browse_lines = order.order_line  # Picking from sale order
            for line in browse_lines:
                proc_id = False
                date_planned = (DateTime.now() + DateTime.RelativeDateTime(
                    days=line.delay or 0.0)).strftime('%Y-%m-%d')
                if line.state == 'done':
                    continue
                if line.product_id and line.product_id.product_tmpl_id.type in (
                        'product', 'consu'):
                    location_id = order.shop_id.warehouse_id.lot_stock_id.id
                    if not picking_id:  # Create new picking
                        loc_dest_id = order.partner_id.property_stock_customer.id
                        picking_id = self.pool.get('stock.picking').create(
                            cr,
                            uid,
                            {
                                'origin':
                                order.name,
                                'type':
                                'out',
                                'state':
                                'auto',
                                'move_type':
                                order.picking_policy,
                                'loc_move_id':
                                loc_dest_id,
                                'sale_id':
                                order.id,
                                'address_id':
                                order.partner_shipping_id.id,
                                'note':
                                order.note,
                                #'invoice_state': (order.order_policy=='picking' and '2binvoiced') or 'none',
                                'invoice_state':
                                (order.order_policy in ('picking', 'allmanual')
                                 and '2binvoiced') or 'none',
                            })

                    move_id = self.pool.get('stock.move').create(cr, uid, {
                        'name': line.name[:64],
                        'picking_id': picking_id,
                        'product_id': line.product_id.id,
                        'date_planned': date_planned,
                        'product_qty': line.product_uom_qty,
                        'product_uom': line.product_uom.id,
                        'product_uos_qty': line.product_uos_qty,
                        'product_uos': (line.product_uos and line.product_uos.id)\
                                or line.product_uom.id,
                        'product_packaging' : line.product_packaging.id,
                        'address_id' : line.address_allotment_id.id or order.partner_shipping_id.id,
                        'location_id': location_id,
                        'location_dest_id': output_id,
                        'sale_line_id': line.id,
                        #'sale_line_ids':[(6,0,[line.id])],
                        'tracking_id': False,
                        'state': 'waiting',
                        'note': line.notes,
                    })
                    proc_id = self.pool.get('mrp.procurement').create(
                        cr, uid, {
                            'name':
                            order.name,
                            'origin':
                            order.name,
                            'date_planned':
                            date_planned,
                            'product_id':
                            line.product_id.id,
                            'product_qty':
                            line.product_uom_qty,
                            'product_uom':
                            line.product_uom.id,
                            'location_id':
                            order.shop_id.warehouse_id.lot_stock_id.id,
                            'procure_method':
                            line.type,
                            'move_id':
                            move_id,
                            'property_ids':
                            [(6, 0, [x.id for x in line.property_ids])],
                        })
                    wf_service = netsvc.LocalService("workflow")
                    wf_service.trg_validate(uid, 'mrp.procurement', proc_id,
                                            'button_confirm', cr)
                    #self.pool.get('sale.order.line').write(cr, uid, [line.id], {'procurement_id': proc_id})
                    self.pool.get('sale.order.line').write(
                        cr, uid, [line.id], {
                            'procurement_id': proc_id,
                            'state': 'done'
                        })
                elif line.product_id and line.product_id.product_tmpl_id.type == 'service':
                    proc_id = self.pool.get('mrp.procurement').create(
                        cr, uid, {
                            'name':
                            line.name,
                            'origin':
                            order.name,
                            'date_planned':
                            date_planned,
                            'product_id':
                            line.product_id.id,
                            'product_qty':
                            line.product_uom_qty,
                            'product_uom':
                            line.product_uom.id,
                            'location_id':
                            order.shop_id.warehouse_id.lot_stock_id.id,
                            'procure_method':
                            line.type,
                            'property_ids':
                            [(6, 0, [x.id for x in line.property_ids])],
                        })
                    wf_service = netsvc.LocalService("workflow")
                    wf_service.trg_validate(uid, 'mrp.procurement', proc_id,
                                            'button_confirm', cr)
                    self.pool.get('sale.order.line').write(
                        cr, uid, [line.id], {'procurement_id': proc_id})
                else:
                    #
                    # No procurement because no product in the sale.order.line.
                    #
                    pass

            val = {}
            if picking_id:
                wf_service = netsvc.LocalService("workflow")
                wf_service.trg_validate(uid, 'stock.picking', picking_id,
                                        'button_confirm', cr)
                #val = {'picking_ids':[(6,0,[picking_id])]}  # Linea originalmente comentada.

            if order.state == 'shipping_except':
                val['state'] = 'progress'
                if (order.order_policy == 'manual') and order.invoice_ids:
                    val['state'] = 'manual'
            self.write(cr, uid, [order.id], val)
        return True