def _create_invoice(obj, cr, uid, data, context):
     if data['form'].get('new_picking',False):
         data['id'] = data['form']['new_picking']
         data['ids'] = [data['form']['new_picking']]
     pool = pooler.get_pool(cr.dbname)
     picking_obj = pooler.get_pool(cr.dbname).get('stock.picking')
     mod_obj = pool.get('ir.model.data')
     act_obj = pool.get('ir.actions.act_window')
 
     type = data['form']['type']
 
     res = picking_obj.action_invoice_create(cr, uid, data['ids'],
             journal_id=data['form']['journal_id'],group=data['form']['group'],
             type=type, context= context)
 
     invoice_ids = res.values()    
     if not invoice_ids:
         raise  wizard.except_wizard(_('Error'),_('Invoice is not created'))
 
     if type == 'out_invoice':
         xml_id = 'action_invoice_tree5'
     elif type == 'in_invoice':
         xml_id = 'action_invoice_tree8'
     elif type == 'out_refund':
         xml_id = 'action_invoice_tree10'
     else:
         xml_id = 'action_invoice_tree12'
 
     result = mod_obj._get_id(cr, uid, 'account', xml_id)
     id = mod_obj.read(cr, uid, result, ['res_id'])    
     result = act_obj.read(cr, uid, id['res_id'])
     result['res_id'] = invoice_ids    
     return result
    def do_partial(self, cr, uid, ids, context=None):
        """
        Made some integrity check on lines and run the do_incoming_shipment of stock.picking
        """
        # Objects
        picking_obj = self.pool.get('stock.picking')

        if context is None:
            context = {}

        if isinstance(ids, (int, long)):
            ids = [ids]

        if not ids:
            raise osv.except_osv(
                _('Processing Error'),
                _('No data to process !'),
            )

        wizard_brw_list = self.browse(cr, uid, ids, context=context)

        self.integrity_check_quantity(cr, uid, wizard_brw_list, context)
        self.integrity_check_prodlot(cr, uid, wizard_brw_list, context=context)
        # call stock_picking method which returns action call
        res = picking_obj.do_partial_out(cr, uid, ids, context=context)
        return self.return_hook_do_partial(cr, uid, ids, context=context, res=res)
Example #3
0
    def pull_continue_thread(self, cr, uid, ids, context=None):
        _logger = logging.getLogger('pull.rw')
        cr = pooler.get_db(cr.dbname).cursor()
        try:
            wizard = self.browse(cr, uid, ids[0])
            #US-26: Added a check if the zip file has already been imported before
            syncusb = self.pool.get('sync.usb.files')
            md5 = syncusb.md5(wizard.pull_data)
            self.write(cr, uid, ids, {'in_progress': True})
            updates_pulled = update_pull_error = updates_ran = update_run_error = \
            messages_pulled = message_pull_error = messages_ran = message_run_error = 0
            try:
                updates_pulled, update_pull_error, updates_ran, update_run_error, \
                messages_pulled, message_pull_error, messages_ran, message_run_error = self.pool.get('sync.client.entity').usb_pull(cr, uid, wizard.pull_data, context=context)
            except zipfile.BadZipfile:
                raise osv.except_osv(_('Not a Zip File'), _('The file you uploaded was not a valid .zip file'))

            #Update list of pulled files
            syncusb.create(cr, uid, {
                'sum': md5,
                'date': datetime.datetime.now().isoformat(),
            }, context=context)

            # handle returned values
            pull_result = ''
            if not update_pull_error:
                pull_result += 'Pulled %d update(s)' % updates_pulled 
                if not update_run_error:
                    pull_result += '\nRan %s update(s)' % updates_ran
                else:
                    pull_result += '\nError while executing %s update(s): %s' % (updates_ran, update_run_error)
            else:
                pull_result += 'Got an error while pulling %d update(s): %s' % (updates_pulled, update_pull_error)

            if not message_pull_error:
                pull_result += '\nPulled %d message(s)' % messages_pulled 
                if not message_run_error:
                    pull_result += '\nRan %s message(s)' % messages_ran
                else:
                    pull_result += '\nError while executing %s message(s): %s' % (messages_ran, message_run_error)
            else:
                pull_result += '\nGot an error while pulling %d message(s): %s' % (messages_pulled, message_pull_error)

            # If the correct sequence is received, then update this value into the DB for this instance, and inform in the RW sync dialog  
            rw_pull_sequence = context.get('rw_pull_sequence', -1)
            if rw_pull_sequence != -1:
                entity = self._get_entity(cr, uid, context)
                self.pool.get('sync.client.entity').write(cr, uid, entity.id, {'rw_pull_sequence': rw_pull_sequence}, context)        
                pull_result += '\n\nThe pulling file sequence is updated. The next expected sequence is %d' % (rw_pull_sequence + 1)

            vals = {
                'pull_result': pull_result,
                'usb_sync_step': self._get_usb_sync_step(cr, uid, context=context),
                'push_file_visible': False,
            }

            self.write(cr, uid, ids, vals, context=context)
        except osv.except_osv, e:
            self.write(cr, uid, ids, {'pull_result': "Error: %s" % e.value})
            _logger.error("%s : %s" % (tools.ustr(e.value), tools.ustr(traceback.format_exc())))
    def action_move(self, cr, uid, ids, context={}):
        for picking in self.browse(cr, uid, ids):
            if picking.invoice_state == "2binvoiced":
                cr.commit() #ensure that picking has been eventually split
                so = picking.sale_id
                
                #eventually block the picking:
                so_lines_total_price = 0
                for move in picking.move_lines:
                    so_line = self.pool.get('sale.order.line').browse(cr, uid, move.sale_line_id.id)
                    sale_shop = so_line.order_id.shop_id
                    print "so_line.price_subtotal * move.product_qty / so_line.product_uos_qty", so_line.price_subtotal_incl, move.product_qty, so_line.product_uos_qty
                    if so_line.price_subtotal_incl:
                        so_lines_total_price += so_line.price_subtotal_incl * move.product_qty / so_line.product_uos_qty
                    else:
                        so_lines_total_price += so_line.price_subtotal * move.product_qty / so_line.product_uos_qty
                
                print "so_lines_total_price", so_lines_total_price
                if (- so.partner_id.credit) * 1.001 < so_lines_total_price * float(sale_shop.picking_blocking_deposit_percent) / 100.0:
                    raise osv.except_osv(_('Error !'), _("Not enough deposits amount! Sale Shop is configured to block picking if paid amount is below %s percent, that is %s") % (sale_shop.picking_blocking_deposit_percent, so_lines_total_price * float(sale_shop.picking_blocking_deposit_percent) / 100.0))

                
                #then invoice picking:
                data2 ={'form':{'group': 0, 'type':'out_invoice', 'journal_id': sale_shop.picking_invoicing_journal_id.id}, 'ids':[picking.id], 'id': picking.id}
                self._create_invoice(cr, uid, data2, {}) #TODO real context


            super(stock_picking, self).action_move(cr, uid, ids, context) #actually perform the move
Example #5
0
 def select_product(self, cr, uid, ids, context=None):
     """
          To get the product and quantity and add in order .
          @param self: The object pointer.
          @param cr: A database cursor
          @param uid: ID of the user currently logged in
          @param context: A standard dictionary
          @return : Return the add product form again for adding more product
     """
     if context is None:
         context = {}
     this = self.browse(cr, uid, ids[0], context=context)
     record_id = context and context.get('active_id', False)
     assert record_id, _('Active ID is not found')
     if record_id:
         order_obj = self.pool.get('pos.order')
         order_obj.add_product(cr, uid, record_id, this.product_id.id, this.quantity, context=context)
     return {
         'name': _('Add Product'),
         'view_type': 'form',
         'view_mode': 'form',
         'res_model': 'pos.add.product',
         'view_id': False,
         'target': 'new',
         'views': False,
         'type': 'ir.actions.act_window',
     }
    def import_all(self, cr, uid, ids, context=None):
        
#        """Import all sugarcrm data into openerp module"""
        keys, module_list = self.get_key(cr, uid, ids, context)
        if not keys:
            raise osv.except_osv(_('Warning !'), _('Select Module to Import.'))
        key_list = module_list.keys()
        for module in key_list :
            module = module_list[module]
            state = self._module_installed(cr,uid,module,context=context)
            if state == False:
                keys =  ', '.join(key_list)
                raise osv.except_osv(_('Error !!'), _("%s data required %s Module to be installed, Please install %s module") %(keys,module,module))
        url = self.parse_valid_url(context)
        context.update({'url': url})
        imp = sugar_import(self, cr, uid, context.get('instance_name'), "import_sugarcrm", context.get('email_user'), context)
        imp.set_table_list(keys)
        imp.start()
        obj_model = self.pool.get('ir.model.data')
        model_data_ids = obj_model.search(cr,uid,[('model','=','ir.ui.view'),('name','=','import.message.form')])
        resource_id = obj_model.read(cr, uid, model_data_ids, fields=['res_id'])
        return {
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'import.message',
                'views': [(resource_id,'form')],
                'type': 'ir.actions.act_window',
                'target': 'new',
            }
 def initialize(self):
     #login
     PortType,sessionid = sugar.login(self.context.get('username',''), self.context.get('password',''), self.context.get('url',''))
     if sessionid == '-1':
         raise osv.except_osv(_('Error !'), _('Authentication error !\nBad Username or Password or bad SugarSoap Api url !'))
     self.context['port'] = PortType
     self.context['session_id'] = sessionid
Example #8
0
    def create(self, cr, uid, vals, context=None):

        if context is None:
            context = {}

        if 'emitido' in vals:
            vals['sprice_subtotal']  = self.pool.get('account.invoice').estruct_dig(cr, uid, str(vals['emitido']))
        else:
            if 'recibido' in vals:
                 vals['sprice_subtotal'] = self.pool.get('account.invoice').estruct_dig(cr, uid, str(vals['recibido']))    


        if 'expedicion_id' in vals and type(vals['expedicion_id']) == tuple:
            vals['expedicion_id'] = vals['expedicion_id'][0]
            vals['expedicion_id_aux'] = vals['expedicion_id']   
        res = super(account_invoice_line,self).create(cr, uid, vals, context=context)
        lin = self.browse(cr, uid, res)
        
        if ('expedicion_id' in vals) and (str(vals['expedicion_id']) !='False')  and (not 'afecta' in vals) :
            raise osv.except_osv(_('Aviso'),_('Tienes que rellenar el campo Afecta en todas las lineas con expedición\n\n (Se asigna automáticamente la expedición de la factura a todas las lineas)'))

       

        if lin.expedicion_id:
            lin.expedicion_id.recalcular()        

        if lin.invoice_id.type == 'out_invoice' or lin.invoice_id.type == 'in_refund':
            lin.write({'emitido':lin.price_subtotal, 'nfactura':lin.invoice_id.number})
        else:
            lin.write({'recibido':lin.price_subtotal, 'nfactura':lin.invoice_id.number})
        return res
Example #9
0
    def account_move_get(self, cr, uid, voucher_id, context=None):
     
      
        seq_obj = self.pool.get('ir.sequence')
        voucher_brw = self.pool.get('account.voucher').browse(cr,uid,voucher_id,context)
        if voucher_brw.number:
            name = voucher_brw.number
        elif voucher_brw.journal_id.sequence_id:
            name = seq_obj.next_by_id(cr, uid, voucher_brw.journal_id.sequence_id.id)
        else:
            raise osv.except_osv(_('Error !'),
                        _('Please define a sequence on the journal !'))
        if not voucher_brw.reference:
            ref = name.replace('/','')
        else:
            ref = voucher_brw.reference

        print ' voucher_brw.fecha     '+str( voucher_brw.fecha)+'    '+str(voucher_brw.date)

        move = {
            'name': name,
            'journal_id': voucher_brw.journal_id.id,
            'narration': voucher_brw.narration,
            'date': voucher_brw.fecha or voucher_brw.date,
            'ref': ref,
            'period_id': voucher_brw.period_id and voucher_brw.period_id.id or False
        }
        return move
def _create_pos(obj, cr, uid, data, context):

    pool = pooler.get_pool(cr.dbname)
    pos_obj = pool.get('pos.order')
    patient_obj = pool.get('medical.patient')
    lab_test_obj = pool.get('medical.patient.lab.test')#lab_test_ids

    pos_data={}
    
    patient = patient_obj.browse( cr, uid, data['ids'])[0]
    if patient.name.insurance:
        pos_data['partner_id'] = patient.name.insurance[0].company.id
        pos_data['note']="Patient name :"+patient.name.name+" with insurance No. : "+patient.name.insurance[0].name
    else:
        pos_data['partner_id'] = patient.name.id
    
    lab_test_ids = lab_test_obj.search(cr, uid, [('doctor_id','=',data['form']['doctor_id']),('state','=','draft'),('patient_id','=',patient.id)])
    test_line=[]
    for test in lab_test_obj.browse(cr, uid, lab_test_ids):
        test_line.append((0,0,{'product_id':test.name.product_id.id,
                                'qty':1,
                                'price_unit':test.name.product_id.lst_price}))
    if test_line:
        pos_data['lines'] = test_line
        pos_id = pos_obj.create(cr, uid, pos_data)

        return {
            'domain': "[('id','=', "+str(pos_id)+")]",
            'name': 'POS',
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'pos.order',
            'type': 'ir.actions.act_window'
        }
    raise  wizard.except_wizard(_('UserError'),_('No Lab test exist for selected Dr.'))
    def _repair_action(self, cr, uid, data, context):
        """
        Action that repairs the invoice numbers 
        """
        logger = netsvc.Logger()

        logger.notifyChannel("l10n_es_account_invoice_sequence_fix", netsvc.LOG_DEBUG, "Searching for invoices.")

        invoice_facade = pooler.get_pool(cr.dbname).get('account.invoice')
        invoice_ids = invoice_facade.search(cr, uid, [('move_id','<>','')], limit=0, order='id', context=context)

        if len(invoice_ids) == 0:
            raise wizard.except_wizard(_('No Data Available'), _('No records found for your selection!'))

        logger.notifyChannel("l10n_es_account_invoice_sequence_fix", netsvc.LOG_DEBUG, "Repairing %d invoices." % len(invoice_ids))

        for invoice in invoice_facade.browse(cr, uid, invoice_ids):
            move_id = invoice.move_id or False
            if move_id:
                cr.execute('UPDATE account_invoice SET invoice_number=%s WHERE id=%s', (move_id.id, invoice.id))

        logger.notifyChannel("l10n_es_account_invoice_sequence_fix", netsvc.LOG_DEBUG, "%d invoices repaired." % len(invoice_ids))

        vals = {
        }
        return vals
Example #12
0
    def create_aeroo_report(self, cr, uid, ids, data, report_xml, context=None, output='odt'):
        """ Returns an aeroo report generated with aeroolib
        """
        pool = pooler.get_pool(cr.dbname)
        if not context:
            context={}
        context = context.copy()
        if self.name=='report.printscreen.list':
            context['model'] = data['model']
            context['ids'] = ids
        
        print_id = context.get('print_id', False)
        aeroo_print = self.active_prints[print_id] # Aeroo print object
        aeroo_print.subreports = []
        #self.oo_subreports[print_id] = []
        objects = self.getObjects_mod(cr, uid, ids, report_xml.report_type, context) or []
        oo_parser = self.parser(cr, uid, self.name2, context=context)
        oo_parser.localcontext.update(context)
        oo_parser.set_context(objects, data, ids, report_xml.report_type)

        self.set_xml_data_fields(objects, oo_parser) # Get/Set XML

        oo_parser.localcontext['data'] = data
        oo_parser.localcontext['user_lang'] = context.get('lang', False)
        if len(objects)>0:
            oo_parser.localcontext['o'] = objects[0]
        xfunc = ExtraFunctions(cr, uid, report_xml.id, oo_parser.localcontext)
        oo_parser.localcontext.update(xfunc.functions)

        #company_id = objects and 'company_id' in objects[0]._table._columns.keys() and \
        #                        objects[0].company_id and objects[0].company_id.id or False # for object company usage
        company_id = False
        style_io=self.get_styles_file(cr, uid, report_xml, company=company_id, context=context)

        if report_xml.tml_source in ('file', 'database'):
            if not report_xml.report_sxw_content or report_xml.report_sxw_content=='False':
                raise osv.except_osv(_('Error!'), _('No template found!'))
            file_data = base64.decodestring(report_xml.report_sxw_content)
        else:
            file_data = self.get_other_template(cr, uid, data, oo_parser)
        if not file_data and not report_xml.report_sxw_content:
            self.logger("End process %s (%s), elapsed time: %s" % (self.name, self.table, time.time() - aeroo_print.start_time), logging.INFO) # debug mode
            return False, output
        #elif file_data:
        #    template_io = StringIO()
        #    template_io.write(file_data or report_xml.report_sxw_content)
        #    basic = Template(source=template_io, styles=style_io)
        else:
            if report_xml.preload_mode == 'preload' and hasattr(self, 'serializer'):
                serializer = copy.copy(self.serializer)
                serializer.apply_style(style_io)
                template_io = serializer.template
            else:
                template_io = StringIO()
                template_io.write(file_data or base64.decodestring(report_xml.report_sxw_content) )
                serializer = OOSerializer(template_io, oo_styles=style_io)
            try:
                basic = Template(source=template_io, serializer=serializer)
            except Exception, e:
                self._raise_exception(e, print_id)
Example #13
0
    def subscribe(self, cr, uid, ids, *args):
        """
        Subscribe Rule for auditing changes on object and apply shortcut for logs on that object.
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param ids: List of Auddittrail Rule’s IDs.
        @return: True
        """
        obj_action = self.pool.get('ir.actions.act_window')
        obj_model = self.pool.get('ir.model.data')
        #start Loop
        for thisrule in self.browse(cr, uid, ids):
            obj = self.pool.get(thisrule.object_id.model)
            if not obj:
                raise osv.except_osv(
                        _('WARNING: audittrail is not part of the pool'),
                        _('Change audittrail depends -- Setting rule as DRAFT'))
                self.write(cr, uid, [thisrule.id], {"state": "draft"})
            val = {
                 "name": 'View Log',
                 "res_model": 'audittrail.log',
                 "src_model": thisrule.object_id.model,
                 "domain": "[('object_id','=', " + str(thisrule.object_id.id) + "), ('res_id', '=', active_id)]"

            }
            action_id = obj_action.create(cr, 1, val)
            self.write(cr, uid, [thisrule.id], {"state": "subscribed", "action_id": action_id})
            keyword = 'client_action_relate'
            value = 'ir.actions.act_window,' + str(action_id)
            res = obj_model.ir_set(cr, 1, 'action', keyword, 'View_log_' + thisrule.object_id.model, [thisrule.object_id.model], value, replace=True, isobject=True, xml_id=False)
            #End Loop
        return True
Example #14
0
    def product_id_change(self,cr, uid, ids, pricelist, product, qty, uom,
            partner_id, date_order=False, fiscal_position=False, date_planned=False,
            name=False, price_unit=False, notes=False, context=None):
        warning = {}
        if not product:
            return {'value': {'price_unit': 0.0, 'name':'','notes':'', 'product_uom' : False}, 'domain':{'product_uom':[]}}
        product_obj = self.pool.get('product.product')
        product_info = product_obj.browse(cr, uid, product)
        title = False
        message = False

        if product_info.purchase_line_warn != 'no-message':
            if product_info.purchase_line_warn == 'block':
                raise osv.except_osv(_('Alert for %s !') % (product_info.name), product_info.purchase_line_warn_msg)
            title = _("Warning for %s") % product_info.name
            message = product_info.purchase_line_warn_msg
            warning['title'] = title
            warning['message'] = message

        result =  super(purchase_order_line, self).product_id_change(cr, uid, ids, pricelist, product, qty, uom,
            partner_id, date_order, fiscal_position)

        if result.get('warning',False):
            warning['title'] = title and title +' & '+result['warning']['title'] or result['warning']['title']
            warning['message'] = message and message +'\n\n'+result['warning']['message'] or result['warning']['message']

        return {'value': result.get('value',{}), 'warning':warning}
    def _empty(self, cr, uid, context=None):
        close = []
        up = []
        obj_tb = self.pool.get('project.gtd.timebox')
        obj_task = self.pool.get('project.task')

        if context is None:
            context = {}
        if not 'active_id' in context:
            return {}

        ids = obj_tb.search(cr, uid, [], context=context)
        if not len(ids):
            raise osv.except_osv(_('Error !'), _('No timebox child of this one !'))
        tids = obj_task.search(cr, uid, [('timebox_id', '=', context['active_id'])])
        for task in obj_task.browse(cr, uid, tids, context):
            if (task.state in ('cancel','done')) or (task.user_id.id <> uid):
                close.append(task.id)
            else:
                up.append(task.id)
        if up:
            obj_task.write(cr, uid, up, {'timebox_id':ids[0]})
        if close:
            obj_task.write(cr, uid, close, {'timebox_id':False})
        return {}
Example #16
0
    def onchange_partner_id(self, cr, uid, ids, type, partner_id,
            date_invoice=False, payment_term=False, partner_bank_id=False, company_id=False):
        if not partner_id:
            return {'value': {
            'account_id': False,
            'payment_term': False,
            }
        }
        warning = {}
        title = False
        message = False
        partner = self.pool.get('res.partner').browse(cr, uid, partner_id)
        if partner.invoice_warn != 'no-message':
            if partner.invoice_warn == 'block':
                raise osv.except_osv(_('Alert for %s !') % (partner.name), partner.invoice_warn_msg)

            title = _("Warning for %s") % partner.name
            message = partner.invoice_warn_msg
            warning = {
                'title': title,
                'message': message
                }
        result =  super(account_invoice, self).onchange_partner_id(cr, uid, ids, type, partner_id,
            date_invoice=False, payment_term=False, partner_bank_id=False)

        if result.get('warning',False):
            warning['title'] = title and title +' & '+ result['warning']['title'] or result['warning']['title']
            warning['message'] = message and message + ' ' + result['warning']['message'] or result['warning']['message']

        return {'value': result.get('value',{}), 'warning':warning}
Example #17
0
    def product_id_change(self, cr, uid, ids, pricelist, product, qty=0,
            uom=False, qty_uos=0, uos=False, name='', partner_id=False,
            lang=False, update_tax=True, date_order=False, packaging=False,
            fiscal_position=False, flag=False, context=None):
        warning = {}
        if not product:
            return {'value': {'th_weight' : 0, 'product_packaging': False,
                'product_uos_qty': qty}, 'domain': {'product_uom': [],
                   'product_uos': []}}
        product_obj = self.pool.get('product.product')
        product_info = product_obj.browse(cr, uid, product)
        title = False
        message = False

        if product_info.sale_line_warn != 'no-message':
            if product_info.sale_line_warn == 'block':
                raise osv.except_osv(_('Alert for %s !') % (product_info.name), product_info.sale_line_warn_msg)
            title = _("Warning for %s") % product_info.name
            message = product_info.sale_line_warn_msg
            warning['title'] = title
            warning['message'] = message

        result =  super(sale_order_line, self).product_id_change( cr, uid, ids, pricelist, product, qty,
            uom, qty_uos, uos, name, partner_id,
            lang, update_tax, date_order, packaging, fiscal_position, flag, context=context)

        if result.get('warning',False):
            warning['title'] = title and title +' & '+result['warning']['title'] or result['warning']['title']
            warning['message'] = message and message +'\n\n'+result['warning']['message'] or result['warning']['message']

        return {'value': result.get('value',{}), 'warning':warning}
    def check_backlogs(self, cr, uid, ids, context=None):
        backlog_obj = self.pool.get('project.scrum.product.backlog')
        mod_obj = self.pool.get('ir.model.data')
        p_list = []
        if context is None:
            context = {}
        #If only one product backlog selected for merging then show an exception
        if len(context['active_ids']) < 2:
            raise osv.except_osv(_('Warning'),_('Please select at least two product Backlogs'))
        #If any of the backlog state is done then it will show an exception
        for backlogs in backlog_obj.browse(cr, uid, context['active_ids'], context=context):
            p_list.append(backlogs.project_id.id)

        #For checking whether project id's are different or same.
        if len(set(p_list)) != 1:
            context.update({'scrum_projects': True})
            model_data_ids = mod_obj.search(cr, uid,[('model','=','ir.ui.view'),('name','=','scrum_merge_project_id_view')], context=context)
            resource_id = mod_obj.read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
            return {
                'context': context,
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'project.scrum.backlog.merge',
                'views': [(resource_id,'form')],
                'type': 'ir.actions.act_window',
                'target': 'new',
            }
        return self.do_merge(cr, uid, ids, context=context)
 def line2bank(self, cr, uid, ids, payment_type=None, context=None):
     """
     Try to return for each Ledger Posting line a corresponding bank
     account according to the payment type.  This work using one of
     the bank of the partner defined on the invoice eventually
     associated to the line.
     Return the first suitable bank for the corresponding partner.
     """
     payment_mode_obj = self.pool.get('payment.mode')
     line2bank = {}
     if not ids:
         return {}
     bank_type = payment_mode_obj.suitable_bank_types(cr, uid, payment_type,
             context=context)
     for line in self.browse(cr, uid, ids, context=context):
         line2bank[line.id] = False
         if line.invoice and line.invoice.partner_bank_id:
             line2bank[line.id] = line.invoice.partner_bank_id.id
         elif line.partner_id:
             if not line.partner_id.bank_ids:
                 line2bank[line.id] = False
             else:
                 for bank in line.partner_id.bank_ids:
                     if bank.state in bank_type:
                         line2bank[line.id] = bank.id
                         break
             if line.id not in line2bank and line.partner_id.bank_ids:
                 line2bank[line.id] = line.partner_id.bank_ids[0].id
         else:
             raise osv.except_osv(_('Error !'), _('No partner defined on entry line'))
     return line2bank
    def default_get(self, cr, uid, fields, context=None):
        """
        This function gets default values
        @param self: The object pointer
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param fields: List of fields for default value
        @param context: A standard dictionary for contextual values

        @return : default values of fields.
        """
        if context is None:
            context = {}
        meeting_pool = self.pool.get('project.scrum.meeting')
        record_ids = context and context.get('active_ids', []) or []
        res = super(project_scrum_email, self).default_get(cr, uid, fields, context=context)
        for meeting in meeting_pool.browse(cr, uid, record_ids, context=context):
            sprint = meeting.sprint_id
            if 'scrum_master_email' in fields:
                res.update({'scrum_master_email': sprint.scrum_master_id and sprint.scrum_master_id.user_email or False})
            if 'product_owner_email' in fields:
                res.update({'product_owner_email': sprint.product_owner_id and sprint.product_owner_id.user_email or False})
            if 'subject' in fields:
                subject = _("Scrum Meeting : %s") %(meeting.date)
                res.update({'subject': subject})
            if 'message' in fields:
                message = _("Hello  , \nI am sending you Scrum Meeting : %s for the Sprint  '%s' of Project '%s'") %(meeting.date, sprint.name, sprint.project_id.name)
                res.update({'message': message})
        return res
Example #21
0
    def export(self, cr, uid, id, options=None, context=None):
        if options is None:
            options = []
        if not context:
            context={}
        context.update({'force_export':True})
        shop_ids = self.read(cr, uid, id, context=context)[0]['shop']
        sale_shop_obj = self.pool.get('sale.shop')
        product_obj = self.pool.get('product.product')
        context['force_product_ids'] = context['active_ids']

        for shop in sale_shop_obj.browse(cr, uid, shop_ids, context=context):
            context['shop_id'] = shop.id
            if not shop.referential_id:
                raise osv.except_osv(_("User Error"), _("The shop '%s' doesn't have any external referential are you sure that it's an externe sale shop? If yes syncronize it before exporting product")%(shop.name,))
            connection = shop.referential_id.external_connection()
            context['conn_obj'] = connection
            none_exportable_product = set(context['force_product_ids']) - set([product.id for product in shop.exportable_product_ids])
            if none_exportable_product:
                products = ', '.join([x['name'] for x in product_obj.read(cr, uid, list(none_exportable_product), fields = ['name'], context=context)])
                raise osv.except_osv(_("User Error"), _("The product '%s' can not be exported to the shop '%s'. \nPlease check : \n    - if their are in the root category \n    - if the website option is correctly configured. \n    - if the check box Magento exportable is checked")%(products, shop.name))

            if 'export_product' in options:
                sale_shop_obj.export_products(cr, uid, shop, context)
            if 'export_inventory' in options:
                product_obj.export_inventory(
                    cr, uid,
                    context['force_product_ids'],
                    shop.id,
                    connection,
                    context=context)
            
        return {'type': 'ir.actions.act_window_close'}
    def validate(self, cr, uid, ids, context=None):
        # Add a validation process that all periods being posted is still open
        for _obj in self.browse(cr, uid, ids, context=context):
            if _obj.period_id.state in ('done'):
                raise osv.except_osv(_('Error!'), _("Move %s is dated in closed period.") % (_obj.name))

        return super(account_move, self).validate(cr, uid, ids, context=context)
    def _split(self, cr, uid, id, quantity, context):
        """
        Sets the quantity to produce for production with id 'id' to 'quantity' and
        creates a new production order with the deference between current amount and
        the new quantity.
        """

        production = self.browse(cr, uid, id, context)
        if production.state != 'confirmed':
          #  raise osv.except_osv(_('Error !'), _('Production order "%s" is not in "Waiting Goods" state.') % production.name)
          pass
        if quantity >= production.product_qty:
            raise osv.except_osv(_('Error !'), _('Quantity must be greater than production quantity in order "%s" (%s / %s)') % (production.name, quantity, production.product_qty))

        # Create new production, but ensure product_lines is kept empty.
        new_production_id = self.copy(cr, uid, id, {
            'product_lines': [],
            'move_prod_id': False,
            'product_qty':  quantity,
        }, context)

        self.write(cr, uid, production.id, {
            'product_qty': production.product_qty -quantity,
            'product_lines': [],
        }, context)

        self.action_compute(cr, uid, [ new_production_id])
        self._change_prod_qty( cr, uid, production.id ,production.product_qty-quantity, context)
        workflow = netsvc.LocalService("workflow")
        workflow.trg_validate(uid, 'mrp.production', new_production_id, 'button_confirm', cr)

        return [id, new_production_id]
    def view_init(self, cr, uid, fields_list, context=None):
        if context is None:
            context = {}
        super(pos_make_payment, self).view_init(cr, uid, fields_list, context=context)
        active_id = context and context.get('active_id', False) or False
        if active_id:
            order = self.pool.get('pos.order').browse(cr, uid, active_id, context=context)

            partner_id = order.partner_id and order.partner_id or False
            if not partner_id:
                partner_id = order.partner_id or False

            ''' Check if the partner has other pickings with the same products'''
            pos_warn_sale_order = order.pos_warn_sale_order or False
            if pos_warn_sale_order and partner_id:
                address_ids = [adr.id for adr in partner_id.address]
                picking_obj = self.pool.get('stock.picking')
                picking_ids = picking_obj.search(cr, uid, [
                        ('state', 'in', ['auto','confirmed','assigned']),
                        ('id', '!=', order.picking_id.id),
                        ('address_id', 'in', address_ids),
                    ])
                if picking_ids:
                    product_ids = [line.product_id.id for line in order.lines]
                    for picking in picking_obj.browse(cr, uid, picking_ids, context):
                        for m in picking.move_lines:
                            if m.product_id.id in product_ids:
                                product = (m.product_id.name).encode('utf-8')
                                sale_order_info = (picking.origin and picking.name + '-' + picking.origin or picking.name).encode('utf-8')
                                raise osv.except_osv(_('Warning! Product already ordered'),
                                    _("Product %s is already ordered in picking %s." \
                                    " If you want to order it again ignoring this picking,"\
                                    " you must uncheck the boolean field"\
                                    " 'Product in sale order warning'.") % (product, sale_order_info))
        return True
    def _change_prod_qty(self, cr, uid, id ,quantity, context):

        prod_obj = self.pool.get('mrp.production')
        prod = prod_obj.browse(cr, uid, id , context=context)
        prod_obj.write(cr, uid, prod.id, {'product_qty' : quantity })
        prod_obj.action_compute(cr, uid, [prod.id])

        move_lines_obj = self.pool.get('stock.move')
        for move in prod.move_lines:
            bom_point = prod.bom_id
            bom_id = prod.bom_id.id
            if not bom_point:
                bom_id = self.pool.get('mrp.bom')._bom_find(cr, uid, prod.product_id.id, prod.product_uom.id)
                if not bom_id:
                    raise osv.except_osv(_('Error'), _("Couldn't find bill of material for product"))
                self.write(cr, uid, [prod.id], {'bom_id': bom_id})
                bom_point = self.pool.get('mrp.bom').browse(cr, uid, [bom_id])[0]

            if not bom_id:
                raise osv.except_osv(_('Error'), _("Couldn't find bill of material for product"))

            factor = prod.product_qty * prod.product_uom.factor / bom_point.product_uom.factor
            res = self.pool.get('mrp.bom')._bom_explode(cr, uid, bom_point, factor / bom_point.product_qty, [])
            for r in res[0]:
                if r['product_id']== move.product_id.id:
                    move_lines_obj.write(cr, uid,move.id, {'product_qty' :  r['product_qty']})

        product_lines_obj = self.pool.get('mrp.production.product.line')

        for m in prod.move_created_ids:
            move_lines_obj.write(cr, uid,m.id, {'product_qty' : quantity})

        return {}
 def create_balance_line(self, cr, uid, move, res_user, name, context=None):    
     move_line_obj = self.pool.get('account.move.line')
     amount = self.get_balance_amount(cr, uid, move.id, context=context)
     if amount > 0:
         account_id = res_user.company_id.expense_currency_exchange_account_id.id
         if not account_id:
             raise osv.except_osv(_('Error!'), _('The company have not associated a expense account.\n'))
         credit = amount
         debit = 0.00
     else:
         account_id = res_user.company_id.income_currency_exchange_account_id.id
         if not account_id:
             raise osv.except_osv(_('Error!'), _('The company have not associated a income account.\n'))
         credit = 0.00
         debit = amount * -1    
         
     move_line = {
                          'name': name,
                          'ref': name,
                          'debit': debit,
                          'credit': credit,
                          'account_id': account_id,
                          'move_id': move.id,
                          'period_id': move.period_id.id,
                          'journal_id': move.journal_id.id,
                          'partner_id': False,
                          'currency_id': False,
                          'amount_currency': 0.00,
                          'state': 'valid',
                          'company_id': res_user.company_id.id,
                          }
     new_move_line_id = move_line_obj.create(cr, uid, move_line, context=context)
     return new_move_line_id
Example #27
0
    def check_buy(self, cr, uid, ids):
        """ Checks product type.
        @return: True or Product Id.
        """
        user = self.pool.get('res.users').browse(cr, uid, uid)
        partner_obj = self.pool.get('res.partner')
        for procurement in self.browse(cr, uid, ids):
            if procurement.product_id.product_tmpl_id.supply_method <> 'buy':
                return False
            if not procurement.product_id.seller_ids:
                cr.execute('update procurement_order set message=%s where id=%s',
                        (_('No supplier defined for this product !'), procurement.id))
                return False
            partner = procurement.product_id.seller_id #Taken Main Supplier of Product of Procurement.

            if not partner:
                cr.execute('update procurement_order set message=%s where id=%s',
                           (_('No default supplier defined for this product'), procurement.id))
                return False

            if user.company_id and user.company_id.partner_id:
                if partner.id == user.company_id.partner_id.id:
                    return False

            address_id = partner_obj.address_get(cr, uid, [partner.id], ['delivery'])['delivery']
            if not address_id:
                cr.execute('update procurement_order set message=%s where id=%s',
                        (_('No address defined for the supplier'), procurement.id))
                return False
        return True
Example #28
0
    def create(self, cr, uid, vals, context=None):
        if context is None:
            context = {}
        vals['parent_id'] = context.get('parent_id', False) or vals.get('parent_id', False)
        if not vals['parent_id']:
            vals['parent_id'] = self.pool.get('document.directory')._get_root_directory(cr,uid, context)
        if not vals.get('res_id', False) and context.get('default_res_id', False):
            vals['res_id'] = context.get('default_res_id', False)
        if not vals.get('res_model', False) and context.get('default_res_model', False):
            vals['res_model'] = context.get('default_res_model', False)
        if vals.get('res_id', False) and vals.get('res_model', False) \
                and not vals.get('partner_id', False):
            vals['partner_id'] = self.__get_partner_id(cr, uid, \
                vals['res_model'], vals['res_id'], context)

        datas = None
        if vals.get('link', False) :
            import urllib
            datas = base64.encodestring(urllib.urlopen(vals['link']).read())
        else:
            datas = vals.get('datas', False)

        if datas:
            vals['file_size'] = len(datas)
        else:
            if vals.get('file_size'):
                del vals['file_size']
        if not self._check_duplication(cr, uid, vals):
            raise osv.except_osv(_('ValidateError'), _('File name must be unique!'))
        result = super(document_file, self).create(cr, uid, vals, context)
        cr.commit() # ?
        return result
    def _send_mails(self, cr, uid, data, context):
        
        import re
        p = pooler.get_pool(cr.dbname)
    
        user = p.get('res.users').browse(cr, uid, uid, context)
        file_name = user.company_id.name.replace(' ','_')+'_'+_('Sale_Order')
        
        default_smtpserver_id = p.get('email.smtpclient').search(cr, uid, [('users_id','=',uid), ('pstate','=','running')], context=None)
        if default_smtpserver_id:
            default_smtpserver_id = default_smtpserver_id[0]
        else:
            raise osv.except_osv(_('Error'), 
                                 _('Can\'t send email, please check whether SMTP client has been defined and you have permission to access!'))
        
        attachments = data['form']['attachment_file']
        attachments = [attachments] or []
        nbr = 0
        for email in data['form']['to'].split(','):
            state = p.get('email.smtpclient').send_email(cr, uid, default_smtpserver_id, email, data['form']['subject'], data['form']['text'], attachments)
            if not state:
                raise osv.except_osv(_('Error sending email'), _('Please check the Server Configuration!'))
            nbr += 1

        return {'email_sent': nbr}
Example #30
0
    def refund_sheet(self, cr, uid, ids, context=None):
        mod_obj = self.pool.get('ir.model.data')
        wf_service = netsvc.LocalService("workflow")
        for payslip in self.browse(cr, uid, ids, context=context):
            id_copy = self.copy(cr, uid, payslip.id, {'credit_note': True, 'name': _('Refund: ')+payslip.name}, context=context)
            self.compute_sheet(cr, uid, [id_copy], context=context)
            wf_service.trg_validate(uid, 'hr.payslip', id_copy, 'hr_verify_sheet', cr)
            wf_service.trg_validate(uid, 'hr.payslip', id_copy, 'process_sheet', cr)

        form_id = mod_obj.get_object_reference(cr, uid, 'hr_payroll', 'view_hr_payslip_form')
        form_res = form_id and form_id[1] or False
        tree_id = mod_obj.get_object_reference(cr, uid, 'hr_payroll', 'view_hr_payslip_tree')
        tree_res = tree_id and tree_id[1] or False
        return {
            'name':_("Refund Payslip"),
            'view_mode': 'tree, form',
            'view_id': False,
            'view_type': 'form',
            'res_model': 'hr.payslip',
            'type': 'ir.actions.act_window',
            'nodestroy': True,
            'target': 'current',
            'domain': "[('id', 'in', %s)]" % [id_copy],
            'views': [(tree_res, 'tree'), (form_res, 'form')],
            'context': {}
        }
 def unlink(self, cr, uid, ids, context=None):
     for e in self.browse(cr, uid, ids):
         check_reference = self.pool.get("hr.employee.violation").search(cr, uid, [('violation_id', '=', e.id)])
         if check_reference:
             raise osv.except_osv(_('Warning!'), _('You Cannot Delete This Violation  Record Which Is Referenced!'))
     return super(osv.osv, self).unlink(cr, uid, ids, context)
Example #32
0
class email_template(osv.Model):
    _inherit = 'email.template'
    _sql_constraints = [('name', 'unique (name)',
                         _('Email Template Name must be unique!'))]

    def send_mail(self,
                  cr,
                  uid,
                  template_id,
                  res_id,
                  force_send=False,
                  context=None):
        """Generates a new mail message for the given template and record,
           and schedules it for delivery through the ``mail`` module's scheduler.

           :param int template_id: id of the template to render
           :param int res_id: id of the record to render the template with
                              (model is taken from the template)
           :param bool force_send: if True, the generated mail.message is
                immediately sent after being created, as if the scheduler
                was executed for this message only.
           :returns: id of the mail.message that was created
        """
        if context is None:
            context = {}
        mail_mail = self.pool.get('mail.mail')
        ir_attachment = self.pool.get('ir.attachment')

        # create a mail_mail based on values, without attachments
        values = self.generate_email(cr,
                                     uid,
                                     template_id,
                                     res_id,
                                     context=context)
        #johnw, 07/29/2014, improve the email_from checking, auto set it to system email_from if it is missing
        if not values.get('email_from'):
            values['email_from'] = tools.config.get('email_from')
        assert values.get(
            'email_from'
        ), 'email_from is missing or empty after template rendering, send_mail() cannot proceed'
        del values['email_recipients']  # TODO Properly use them.
        attachment_ids = values.pop('attachment_ids', [])
        attachments = values.pop('attachments', [])
        msg_id = mail_mail.create(cr, uid, values, context=context)

        # manage attachments
        for attachment in attachments:
            attachment_data = {
                'name': attachment[0],
                'datas_fname': attachment[0],
                'datas': attachment[1],
                'res_model': 'mail.message',
                'res_id': msg_id,
            }
            context.pop('default_type', None)
            attachment_ids.append(
                ir_attachment.create(cr, uid, attachment_data,
                                     context=context))
        if attachment_ids:
            values['attachment_ids'] = [(6, 0, attachment_ids)]
            mail_mail.write(cr,
                            uid,
                            msg_id,
                            {'attachment_ids': [(6, 0, attachment_ids)]},
                            context=context)

        if force_send:
            mail_mail.send(cr, uid, [msg_id], context=context)
        return msg_id
Example #33
0
class account_asset_history(osv.osv):

    _inherit = 'account.asset.history'

    _rec_name = 'type'

    def _check_history_lines(self, cr, uid, ids, context=None):
        """ Constrain fucntion to prohibit user from making teo operation at a time and 
        prohibit user to make any operation on zero value asset.

        @return: True or raise message
        """
        for hst in self.browse(cr, uid, ids, context=context):
            if hst.type == 'abandon' and hst.state == 'draft':
                if hst.amount > hst.asset_id.value_residual:
                    raise orm.except_orm(
                        _('Warrning'),
                        _('The abandon value Must be lower than book value'))
            intial = self.search(cr,
                                 uid, [('asset_id', '=', hst.asset_id.id),
                                       ('type', '=', 'initial'),
                                       ('id', '!=', hst.id)],
                                 context=context)
            if hst.type == 'initial':
                if intial:
                    raise orm.except_orm(
                        _('Warrning'),
                        _('Sorry the Intial value has already been intered you can not repeat this process!'
                          ))
                return True
            else:
                msg=not intial and 'Sorry no intial value for this asset please set it first to complate this process !' or \
                    self.search(cr, uid, [('asset_id','=',hst.asset_id.id),('state','=','draft'),('id','!=',hst.id)], context=context) and\
                    hst.state not in  ('reversed','posted') and 'Sorry you need to post draft prosess first to complate this process !' or ''
                if msg:
                    raise orm.except_orm(_('Warrning'), msg)
                return True

    _constraints = [
        (_check_history_lines, _('Sorry!'), ['type']),
    ]

    def create_operation_move(self, cr, uid, ids, context={}):
        '''
        Method is used to post Asset sale, revaluation, rehabilitation, abandon and initial values (initial can create 4 lines move)
        '''
        move_obj = self.pool.get('account.move')
        asset_obj = self.pool.get('account.asset.asset')
        moves = []
        for history in self.browse(cr, uid, ids, context):
            asset = history.asset_id
            if history.type in ('initial'):
                asset.write({
                    'purchase_value': history.amount,
                    'value_residual': history.amount
                })
            if history.type in ('rehabilitation'):
                asset.write(
                    {'value_residual': asset.value_residual + history.amount})
            if history.type in ('reval'):
                asset.write({'value_residual': history.amount})
            if history.type == 'sale':
                asset.write({'value_residual': 0.0})
                asset.write({'state': 'sold'})
            if history.type == 'abandon':
                asset.write(
                    {'value_residual': asset.value_residual - history.amount})
                if (asset.value_residual - history.amount) == 0.0:
                    asset.write({'state': 'abandon'})

            history.write({'state': 'posted'})
            self.pool.get('account.asset.asset').compute_depreciation_board(
                cr, uid, [asset.id], {})

        return True
Example #34
0
 def copy(self, cr, uid, ids, *args, **argv):
     raise osv.except_osv(_('Error !'),
                          _('You cannot duplicate a timesheet!'))
Example #35
0
class res_partner(osv.osv):
    _inherit = 'res.partner'

    _columns = {
        'seniat_updated':
        fields.boolean(
            'Seniat Updated',
            help=
            "This field indicates if partner was updated using SENIAT button"),
        'wh_iva_rate':
        fields.float(string='Rate',
                     digits_compute=dp.get_precision('Withhold'),
                     help="Vat Withholding rate"),
        'wh_iva_agent':
        fields.boolean(
            'Wh. Agent',
            help="Indicate if the partner is a withholding vat agent"),
    }

    _default = {
        'seniat_updated': False,
    }

    def vat_cleaner_ve(self, vat):
        return vat.replace('-', '').replace(' ',
                                            '').replace('/',
                                                        '').upper().strip()

    def name_search(self,
                    cr,
                    uid,
                    name='',
                    args=[],
                    operator='ilike',
                    context=None,
                    limit=80):
        if context is None:
            context = {}
        ids = []
        if len(name) >= 2:
            ids = self.search(cr,
                              uid, [('vat', operator, name)] + args,
                              limit=limit,
                              context=context)
        if not ids:
            ids = self.search(cr,
                              uid, [('name', operator, name)] + args,
                              limit=limit,
                              context=context)
        return self.name_get(cr, uid, ids, context=context)

    '''
    Required Invoice Address
    '''

    def _check_partner_invoice_addr(self, cr, uid, ids, context={}):
        partner_obj = self.browse(cr, uid, ids[0])
        if partner_obj.vat and partner_obj.vat[:2].upper() == 'VE':
            if hasattr(partner_obj, 'address'):
                res = [
                    addr for addr in partner_obj.address
                    if addr.type == 'invoice'
                ]
                if res:
                    return True
                else:
                    return False
            else:
                return True
        return True

    def _check_vat_uniqueness(self, cr, uid, ids, context={}):
        ids = isinstance(ids, (int, long)) and [ids] or ids
        partner_obj = self.pool.get('res.partner')
        partner_brw = partner_obj.browse(cr, uid, ids, context=context)[0]
        current_vat = partner_brw.vat if partner_brw.vat else ''
        if not current_vat or not 'VE' in [
                a.country_id.code for a in partner_brw.address
        ]:
            return True  # Accept empty and foreign VAT's
        current_vat = self.vat_cleaner_ve(current_vat)
        duplicates = partner_obj.search(cr, uid,
                                        [('vat', '=', current_vat),
                                         ('id', '!=', partner_brw.id)])
        return not duplicates

    _constraints = [
        (_check_partner_invoice_addr,
         _('Error ! The partner does not have an invoice address.'), []),
        (_check_vat_uniqueness,
         _("Error ! Partner's VAT must be a unique value or empty"), []),
    ]

    def vat_change_fiscal_requirements(self,
                                       cr,
                                       uid,
                                       ids,
                                       value,
                                       context=None):
        if context is None:
            context = {}
        ids = isinstance(ids, (int, long)) and [ids] or ids
        if not value:
            return super(res_partner, self).vat_change(cr,
                                                       uid,
                                                       ids,
                                                       value,
                                                       context=context)
        res = self.search(cr, uid, [('vat', 'ilike', value),
                                    ('id', 'not in', ids)])
        if res:
            rp = self.browse(cr, uid, res[0], context=context)
            return {
                'warning': {
                    'title':
                    _('Vat Error !'),
                    'message':
                    _('The VAT [%s] looks like [%s] ' +
                      'which is already being used ' + 'by: %s') %
                    (value, rp.vat.upper(), rp.name.upper())
                }
            }
        else:
            res = super(res_partner, self).vat_change(cr,
                                                      uid,
                                                      ids,
                                                      value,
                                                      context=context)
            res['value'].update({'vat': self.vat_cleaner_ve(value)})
            return res

    def check_vat_ve(self, vat, context=None):
        '''
        Check Venezuelan VAT number, locally caled RIF.
        RIF: JXXXXXXXXX RIF CEDULA VENEZOLANO: VXXXXXXXXX CEDULA EXTRANJERO: EXXXXXXXXX
        '''
        def compute_vat_ve(vat2):
            '''
            Toma un nro de cedula o rif y calcula el digito validador
            data: string con numero de CI o RIF sin espacios ni guiones ej.
                V12345678
                E12345678
                J123456789
            devuelve el rif con el digito calculado
            no se validan los datos de entrada
            para validar: if data == calcular_rif(data):
            '''
            _OPER_RIF = [4, 3, 2, 7, 6, 5, 4, 3, 2]
            items = [' VEJPG'.find(vat2[0])]
            items.extend(map(lambda x: int(x), vat2[1:]))
            val = sum(i * o for (i, o) in zip(items, _OPER_RIF))
            digit = 11 - (val % 11)
            digit = digit if digit < 10 else 0
            return '%s%s' % (vat2[:9], digit)

        res = False
        if context is None:
            context = {}
        if re.search(r'^[VEJPG][0-9]{9}$', vat):
            context.update({'ci_pas': False})
            res = True
        if re.search(r'^([0-9]{1,8}|[D][0-9]{9})$', vat):
            context.update({'ci_pas': True})
            res = True
        if vat and res and len(vat) == 10:
            res = vat == compute_vat_ve(vat)
        return res

    def update_rif(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        su_obj = self.pool.get('seniat.url')
        return su_obj.update_rif(cr, uid, ids, context=context)

    def create(self, cr, uid, vals, context=None):
        if vals.get('vat'):
            vals.update({'vat': self.vat_cleaner_ve(vals.get('vat', ''))})
        res = super(res_partner, self).create(cr, uid, vals, context)
        return res

    def write(self, cr, uid, ids, vals, context=None):
        if vals.get('vat'):
            vals.update({'vat': self.vat_cleaner_ve(vals.get('vat', ''))})
        res = super(res_partner, self).write(cr, uid, ids, vals, context)
        return res
Example #36
0
 def button_reg_cancel(self, cr, uid, ids, *args):
     """This Function Cancel Event Registration.
     """
     registrations = self.browse(cr, uid, ids)
     self.history(cr, uid, registrations, _('Cancel'))
     return self.write(cr, uid, ids, {'state': 'cancel'})
Example #37
0
    def action_invoice_create(self,
                              cr,
                              uid,
                              ids,
                              grouped=False,
                              date_inv=False,
                              context=None):
        """ Action of Create Invoice """
        res = False
        invoices = {}
        tax_ids = []
        new_invoice_ids = []
        inv_lines_pool = self.pool.get('account.invoice.line')
        inv_pool = self.pool.get('account.invoice')
        product_pool = self.pool.get('product.product')
        contact_pool = self.pool.get('res.partner.contact')
        if context is None:
            context = {}
        # If date was specified, use it as date invoiced, usefull when invoices are generated this month and put the
        # last day of the last month as invoice date
        if date_inv:
            context['date_inv'] = date_inv

        for reg in self.browse(cr, uid, ids, context=context):
            val_invoice = inv_pool.onchange_partner_id(
                cr, uid, [], 'out_invoice', reg.partner_invoice_id.id, False,
                False)
            val_invoice['value'].update(
                {'partner_id': reg.partner_invoice_id.id})
            partner_address_id = val_invoice['value']['address_invoice_id']
            if not partner_address_id:
                raise osv.except_osv(
                    _('Error !'),
                    _("Registered partner doesn't have an address to make the invoice."
                      ))

            value = inv_lines_pool.product_id_change(
                cr,
                uid, [],
                reg.event_id.product_id.id,
                uom=False,
                partner_id=reg.partner_invoice_id.id,
                fposition_id=reg.partner_invoice_id.property_account_position.
                id)
            product = product_pool.browse(cr,
                                          uid,
                                          reg.event_id.product_id.id,
                                          context=context)
            for tax in product.taxes_id:
                tax_ids.append(tax.id)
            vals = value['value']
            c_name = reg.contact_id and ('-' + contact_pool.name_get(
                cr, uid, [reg.contact_id.id])[0][1]) or ''
            vals.update({
                'name': reg.event_product + '-' + c_name,
                'price_unit': reg.unit_price,
                'quantity': reg.nb_register,
                'product_id': reg.event_id.product_id.id,
                'invoice_line_tax_id': [(6, 0, tax_ids)],
            })
            inv_line_ids = self._create_invoice_lines(cr, uid, [reg.id], vals)
            invoices.setdefault(reg.partner_id.id, []).append(
                (reg, inv_line_ids))
        for val in invoices.values():
            res = False
            if grouped:
                res = self._make_invoice(cr,
                                         uid,
                                         val[0][0], [v for k, v in val],
                                         context=context)

                for k, v in val:
                    self.do_close(cr, uid, [k.id], context={'invoice_id': res})

            else:
                for k, v in val:
                    res = self._make_invoice(cr, uid, k, [v], context=context)
                    self.do_close(cr, uid, [k.id], context={'invoice_id': res})
            if res: new_invoice_ids.append(res)
        return new_invoice_ids
class hr_employee_violation(osv.Model):

    _name = "hr.employee.violation"

    _description = "Employee Violations and Punishments"

    _rec_name = "employee_id"

    _columns = {
        'employee_id': fields.many2one('hr.employee', "Employee", domain="[('state','!=',('refuse','draft'))]", required=True, 
                                       readonly=True, states={'draft':[('readonly', False)]}),
        'violation_id': fields.many2one('hr.violation', "Violation", required=True, 
                                       readonly=True, states={'draft':[('readonly', False)]}),
        'violation_date' :fields.date("Violation Date" , required=True, 
                                       readonly=True, states={'draft':[('readonly', False)]}),
        'violation_descr' :fields.text("Violation Description"),
        'decision_date' :fields.date("Decision Date",
                                       readonly=True, states={'draft':[('readonly', False)]}),
        'decision_descr' :fields.text("Decision Description"),
        'punishment_id': fields.many2one('hr.punishment', "Punishment", 
                                       readonly=True, states={'draft':[('readonly', False)]} ),
		'punishment_date' :fields.date("Punishment Date", size=8),
        'penalty_amount': fields.float("Penalty Amount", digits_compute=dp.get_precision('penalty_amount')),
        'start_date' :fields.date("Penalty Start Date"),
        'end_date' :fields.date("Penalty End Date"),
        'factor' :fields.integer("Factor"),
        'penalty' : fields.boolean('Penalty'),
        'state': fields.selection([('draft', 'Draft'), ('complete', 'Complete'),('implement','Implement')], 'State', readonly=True),
    }

    _defaults = {
        'state': 'draft',
        'violation_id':False, #To call onchange_violation and apply punishment_id domain
    }

    def _positive_factor(self, cr, uid, ids, context=None):
        for fact in self.browse(cr, uid, ids, context=context):
          if fact.factor<0 or fact.penalty_amount<0:
               return False
        return True 

    def check_dates(self, cr, uid, ids, context=None):
         exp = self.read(cr, uid, ids[0], ['violation_date', 'decision_date'])
         if exp['violation_date'] and exp['decision_date']:
             if exp['violation_date'] > exp['decision_date']:
                 return False
         return True
    def check_dates2(self, cr, uid, ids, context=None):
         exp = self.read(cr, uid, ids[0], ['start_date', 'end_date'])
         if exp['start_date'] and exp['end_date']:
             if exp['start_date'] > exp['end_date']:
                 return False
         return True   
     
    _constraints = [
        (_positive_factor, 'The value  must be more than zero!', ['factor or penalty_amount']),
        (check_dates, 'Error! Exception violation-date must be lower then Exception decision-date.', ['violation_date', 'decision_date']),(check_dates2, 'Error! Exception Penality Start Date must be lower then Penality End Date.', ['start_date', 'end_date']),
    ]

    _sql_constraints = [
        ("factor_check", "CHECK (state <> 'implement' OR penalty <> True OR factor > 0)",  _("The factor should be greater than Zero!")),
        ("penalty_amount_check", "CHECK (state <> 'implement' OR penalty <> True OR penalty_amount > 0)",  _("The penalty amount should be greater than Zero!")),
    ]

    def onchange_punishment(self, cr, uid, ids, punishment_id, context=None):
        """
        Method that retrieves the pentalty of the selected punishment.

        @param punishment_id: ID of the punishment
        @return: Dictionary of value 
        """
        return {'value': {'penalty':self.pool.get('hr.punishment').browse(cr, uid, punishment_id, context=context).penalty}}

    def onchange_violation(self, cr, uid, ids, violation_id, context=None):
        """
        Retrieves available punishments for specific Violation.

        @param violation_id: ID of violation
        @return: Dictionary of values
        """
        punishs = []
        if violation_id:
            punish_pool = self.pool.get('hr.violation.punishment')
            punish_ids = punish_pool.search(cr, uid, [('violation_id','=',violation_id)], context=context)
            punishs =[p['punishment_id'][0] for p in punish_pool.read(cr, uid, punish_ids, ['punishment_id'],context=context)]
        #return {'value': {'punishment_id':False} , 'domain': {'punishment_id':[('id', 'in', punishs),('ref_process','=','procedural_suspend')]}}
        return {'value': {'punishment_id':False} , 'domain': {'punishment_id':[('id', 'in', punishs)]}}

    def onchange_factor(self, cr, uid, ids,start_date, factor, employee_id, punishment_id, context=None):
        """
        Method thats computes the penalty amount of the violations.

        @param factor: Number of days
        @param employee_id: ID of employee
        @param punishment_id: ID of punishment
        @return: Dictionary that contains the Value of penalty
        """
        amount = 0
        punishment = self.pool.get('hr.punishment').browse(cr, uid, punishment_id, context=context)
        if punishment.penalty:
            emp = self.pool.get('hr.employee').browse(cr, uid, employee_id, context=context)
            allow_dict=self.pool.get('payroll').allowances_deductions_calculation(cr,uid,start_date,emp,{'no_sp_rec':True}, [ punishment.allow_deduct.id], False,[])
            amount = round(allow_dict['total_deduct']/30*factor,2)
        return {'value': {'penalty_amount':amount}}

    def implement_penalty(self, cr, uid, ids, context=None):
        """
        Creates Record  in hr_allowance_deduction_exception object.

        @return: Boolean True
        """
        employee_exception_line_obj = self.pool.get('hr.allowance.deduction.exception')
        for rec in self.browse(cr, uid, ids, context=context):
            if rec.penalty:
                emp_line = {
                    'code':rec.employee_id.emp_code,
                    'employee_id':rec.employee_id.id,
                    'start_date':rec.start_date,
                    'end_date':rec.end_date,
                    'allow_deduct_id':rec.punishment_id.allow_deduct.id,
                    'amount':rec.penalty_amount,
                    'types':'deduct',
                    'action':'special',
                    'types':rec.punishment_id.allow_deduct.name_type,
                }
                employee_exception_line_obj.create(cr, uid, emp_line, context=context)
        return self.write(cr, uid, ids, {'state':'implement'}, context=context)

    def unlink(self, cr, uid, ids, context=None):
        """
        Method that prevents the deletion of non draft punishment.

        @return: Super unlink mehtod or raise exception
        """
        if self.search(cr, uid, [('state','!=','draft'),('id','in',ids)], context=context):
            raise orm.except_orm(_('Warning!'),_('You cannot delete non draft violation process.'))
        return super(hr_employee_violation,self).unlink(cr, uid, ids, context=context)

    def set_to_draft(self, cr, uid, ids, context=None):
        """
        Method reset the workflow and change state to 'draft'.
        
        @return: Boolean True
        """
        self.write(cr, uid, ids, {'state': 'draft'}, context=context)
        wf_service = netsvc.LocalService("workflow")
        for id in ids:
            wf_service.trg_delete(uid, 'hr.employee.violation', id, cr)
            wf_service.trg_create(uid, 'hr.employee.violation', id, cr)
        return True

    def copy(self, cr, uid, id, default=None, context=None):
        raise osv.except_osv(_('Warning!'),_('You cannot duplicate this record refill it if you want !'))
    def generate_xml(self, cr, uid, context, pool, modelName, parentNode,
                     document, depth, first_call):
        # First of all add "id" field
        fieldNode = document.createElement('id')
        parentNode.appendChild(fieldNode)
        valueNode = document.createTextNode('1')
        fieldNode.appendChild(valueNode)
        language = context.get('lang')
        if language == 'en_US':
            language = False

        # Then add all fields in alphabetical order
        model = pool.get(modelName)
        fields = model._columns.keys()
        fields += model._inherit_fields.keys()
        # Remove duplicates because model may have fields with the
        # same name as it's parent
        fields = sorted(list(set(fields)))
        for field in fields:
            name = False
            if language:
                # Obtain field string for user's language.
                name = pool.get('ir.translation')._get_source(
                    cr, uid, modelName + ',' + field, 'field', language)
            if not name:
                # If there's not description in user's language, use default (english) one.
                if field in model._columns.keys():
                    name = model._columns[field].string
                else:
                    name = model._inherit_fields[field][2].string

            if name:
                name = self.unaccent(name)
            # After unaccent the name might result in an empty string
            if name:
                name = '%s-%s' % (self.unaccent(name), field)
            else:
                name = field
            fieldNode = document.createElement(name)

            parentNode.appendChild(fieldNode)
            if field in pool.get(modelName)._columns:
                fieldType = model._columns[field]._type
            else:
                fieldType = model._inherit_fields[field][2]._type
            if fieldType in ('many2one', 'one2many', 'many2many'):
                if depth <= 1:
                    continue
                if field in model._columns:
                    newName = model._columns[field]._obj
                else:
                    newName = model._inherit_fields[field][2]._obj
                self.generate_xml(cr, uid, context, pool, newName, fieldNode,
                                  document, depth - 1, False)
                continue

            if fieldType == 'float':
                value = '12345.67'
            elif fieldType == 'integer':
                value = '12345'
            elif fieldType == 'date':
                value = '2009-12-31 00:00:00'
            elif fieldType == 'time':
                value = '12:34:56'
            elif fieldType == 'datetime':
                value = '2009-12-31 12:34:56'
            else:
                value = field

            valueNode = document.createTextNode(value)
            fieldNode.appendChild(valueNode)

        if depth > 1 and modelName != 'Attachments':
            # Create relation with attachments
            fieldNode = document.createElement('%s-Attachments' %
                                               _('Attachments'))
            parentNode.appendChild(fieldNode)
            self.generate_xml(cr, uid, context, pool, 'ir.attachment',
                              fieldNode, document, depth - 1, False)

        if first_call:
            # Create relation with user
            fieldNode = document.createElement('%s-User' % _('User'))
            parentNode.appendChild(fieldNode)
            self.generate_xml(cr, uid, context, pool, 'res.users', fieldNode,
                              document, depth - 1, False)
 def copy(self, cr, uid, id, default=None, context=None):
     raise osv.except_osv(_('Warning!'),_('You cannot duplicate this record refill it if you want !'))
Example #41
0
    def action_reopen(self, cr, uid, ids, *args):
        _logger = logging.getLogger(__name__)
        context = self.pool['res.users'].context_get(cr, uid)
        attachment_obj = self.pool['ir.attachment']
        account_move_obj = self.pool['account.move']
        account_move_line_obj = self.pool['account.move.line']
        report_xml_obj = self.pool['ir.actions.report.xml']

        # _logger.debug('FGF reopen invoices %s' % (invoices))

        wf_service = netsvc.LocalService("workflow")

        move_ids = []  # ones that we will need to update
        now = ' ' + _('Invalid') + time.strftime(' [%Y%m%d %H%M%S]')
        for invoice in self.browse(cr, uid, ids, context):
            if invoice.move_id:
                move_ids.append(invoice.move_id.id)
                _logger.debug('FGF reopen move_ids %s' % move_ids)
                for move in account_move_obj.browse(cr, uid, move_ids, context):
                    if not move.journal_id.reopen_posted:
                        raise orm.except_orm(_('Error !'), _(
                            'You can not reopen invoice of this journal [%s]! You need to need to set "Allow Update Posted Entries" first') % (
                                             move.journal_id.name))

            if invoice.payment_ids:
                pay_ids = account_move_line_obj.browse(cr, uid, invoice.payment_ids, context)
                for move_line in pay_ids:
                    if move_line.reconcile_id or (
                        move_line.reconcile_partial_id and move_line.reconcile_partial_id.line_partial_ids):
                        raise orm.except_orm(_('Error !'), _(
                            'You can not reopen an invoice which is partially paid! You need to unreconcile related payment entries first!'))
            self.write(cr, uid, invoice.id, {'state': 'draft'})
            wf_service.trg_delete(uid, 'account.invoice', invoice.id, cr)
            wf_service.trg_create(uid, 'account.invoice', invoice.id, cr)


        # # rename attachments (reports)
        # # for some reason datas_fname has .pdf.pdf extension
        # for inv in self.browse(cr, uid, ids):
        #     report_ids = report_xml_obj.search(cr, uid,
        #                                        [('model', '=', 'account.invoice'), ('attachment', '!=', False)])
        #     for report in report_xml_obj.browse(cr, uid, report_ids):
        #         if report.attachment:
        #             aname = report.attachment.replace('object', 'inv')
        #             if eval(aname):
        #                 aname = eval(aname) + '.pdf'
        #                 attachment_ids = attachment_obj.search(cr, uid, [('res_model', '=', 'account.invoice'),
        #                                                                  ('datas_fname', '=', aname),
        #                                                                  ('res_id', '=', inv.id)])
        #                 for a in attachment_obj.browse(cr, uid, attachment_ids):
        #                     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)

        # unset set the invoices move_id 
        self.write(cr, uid, ids, {'move_id': False}, context)

        if move_ids:

            for move in account_move_obj.browse(cr, uid, move_ids, context):
                name = move.name + now
                account_move_obj.write(cr, uid, [move.id], {'name': name})
                _logger.debug('FGF reopen move_copy moveid %s' % move.id)
                if move.journal_id.entry_posted:
                    raise orm.except_orm(_('Error !'),
                                         _('You can not reopen an invoice if the journal is set to skip draft!'))
                move_copy_id = account_move_obj.copy(cr, uid, move.id)
                _logger.debug('FGF reopen move_copy_id %s' % move_copy_id)
                name = name + '*'
                cr.execute("""update account_move_line
                                 set debit=credit, credit=debit, tax_amount= -tax_amount
                               where move_id = %s;""" % move_copy_id)
                account_move_obj.write(cr, uid, [move_copy_id], {'name': name}, context)
                _logger.debug('FGF reopen move_copy_id validate')
                account_move_obj.button_validate(cr, uid, [move_copy_id], context=context)
                _logger.debug('FGF reopen move_copy_id validated')
                # reconcile 
                r_id = self.pool.get('account.move.reconcile').create(cr, uid, {'type': 'auto'}, context)
                _logger.debug('FGF reopen reconcile_id %s' % r_id)
                line_ids = account_move_line_obj.search(cr, uid, [('move_id', 'in', [move_copy_id, move.id])], context=context)
                _logger.debug('FGF reopen reconcile_line_ids %s' % line_ids)
                lines_to_reconile = []
                for ltr in account_move_line_obj.browse(cr, uid, line_ids, context):
                    if ltr.account_id.id in (
                            ltr.partner_id.property_account_payable.id, ltr.partner_id.property_account_receivable.id):
                        lines_to_reconile.append(ltr.id)
                account_move_line_obj.write(cr, uid, lines_to_reconile, {'reconcile_id': r_id}, context)

        self._log_event(cr, uid, ids, -1.0, 'Reopened Invoice')

        return True
Example #42
0
    def do_change_standard_price(self, cr, uid, ids, datas, context=None):
        """ Changes the Standard Price of Product and creates an account move 
                    accordingly.
        @param datas : dict. contain default datas like new_price, 
                        stock_output_account, stock_input_account, stock_journal
        @param context: A standard dictionary
        @return: List of account.move ids created
        """

        location_obj = self.pool.get('stock.location')
        move_obj = self.pool.get('account.move')
        move_line_obj = self.pool.get('account.move.line')
        if context is None:
            context = {}

        new_price = datas.get('new_price', 0.0)
        stock_output_acc = datas.get('stock_output_account', False)
        stock_input_acc = datas.get('stock_input_account', False)
        journal_id = datas.get('stock_journal', False)
        product_obj = self.browse(cr, uid, ids, context=context)[0]
        account_variation = product_obj.categ_id.property_stock_variation
        account_variation_id = account_variation and account_variation.id or \
                                                                        False
        if product_obj.valuation != 'manual_periodic' \
                                        and not account_variation_id:
            raise osv.except_osv(_('Error!'),
                                 _('Variation Account is not specified for '\
                                   'Product Category: %s') % \
                                 (product_obj.categ_id.name))
        move_ids = []
        loc_ids = location_obj.search(cr, uid, [('usage', '=', 'internal')])
        for rec_id in ids:
            # If valuation == 'manual_periodic' is not necessary create an
            # account move for stock variation
            if product_obj.valuation == 'manual_periodic':
                self.write(cr, uid, rec_id, {'standard_price': new_price})
                continue

            for location in location_obj.browse(cr, uid, loc_ids, \
                                                context=context):
                c = context.copy()
                c.update({'location': location.id, 'compute_child': False})

                product = self.browse(cr, uid, rec_id, context=c)
                qty = product.qty_available
                diff = product.standard_price - new_price
                if not diff:
                    raise osv.except_osv(
                        _('Error!'),
                        _("Could not find any difference between '\
                                      'standard price and new price!"))
                if qty:
                    company_id = location.company_id \
                                        and location.company_id.id \
                                        or False
                    if not company_id:
                        raise osv.except_osv(
                            _('Error!'),
                            _('Company is not specified in Location'))
                    #
                    # Accounting Entries
                    #
                    if not journal_id:
                        journal_id = product.categ_id.property_stock_journal \
                                and product.categ_id.property_stock_journal.id \
                                or False
                    if not journal_id:
                        raise osv.except_osv(_('Error!'),
                            _('There is no journal defined '\
                                'on the product category: "%s" (id: %d)') % \
                                (product.categ_id.name,
                                    product.categ_id.id,))
                    move_id = move_obj.create(cr, uid, {
                        'journal_id': journal_id,
                        'company_id': company_id
                    })

                    move_ids.append(move_id)

                    if diff > 0:
                        if not stock_input_acc:
                            stock_input_acc = product.product_tmpl_id.\
                                property_stock_account_input.id
                        if not stock_input_acc:
                            stock_input_acc = product.categ_id.\
                                    property_stock_account_input_categ.id
                        if not stock_input_acc:
                            raise osv.except_osv(_('Error!'),
                                _('There is no stock input account ' \
                                'defined for this product: "%s" (id: %d)') % \
                                (product.name, product.id,))
                        amount_diff = qty * diff
                        move_line_obj.create(
                            cr, uid, {
                                'name': product.name,
                                'account_id': stock_input_acc,
                                'debit': amount_diff,
                                'move_id': move_id,
                            })
                        move_line_obj.create(
                            cr, uid, {
                                'name': product.categ_id.name,
                                'account_id': account_variation_id,
                                'credit': amount_diff,
                                'move_id': move_id
                            })
                    elif diff < 0:
                        if not stock_output_acc:
                            stock_output_acc = product.product_tmpl_id.\
                                property_stock_account_output.id
                        if not stock_output_acc:
                            stock_output_acc = product.categ_id.\
                                    property_stock_account_output_categ.id
                        if not stock_output_acc:
                            raise osv.except_osv(_('Error!'),
                                    _('There is no stock output account ' \
                                    'defined for this product: "%s" (id: %d)') % \
                                    (product.name, product.id,))
                        amount_diff = qty * -diff
                        move_line_obj.create(
                            cr, uid, {
                                'name': product.name,
                                'account_id': stock_output_acc,
                                'credit': amount_diff,
                                'move_id': move_id
                            })
                        move_line_obj.create(
                            cr, uid, {
                                'name': product.categ_id.name,
                                'account_id': account_variation_id,
                                'debit': amount_diff,
                                'move_id': move_id
                            })

            self.write(cr, uid, rec_id, {'standard_price': new_price})

        return move_ids
Example #43
0
    def create_product(self, cr, uid, ids, context=None):
        if context is None:
            context = {}

        # Get the selected BOM Template
        object = self.browse(cr, uid, ids[0], context=context)
        lines = object.panel_lines + object.door_lines + object.window_lines

        result = []

        if not len(lines):
            return False

        new_id, old_id = 0, 0

        for line in lines:
            bom_template = line.bom_template_id
            # If template, then continue, else, stop
            if bom_template.is_bom_template:
                product_obj = self.pool.get('product.product')
                bom_obj = self.pool.get('mrp.bom')
                # Create new object by copy the existing one, then change name using predefined format
                product_template = product_obj.browse(
                    cr, uid, bom_template.product_id.id)
                new_product_name = eval(bom_template.new_name_format, {
                    'object': object,
                    'line': line
                })
                res = self._prepare_product(cr,
                                            uid,
                                            ids,
                                            new_product_name,
                                            line,
                                            object,
                                            context=context)
                new_product_id = product_obj.copy(cr,
                                                  uid,
                                                  product_template.id,
                                                  default={},
                                                  context=context)
                result.append(new_product_id)
                product_obj.write(cr, uid, new_product_id, res)

                # Copy Bill of Material
                res = {
                    'name': new_product_name,
                    'product_id': new_product_id,
                    'is_bom_template': False,
                    'bom_template_type': None
                }

                # Performance Tuning
                new_id = bom_template.id
                if new_id != old_id:
                    context.update({'bom_data': False})
                new_bom_id, bom_data = bom_obj.copy_bom_formula(
                    cr,
                    uid,
                    bom_template.id,
                    object,
                    line,
                    default={},
                    context=context)
                old_id = bom_template.id
                context.update({'bom_data': bom_data})
                # --
                bom_obj.write(cr, uid, new_bom_id, res)

        # Return
        data_obj = self.pool.get('ir.model.data')
        if result and len(result):

            self.write(cr, uid, ids[0], {'state': 'done'})

            #res_id = result[0]
            form_view_id = data_obj._get_id(cr, uid, 'product',
                                            'product_normal_form_view')
            form_view = data_obj.read(cr, uid, form_view_id, ['res_id'])
            tree_view_id = data_obj._get_id(cr, uid, 'product',
                                            'product_product_tree_view')
            tree_view = data_obj.read(cr, uid, tree_view_id, ['res_id'])
            search_view_id = data_obj._get_id(cr, uid, 'product',
                                              'product_search_form_view')
            search_view = data_obj.read(cr, uid, search_view_id, ['res_id'])
            return {
                'name':
                _('Product'),
                'view_type':
                'form',
                'view_mode':
                'tree,form',
                'res_model':
                'product.product',
                'view_id':
                False,
                'domain': [('id', 'in', result)],
                #'res_id': res_id,
                'views': [(tree_view['res_id'], 'tree'),
                          (form_view['res_id'], 'form')],
                'type':
                'ir.actions.act_window',
                'search_view_id':
                search_view['res_id'],
                'nodestroy':
                True
            }
        return False
Example #44
0
                                                      ira,
                                                      boo.path,
                                                      do_create=True)
                fname = os.path.join(path, npath[-1])
                fp = open(fname, 'wb')
                try:
                    fp.write(data)
                finally:
                    fp.close()
                self._doclog.debug("Saved data to %s", fname)
                filesize = len(data)  # os.stat(fname).st_size
                store_fname = os.path.join(*npath)
                # TODO Here, an old file would be left hanging.
            except Exception, e:
                self._doclog.warning("Couldn't save data:", exc_info=True)
                raise except_orm(_('Error!'), str(e))

        elif boo.type == 'virtual':
            raise ValueError('Virtual storage does not support static files')

        else:
            raise TypeError("No %s storage" % boo.type)

        # 2nd phase: store the metadata
        try:
            icont = ''
            mime = ira.file_type
            if not mime:
                mime = ""
            try:
                mime, icont = cntIndex.doIndex(data, ira.datas_fname,
Example #45
0
class stock_location(osv.osv):
    _inherit = "stock.location"
    _name = "stock.location"

    def _product_get_all_report(self,
                                cr,
                                uid,
                                ids,
                                product_ids=False,
                                context=None):
        return self._product_get_report(cr,
                                        uid,
                                        ids,
                                        product_ids,
                                        context,
                                        recursive=True)

    def _product_get_report(self,
                            cr,
                            uid,
                            ids,
                            product_ids=False,
                            context=None,
                            recursive=False):
        """ Finds the product quantity and price for particular location.
        @param product_ids: Ids of product
        @param recursive: True or False
        @return: Dictionary of values
        """
        if context is None:
            context = {}
            user = self.pool.get("res.users").browse(cr, uid, uid)
            context.update(
                {"lang": user.partner_id and user.partner_id.lang or "en_US"})
        product_obj = self.pool.get('product.product')
        move_obj = self.pool.get('stock.move')
        # Take the user company and pricetype
        context['currency_id'] = self.pool.get('res.users').browse(
            cr, uid, uid, context=context).company_id.currency_id.id

        # To be able to offer recursive or non-recursive reports we need to prevent recursive quantities by default
        context['compute_child'] = False

        if not product_ids:
            #product_ids = product_obj.search(cr, uid, [], context={'active_test': False})
            cr.execute(
                "select distinct product_id from stock_move where state = 'done' and ( location_id IN %s or location_dest_id IN %s )",
                (
                    tuple(ids),
                    tuple(ids),
                ))
            product_ids = filter(None, map(lambda x: x[0], cr.fetchall()))

        products = product_obj.browse(cr, uid, product_ids, context=context)
        products_by_uom = {}
        products_by_id = {}
        for product in products:
            products_by_uom.setdefault(product.uom_id.id, [])
            products_by_uom[product.uom_id.id].append(product)
            products_by_id.setdefault(product.id, [])
            products_by_id[product.id] = product

        result = {}
        result['product'] = []
        for id in ids:
            quantity_total = 0.0
            total_price = 0.0
            for uom_id in products_by_uom.keys():
                fnc = self._product_get
                if recursive:
                    fnc = self._product_all_get
                ctx = context.copy()
                ctx['uom'] = uom_id
                qty = fnc(cr,
                          uid,
                          id, [x.id for x in products_by_uom[uom_id]],
                          context=ctx)
                for product_id in qty.keys():
                    if not qty[product_id]:
                        continue
                    prod_p_qty = 0
                    product = products_by_id[product_id]
                    quantity_total += qty[product_id]

                    # Compute based on pricetype
                    # Choose the right filed standard_price to read
                    amount_unit = product.price_get(
                        'standard_price', context=context)[product.id]
                    price = qty[product_id] * amount_unit

                    prod_p_qty = (qty[product_id] / product.uom_id.factor *
                                  product.uom_po_id.factor)

                    total_price += price
                    result['product'].append({
                        'price': amount_unit,
                        'prod_name': product.name_sort_en,
                        'prod_name_cn': product.name_sort_cn,
                        'code': product.
                        default_code,  # used by lot_overview_all report!
                        'variants': product.variants or '',
                        'uom': product.uom_id.name,
                        'p_uom': product.uom_po_id.name,
                        'prod_qty': qty[product_id],
                        'prod_p_qty': prod_p_qty,
                        'price_value': price,
                    })
        result['total'] = quantity_total
        result['total_price'] = total_price
        return result

    _columns = {
        'location_return':
        fields.boolean(_('For Return ?'),
                       help=_('This location is for return goods?')),
    }
Example #46
0
    def _get_move_lines(self,
                        cr,
                        uid,
                        ids,
                        to_wh,
                        period_id,
                        pay_journal_id,
                        writeoff_acc_id,
                        writeoff_period_id,
                        writeoff_journal_id,
                        date,
                        name,
                        context=None):
        """ Generate move lines in corresponding account
        @param to_wh: whether or not withheld
        @param period_id: Period
        @param pay_journal_id: pay journal of the invoice
        @param writeoff_acc_id: account where canceled
        @param writeoff_period_id: period where canceled
        @param writeoff_journal_id: journal where canceled
        @param date: current date
        @param name: description
        """
        context = context or {}
        ids = isinstance(ids, (int, long)) and [ids] or ids
        res = super(account_invoice, self)._get_move_lines(cr,
                                                           uid,
                                                           ids,
                                                           to_wh,
                                                           period_id,
                                                           pay_journal_id,
                                                           writeoff_acc_id,
                                                           writeoff_period_id,
                                                           writeoff_journal_id,
                                                           date,
                                                           name,
                                                           context=context)

        if not context.get('income_wh', False):
            return res

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

        types = {
            'out_invoice': -1,
            'in_invoice': 1,
            'out_refund': 1,
            'in_refund': -1
        }
        direction = types[inv_brw.type]

        for iwdl_brw in to_wh:
            if inv_brw.type in ('out_invoice', 'out_refund'):
                acc = iwdl_brw.concept_id.property_retencion_islr_receivable and \
                    iwdl_brw.concept_id.property_retencion_islr_receivable.id or \
                    False
            else:
                acc = iwdl_brw.concept_id.property_retencion_islr_payable and \
                    iwdl_brw.concept_id.property_retencion_islr_payable.id or False
            if not acc:
                raise osv.except_osv(
                    _('Missing Account in Tax!'),
                    _("Tax [%s] has missing account. "
                      "Please, fill the missing fields") %
                    (iwdl_brw.concept_id.name, ))
            res.append((0, 0, {
                'debit':
                direction * iwdl_brw.amount < 0
                and -direction * iwdl_brw.amount,
                'credit':
                direction * iwdl_brw.amount > 0
                and direction * iwdl_brw.amount,
                'account_id':
                acc,
                'partner_id':
                inv_brw.partner_id.id,
                'ref':
                inv_brw.number,
                'date':
                date,
                'currency_id':
                False,
                'name':
                _('%s - ISLR: %s') % (name, iwdl_brw.islr_rates_id.code)
            }))

        return res
Example #47
0
    def action_invoice_create(self, cr, uid, ids):
        res = False
        invoice_obj = self.pool.get('account.invoice')
        property_obj = self.pool.get('ir.property')
        sequence_obj = self.pool.get('ir.sequence')
        analytic_journal_obj = self.pool.get('account.analytic.journal')
        account_journal = self.pool.get('account.journal')
        for exp in self.browse(cr, uid, ids):
            lines = []
            for l in exp.line_ids:
                tax_id = []
                if l.product_id:
                    acc = l.product_id.product_tmpl_id.property_account_expense
                    if not acc:
                        acc = l.product_id.categ_id.property_account_expense_categ
                    tax_id = [x.id for x in l.product_id.supplier_taxes_id]
                else:
                    acc = property_obj.get(cr, uid,
                                           'property_account_expense_categ',
                                           'product.category')
                    if not acc:
                        raise osv.except_osv(
                            _('Error !'),
                            _('Please configure Default Expense account for Product purchase, `property_account_expense_categ`'
                              ))

                lines.append((0, False, {
                    'name':
                    l.name,
                    'account_id':
                    acc.id,
                    'price_unit':
                    l.unit_amount,
                    'quantity':
                    l.unit_quantity,
                    'uos_id':
                    l.uom_id.id,
                    'product_id':
                    l.product_id and l.product_id.id or False,
                    'invoice_line_tax_id':
                    tax_id and [(6, 0, tax_id)] or False,
                    'account_analytic_id':
                    l.analytic_account.id,
                }))
            if not exp.employee_id.address_home_id:
                raise osv.except_osv(
                    _('Error !'), _('The employee must have a Home address.'))
            if not exp.employee_id.address_home_id.partner_id:
                raise osv.except_osv(
                    _('Error !'),
                    _("The employee's home address must have a partner linked."
                      ))
            acc = exp.employee_id.address_home_id.partner_id.property_account_payable.id
            payment_term_id = exp.employee_id.address_home_id.partner_id.property_payment_term.id
            inv = {
                'name':
                exp.name,
                'reference':
                sequence_obj.get(cr, uid, 'hr.expense.invoice'),
                'account_id':
                acc,
                'type':
                'in_invoice',
                'partner_id':
                exp.employee_id.address_home_id.partner_id.id,
                'address_invoice_id':
                exp.employee_id.address_home_id.id,
                'address_contact_id':
                exp.employee_id.address_home_id.id,
                'origin':
                exp.name,
                'invoice_line':
                lines,
                'currency_id':
                exp.currency_id.id,
                'payment_term':
                payment_term_id,
                'fiscal_position':
                exp.employee_id.address_home_id.partner_id.
                property_account_position.id
            }
            if payment_term_id:
                to_update = invoice_obj.onchange_payment_term_date_invoice(
                    cr, uid, [], payment_term_id, None)
                if to_update:
                    inv.update(to_update['value'])
            journal = False
            if exp.journal_id:
                inv['journal_id'] = exp.journal_id.id
                journal = exp.journal_id
            else:
                journal_id = invoice_obj._get_journal(
                    cr, uid, context={'type': 'in_invoice'})
                if journal_id:
                    inv['journal_id'] = journal_id
                    journal = account_journal.browse(cr, uid, journal_id)
            if journal and not journal.analytic_journal_id:
                analytic_journal_ids = analytic_journal_obj.search(
                    cr, uid, [('type', '=', 'purchase')])
                if analytic_journal_ids:
                    account_journal.write(
                        cr, uid, [journal.id],
                        {'analytic_journal_id': analytic_journal_ids[0]})
            inv_id = invoice_obj.create(cr, uid, inv, {'type': 'in_invoice'})
            invoice_obj.button_compute(cr,
                                       uid, [inv_id], {'type': 'in_invoice'},
                                       set_total=True)

            self.write(cr, uid, [exp.id], {
                'invoice_id': inv_id,
                'state': 'invoiced'
            })
            res = inv_id
        return res
Example #48
0
 def create_ext_shipping(self, cr, uid, id, picking_type,
                         external_referential_id, context):
     osv.except_osv(_("Not Implemented"),
                    _("Not Implemented in abstract base module!"))
Example #49
0
    def process_ship_accept(self, cr, uid, do, packages, context=None):
        shipment_accept_request_xml = self.create_ship_accept_request_new(
            cr, uid, do, context=context)
        if do.logis_company.test_mode:
            acce_web = do.logis_company.ship_accpt_test_web or ''
            acce_port = do.logis_company.ship_accpt_test_port
        else:
            acce_web = do.logis_company.ship_accpt_web or ''
            acce_port = do.logis_company.ship_accpt_port
        if acce_web:
            parse_url = urlparse(acce_web)
            serv = parse_url.netloc
            serv_path = parse_url.path
        else:
            raise osv.except_osv(
                _('Unable to find Shipping URL!'),
                _("Please configure the shipping company with websites."))

        conn = httplib.HTTPSConnection(serv, acce_port)
        res = conn.request("POST", serv_path, shipment_accept_request_xml)
        import xml2dic
        res = conn.getresponse()
        result = res.read()

        response_dic = xml2dic.main(result)
        NegotiatedRates = ''
        ShipmentIdentificationNumber = ''
        TrackingNumber = ''
        label_image = ''
        control_log_image = ''
        status = 0

        status_description = ''
        for response in response_dic['ShipmentAcceptResponse']:
            if response.get('Response'):
                for resp_items in response['Response']:
                    if resp_items.get('ResponseStatusCode') and resp_items[
                            'ResponseStatusCode'] == '1':
                        status = 1
                    if resp_items.get('ResponseStatusDescription'):
                        status_description = resp_items[
                            'ResponseStatusDescription']
                    if resp_items.get('Error'):
                        for err in resp_items['Error']:
                            if err.get('ErrorSeverity'):
                                status_description += '\n' + err.get(
                                    'ErrorSeverity')
                            if err.get('ErrorDescription'):
                                status_description += '\n' + err.get(
                                    'ErrorDescription')
            do.write({'ship_message': status_description})

        packages_ids = [package.id for package in do.packages_ids]

        if status:
            shipment_identific_number, tracking_number_notes, ship_charge = '', '', 0.0
            for shipmentresult in response_dic['ShipmentAcceptResponse']:
                if shipmentresult.get('ShipmentResults'):
                    package_obj = self.pool.get('stock.packages')
                    for package in response['ShipmentResults']:
                        if package.get('ShipmentIdentificationNumber'):
                            shipment_identific_number = package[
                                'ShipmentIdentificationNumber']
                            continue
                        ship_charge += package.get(
                            'ShipmentCharges') and float(
                                package['ShipmentCharges'][2]['TotalCharges']
                                [1]['MonetaryValue']) or 0.0
                        if package.get('PackageResults'):
                            label_image = ''
                            tracking_number = ''
                            label_code = ''
                            tracking_url = do.logis_company.ship_tracking_url or ''
                            for tracks in package['PackageResults']:
                                if tracks.get('TrackingNumber'):
                                    tracking_number = tracks['TrackingNumber']
                                    if tracking_url:
                                        try:
                                            tracking_url = tracking_url % tracking_number
                                        except Exception, e:
                                            tracking_url = "Invalid tracking url on shipping company"
                                if tracks.get('LabelImage'):
                                    for label in tracks['LabelImage']:
                                        if label.get('LabelImageFormat'):
                                            for format in label[
                                                    'LabelImageFormat']:
                                                label_code = format.get('Code')
                                        if label.get('GraphicImage'):
                                            label_image = label['GraphicImage']
                                            im_in_raw = base64.decodestring(
                                                label_image)
                                            path = tempfile.mktemp('.txt')
                                            temp = file(path, 'wb')
                                            temp.write(im_in_raw)
                                            result = base64.b64encode(
                                                im_in_raw)
                                            (dirName,
                                             fileName) = os.path.split(path)
                                            self.pool.get(
                                                'ir.attachment').create(
                                                    cr,
                                                    uid, {
                                                        'name': fileName,
                                                        'datas': result,
                                                        'datas_fname':
                                                        fileName,
                                                        'res_model':
                                                        self._name,
                                                        'res_id': do.id,
                                                        'type': 'binary'
                                                    },
                                                    context=context)
                                            temp.close()
                                            try:
                                                new_im = Image.open(path)
                                                new_im = new_im.rotate(270)
                                                new_im.save(path, 'JPEG')
                                            except Exception, e:
                                                pass
                                            label_from_file = open(path, 'rb')
                                            label_image = base64.encodestring(
                                                label_from_file.read())
                                            label_from_file.close()
                                            if label_code == 'GIF':
                                                package_obj.write(
                                                    cr,
                                                    uid,
                                                    packages_ids[packages], {
                                                        'tracking_no':
                                                        tracking_number,
                                                        'shipment_identific_no':
                                                        shipment_identific_number,
                                                        'logo': label_image,
                                                        'ship_state':
                                                        'in_process',
                                                        'tracking_url':
                                                        tracking_url,
                                                        'att_file_name':
                                                        fileName
                                                    },
                                                    context=context)
                                            else:
                                                package_obj.write(
                                                    cr,
                                                    uid,
                                                    packages_ids[packages], {
                                                        'tracking_no':
                                                        tracking_number,
                                                        'shipment_identific_no':
                                                        shipment_identific_number,
                                                        'ship_state':
                                                        'in_process',
                                                        'tracking_url':
                                                        tracking_url,
                                                        'att_file_name':
                                                        fileName
                                                    },
                                                    context=context)

                                            if int(
                                                    time.strftime("%w")
                                            ) in range(1, 6) or (
                                                    time.strftime("%w") == '6'
                                                    and do.sat_delivery):
                                                next_pic_date = time.strftime(
                                                    "%Y-%m-%d")
                                            else:
                                                timedelta = datetime.timedelta(
                                                    7 -
                                                    int(time.strftime("%w")))
                                                next_pic_date = (
                                                    datetime.datetime.today() +
                                                    timedelta
                                                ).strftime("%Y-%m-%d")

                                            package_data = package_obj.read(
                                                cr,
                                                uid,
                                                packages_ids[packages],
                                                ['weight', 'description'],
                                                context=context)
                                            #                                             i += 1
                                            ship_move_obj = self.pool.get(
                                                'shipping.move')
                                            if label_code == 'GIF':
                                                ship_move_obj.create(cr, uid, {
                                                    'pick_id': do.id,
                                                    'package_weight': package_data['weight'],
                                                    'partner_id': do.partner_id.id,
                                                    'service': do.ups_service.id,
                                                    'ship_to': do.partner_id.id,
                                                    'ship_from': do.ship_from and do.ship_from_address.id  or \
                                                                 do.shipper and do.shipper.address and do.shipper.address.id,
                                                    'tracking_no': tracking_number,
                                                    'shipment_identific_no': shipment_identific_number,
                                                    'logo': label_image,
                                                    'state': 'ready_pick',
                                                    'tracking_url': tracking_url,
                                                    'package': package_data['description'] and str(package_data['description'])[:126],
                                                    'pic_date': next_pic_date,
                                                    'sale_id': do.sale_id.id and do.sale_id.id or False,
                                                    }, context=context)
                                            else:
                                                ship_move_obj.create(cr, uid, {
                                                    'pick_id': do.id,
                                                    'package_weight': package_data['weight'],
                                                    'partner_id': do.partner_id.id,
                                                    'service': do.ups_service.id,
                                                    'ship_to': do.partner_id.id,
                                                    'ship_from': do.ship_from and do.ship_from_address.id  or \
                                                                 do.shipper and do.shipper.address and do.shipper.address.id,
                                                    'tracking_no': tracking_number,
                                                    'shipment_identific_no': shipment_identific_number,
                                                    'state': 'ready_pick',
                                                    'tracking_url': tracking_url,
                                                    'package': package_data['description'] and str(package_data['description'])[:126],
                                                    'pic_date': next_pic_date,
                                                    'sale_id': do.sale_id.id and do.sale_id.id or False,
                                                    }, context=context)
                                            tracking_number_notes += '\n' + tracking_number

                        if package.get('ControlLogReceipt'):
                            for items in package['ControlLogReceipt']:
                                if items.get('GraphicImage'):
                                    control_log_image = items['GraphicImage']
                                    im_in_raw = base64.decodestring(
                                        control_log_image)
                                    file_name = tempfile.mktemp()
                                    path = file_name = '.html'
                                    temp = file(path, 'wb')
                                    temp.write(im_in_raw)
                                    temp.close()
                                    label_from_file = open(path, 'rb')
                                    control_log_image = base64.encodestring(
                                        label_from_file.read())
                                    label_from_file.close()
                                    package_obj.write(
                                        cr,
                                        uid,
                                        packages_ids, {
                                            'control_log_receipt':
                                            control_log_image,
                                        },
                                        context=context)
Example #50
0
    def create_returns(self, cr, uid, ids, context=None):
        """ 
         Creates return picking.
         @param self: The object pointer.
         @param cr: A database cursor
         @param uid: ID of the user currently logged in
         @param ids: List of ids selected
         @param context: A standard dictionary
         @return: A dictionary which of fields with values.
        """
        if context is None:
            context = {}
        record_id = context and context.get('active_id', False) or False
        move_obj = self.pool.get('stock.move')
        pick_obj = self.pool.get('stock.picking')
        uom_obj = self.pool.get('product.uom')
        data_obj = self.pool.get('stock.return.picking.memory')
        act_obj = self.pool.get('ir.actions.act_window')
        model_obj = self.pool.get('ir.model.data')
        wf_service = netsvc.LocalService("workflow")
        pick = pick_obj.browse(cr, uid, record_id, context=context)
        data = self.read(cr, uid, ids[0], context=context)
        date_cur = time.strftime('%Y-%m-%d %H:%M:%S')
        set_invoice_state_to_none = False  #True LY by default
        returned_lines = 0
        return_type = 'customer'

        # Create new picking for returned products
        if pick.type == 'out':
            new_type = 'in'
        elif pick.type == 'in':
            new_type = 'out'
        else:
            new_type = 'internal'

        seq_obj_name = 'stock.picking.' + new_type
        # SHOULD USE ir_sequence.next_by_code() or ir_sequence.next_by_id()
        new_pick_name = self.pool.get('ir.sequence').get(cr, uid, seq_obj_name)
        new_picking_vals = {
            'name':
            _('%s-%s-return') % (new_pick_name, pick.name),
            'move_lines': [],
            'state':
            'draft',
            'type':
            new_type,
            'return':
            data['return_type'],
            'note':
            data['note'],
            'return_reason_id':
            data['return_reason_id'] and data['return_reason_id']
            [0],  #data return (id,code) eg. (10, 'operation')
            'date':
            date_cur,
            'invoice_state':
            data['invoice_state'],
        }
        new_picking = pick_obj.copy(cr, uid, pick.id, new_picking_vals)

        val_id = data['product_return_moves']
        for v in val_id:
            data_get = data_obj.browse(cr, uid, v, context=context)
            mov_id = data_get.move_id.id
            new_qty = data_get.quantity
            move = move_obj.browse(cr, uid, mov_id, context=context)
            if move.state in ('cancel') or move.scrapped:
                continue
            new_location = move.location_dest_id.id
            returned_qty = move.product_qty
            for rec in move.move_history_ids2:
                returned_qty -= rec.product_qty

            #if  data['invoice_state'] == 'none':#returned_qty == new_qty #!= new_qty:
            #    set_invoice_state_to_none = True#LY False
            if new_qty:
                returned_lines += 1
                new_move_vals = {
                    'product_qty':
                    new_qty,
                    'product_uos_qty':
                    uom_obj._compute_qty(cr, uid, move.product_uom.id, new_qty,
                                         move.product_uos.id),
                    'picking_id':
                    new_picking,
                    'state':
                    'draft',
                    'location_id':
                    new_location,
                    'location_dest_id':
                    move.location_id.id,
                    'date':
                    date_cur,
                    'note':
                    data['note'],
                    'return_reason_id':
                    data['return_reason_id'] and data['return_reason_id'][0],
                }  #data return (id,code) eg. (10, 'operation')
                if data['location_id']:
                    if data['return_type'] == 'customer':
                        new_move_vals.update({
                            'location_dest_id':
                            data['location_id'][0],
                        })
                    else:
                        new_move_vals.update({
                            'location_id':
                            data['location_id'][0],
                        })

                new_move = move_obj.copy(cr, uid, move.id, new_move_vals)
                move_obj.write(cr,
                               uid, [move.id],
                               {'move_history_ids2': [(4, new_move)]},
                               context=context)
        if not returned_lines:
            raise osv.except_osv(
                _('Warning!'),
                _("Please specify at least one non-zero quantity."))

        #LY make it can be invoiced
        if data['invoice_state'] == 'none':  #returned_qty == new_qty #!= new_qty:
            set_invoice_state_to_none = True  #LY False
        if set_invoice_state_to_none:
            pick_obj.write(cr,
                           uid, [pick.id], {'invoice_state': 'none'},
                           context=context)
        wf_service.trg_validate(uid, 'stock.picking', new_picking,
                                'button_confirm', cr)
        pick_obj.force_assign(cr, uid, [new_picking], context)
        # Update view id in context, lp:702939
        model_list = {
            'out': 'stock.picking.out',
            'in': 'stock.picking.in',
            'internal': 'stock.picking',
        }
        return {
            'domain': "[('id', 'in', [" + str(new_picking) + "])]",
            'name': _('Returned Picking'),
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': model_list.get(new_type, 'stock.picking'),
            'type': 'ir.actions.act_window',
            'context': context,
        }
    def data_save(self, cr, uid, ids, context=None):
        """
        This function close account fiscalyear and create entries in new fiscalyear
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param ids: List of Account fiscalyear close state’s IDs

        """
        obj_acc_period = self.pool.get('account.period')
        obj_acc_fiscalyear = self.pool.get('account.fiscalyear')
        obj_acc_journal = self.pool.get('account.journal')
        obj_acc_move_line = self.pool.get('account.move.line')
        obj_acc_account = self.pool.get('account.account')
        obj_acc_journal_period = self.pool.get('account.journal.period')

        data =  self.read(cr, uid, ids, context=context)

        if context is None:
            context = {}
        fy_id = data[0]['fy_id']

        cr.execute("SELECT id FROM account_period WHERE date_stop < (SELECT date_start FROM account_fiscalyear WHERE id = %s)", (str(data[0]['fy2_id']),))
        fy_period_set = ','.join(map(lambda id: str(id[0]), cr.fetchall()))
        cr.execute("SELECT id FROM account_period WHERE date_start > (SELECT date_stop FROM account_fiscalyear WHERE id = %s)", (str(fy_id),))
        fy2_period_set = ','.join(map(lambda id: str(id[0]), cr.fetchall()))

        period = obj_acc_period.browse(cr, uid, data[0]['period_id'], context=context)
        new_fyear = obj_acc_fiscalyear.browse(cr, uid, data[0]['fy2_id'], context=context)
        old_fyear = obj_acc_fiscalyear.browse(cr, uid, data[0]['fy_id'], context=context)

        new_journal = data[0]['journal_id']
        new_journal = obj_acc_journal.browse(cr, uid, new_journal, context=context)

        if not new_journal.default_credit_account_id or not new_journal.default_debit_account_id:
            raise osv.except_osv(_('UserError'),
                    _('The journal must have default credit and debit account'))
        if (not new_journal.centralisation) or new_journal.entry_posted:
            raise osv.except_osv(_('UserError'),
                    _('The journal must have centralised counterpart without the Skipping draft state option checked!'))

        move_ids = obj_acc_move_line.search(cr, uid, [
            ('journal_id', '=', new_journal.id), ('period_id.fiscalyear_id', '=', new_fyear.id)])

        if move_ids:
            obj_acc_move_line._remove_move_reconcile(cr, uid, move_ids, context=context)
            obj_acc_move_line.unlink(cr, uid, move_ids, context=context)

        cr.execute("SELECT id FROM account_fiscalyear WHERE date_stop < %s", (str(new_fyear.date_start),))
        result = cr.dictfetchall()
        fy_ids = ','.join([str(x['id']) for x in result])
        query_line = obj_acc_move_line._query_get(cr, uid,
                obj='account_move_line', context={'fiscalyear': fy_ids})
        cr.execute('select id from account_account WHERE active AND company_id = %s', (old_fyear.company_id.id,))
        ids = map(lambda x: x[0], cr.fetchall())
        for account in obj_acc_account.browse(cr, uid, ids,
            context={'fiscalyear': fy_id}):
            accnt_type_data = account.user_type
            if not accnt_type_data:
                continue
            if accnt_type_data.close_method=='none' or account.type == 'view':
                continue
            if accnt_type_data.close_method=='balance':
                if abs(account.balance)>0.0001:
                    obj_acc_move_line.create(cr, uid, {
                        'debit': account.balance>0 and account.balance,
                        'credit': account.balance<0 and -account.balance,
                        'name': data[0]['report_name'],
                        'date': period.date_start,
                        'journal_id': new_journal.id,
                        'period_id': period.id,
                        'account_id': account.id
                    }, {'journal_id': new_journal.id, 'period_id':period.id})
            if accnt_type_data.close_method == 'unreconciled':
                offset = 0
                limit = 100
                while True:
                    cr.execute('SELECT id, name, quantity, debit, credit, account_id, ref, ' \
                                'amount_currency, currency_id, blocked, partner_id, ' \
                                'date_maturity, date_created ' \
                            'FROM account_move_line ' \
                            'WHERE account_id = %s ' \
                                'AND ' + query_line + ' ' \
                                'AND reconcile_id is NULL ' \
                            'ORDER BY id ' \
                            'LIMIT %s OFFSET %s', (account.id, limit, offset))
                    result = cr.dictfetchall()
                    if not result:
                        break
                    for move in result:
                        move.pop('id')
                        move.update({
                            'date': period.date_start,
                            'journal_id': new_journal.id,
                            'period_id': period.id,
                        })
                        obj_acc_move_line.create(cr, uid, move, {
                            'journal_id': new_journal.id,
                            'period_id': period.id,
                            })
                    offset += limit

                #We have also to consider all move_lines that were reconciled
                #on another fiscal year, and report them too
                offset = 0
                limit = 100
                while True:
                    cr.execute('SELECT  DISTINCT b.id, b.name, b.quantity, b.debit, b.credit, b.account_id, b.ref, ' \
                                'b.amount_currency, b.currency_id, b.blocked, b.partner_id, ' \
                                'b.date_maturity, b.date_created ' \
                            'FROM account_move_line a, account_move_line b ' \
                            'WHERE b.account_id = %s ' \
                                'AND b.reconcile_id is NOT NULL ' \
                                'AND a.reconcile_id = b.reconcile_id ' \
                                'AND b.period_id IN ('+fy_period_set+') ' \
                                'AND a.period_id IN ('+fy2_period_set+') ' \
                            'ORDER BY id ' \
                            'LIMIT %s OFFSET %s', (account.id, limit, offset))
                    result = cr.dictfetchall()
                    if not result:
                        break
                    for move in result:
                        move.pop('id')
                        move.update({
                            'date': period.date_start,
                            'journal_id': new_journal.id,
                            'period_id': period.id,
                        })
                        obj_acc_move_line.create(cr, uid, move, {
                            'journal_id': new_journal.id,
                            'period_id': period.id,
                            })
                    offset += limit
            if accnt_type_data.close_method=='detail':
                offset = 0
                limit = 100
                while True:
                    cr.execute('SELECT id, name, quantity, debit, credit, account_id, ref, ' \
                                'amount_currency, currency_id, blocked, partner_id, ' \
                                'date_maturity, date_created ' \
                            'FROM account_move_line ' \
                            'WHERE account_id = %s ' \
                                'AND ' + query_line + ' ' \
                            'ORDER BY id ' \
                            'LIMIT %s OFFSET %s', (account.id, limit, offset))

                    result = cr.dictfetchall()
                    if not result:
                        break
                    for move in result:
                        move.pop('id')
                        move.update({
                            'date': period.date_start,
                            'journal_id': new_journal.id,
                            'period_id': period.id,
                        })
                        obj_acc_move_line.create(cr, uid, move)
                    offset += limit
        ids = obj_acc_move_line.search(cr, uid, [('journal_id','=',new_journal.id),
            ('period_id.fiscalyear_id','=',new_fyear.id)])
        context['fy_closing'] = True

        if ids:
            obj_acc_move_line.reconcile(cr, uid, ids, context=context)
        new_period = data[0]['period_id']
        ids = obj_acc_journal_period.search(cr, uid, [('journal_id','=',new_journal.id),('period_id','=',new_period)])
        if not ids:
            ids = [obj_acc_journal_period.create(cr, uid, {
                   'name': (new_journal.name or '')+':'+(period.code or ''),
                   'journal_id': new_journal.id,
                   'period_id': period.id
               })]
        cr.execute('UPDATE account_fiscalyear ' \
                    'SET end_journal_period_id = %s ' \
                    'WHERE id = %s', (ids[0], old_fyear.id))
        return {'type': 'ir.actions.act_window_close'}
Example #52
0
    def process_ship(self, cr, uid, ids, context=None):
        company = self.pool.get('res.users').browse(cr,
                                                    uid,
                                                    uid,
                                                    context=context).company_id
        res = {
            'type': 'ir.actions.client',
            'tag': 'printer_proxy.print',
            'name': _('Print Shipping Label'),
            'params': {
                'printer_name': company.printer_proxy_device_name,
                'url': company.printer_proxy_url,
                'username': company.printer_proxy_username,
                'password': company.printer_proxy_password,
                'data': [],
                'format': 'epl2'
            }
        }
        data = self.browse(cr,
                           uid,
                           type(ids) == type([]) and ids[0] or ids,
                           context=context)

        # Pass on up this function call if the shipping company specified was not UPS.
        if data.ship_company_code != 'ups':
            return super(stock_picking_out, self).process_ship(cr,
                                                               uid,
                                                               ids,
                                                               context=context)

        if not (data.logis_company or data.shipper or data.ups_service):
            raise osv.except_osv(
                "Warning",
                "Please select a Logistics Company, Shipper and Shipping Service."
            )

        if not (data.logis_company
                and data.logis_company.ship_company_code == 'ups'):
            return super(stock_picking_out, self).process_ship(cr,
                                                               uid,
                                                               ids,
                                                               context=context)

        if not data.packages_ids or len(data.packages_ids) == 0:
            raise osv.except_osv("Warning", "Please define your packages.")

        error = False
        ups_config = api.v1.get_config(cr,
                                       uid,
                                       sale=data.sale_id,
                                       context=context)

        for pkg in data.packages_ids:
            try:
                # Get the shipping label, store it, and return it.
                label = api.v1.get_label(ups_config, data, pkg)
                res['params']['data'].append(base64.b64encode(label.label))
                self.pool.get('stock.packages').write(
                    cr, uid, [pkg.id], {
                        'logo': label.label,
                        'tracking_no': label.tracking,
                        'ship_message': 'Shipment has processed'
                    })

            except Exception, e:
                if not error:
                    error = []
                error_str = str(e)
                error.append(error_str)

            if error:
                self.pool.get('stock.packages').write(
                    cr,
                    uid,
                    pkg.id, {'ship_message': error_str},
                    context=context)
def parser( cr, uid, ids, data, context ):
    # Process filters from wizard 
    report_type = data['form']['type']
    start_date = data['form']['start_date']
    end_date = data['form']['end_date']
    accounts = data['form'].get('accounts', [])
    if accounts:
        accounts = accounts[0][2]
    else:
        accounts = []
    journals = data['form'].get('journals', [])
    if journals:
        journals = journals[0][2]
    else:
        journals = []
    periods = data['form'].get('periods', [])
    if periods:
        periods = periods[0][2]
    else:
        periods = []
    start_account = data['form'].get('start_account')
    depth = data['form'].get('depth', 0)
    show_balance_zero = data['form'].get('show_balance_zero', False)
    partner_type = data['form'].get('partner_type')
    fiscal_year = data['form'].get('fiscal_year')
    accumulated_periods = data['form'].get('accumulated_periods')
    if accumulated_periods:
        accumulated_periods = accumulated_periods[0][2]
    else:
        accumulated_periods = []

    order = data['form'].get('order')

    pool = pooler.get_pool(cr.dbname)

    # SUBTITLE Parameters
    subtitle = {}
    if start_date:
        subtitle['start_date'] = datetime.strptime( start_date, '%Y-%m-%d' ).strftime( '%d/%m/%Y' )
    else:
        subtitle['start_date'] = '*'
    if end_date:
        subtitle['end_date'] = datetime.strptime( end_date, '%Y-%m-%d' ).strftime( '%d/%m/%Y' )
    else:
        subtitle['end_date'] = '*'

    if journals:
        subtitle['journals'] = ''
        js = pool.get('account.journal').search(cr, uid, [('id','in',journals)], context=context)
        
        journals_subtitle = []
        for x in pool.get('account.journal').read(cr, uid, js, ['name'], context):
            journals_subtitle.append( x['name'] )
        subtitle['journals'] = ','.join( journals_subtitle )
    else:
        subtitle['journals'] = _('ALL JOURNALS')

    if periods:
        subtitle['periods'] = []
        js = pool.get('account.period').search(cr, uid, [('id','in',periods)], order='date_start ASC, date_stop ASC', context=context)
        periods_subtitle = []
        for x in pool.get('account.period').browse(cr, uid, js, context):
            periods_subtitle.append( x.name )
        subtitle['periods'] = ', '.join( periods_subtitle )
        #last_period_id = False
        #for period in pool.get('account.period').browse(cr, uid, js, context):
        #    if not last_period_id or last_period_id != period.id - 1:
        #        sd = datetime.strptime( period.date_start, '%Y-%m-%d' ).strftime('%d/%m/%Y')
        #        ed = datetime.strptime( period.date_stop, '%Y-%m-%d' ).strftime('%d/%m/%Y')
        #        subtitle['periods'].append( ( sd, ed ) )
        #subtitle['periods'] = '%s - %s' % (subtitle['periods'][0][0], subtitle['periods'][-1][1])
    else:
        subtitle['periods'] = _('ALL PERIODS')

    if accounts:
        js = pool.get('account.account').search(cr, uid, [('id','in',accounts)], context=context)
        accounts_subtitle = []
        for x in pool.get('account.account').browse(cr, uid, js, context):
            if len(accounts_subtitle) > 4:
                accounts_subtitle.append( '...' )
                break
            accounts_subtitle.append( x.code ) 
        subtitle['accounts'] = ', '.join( accounts_subtitle )
    else:
        subtitle['accounts'] = _('ALL ACCOUNTS')


    ids = []
    name = ''
    model = ''
    records = []
    data_source = 'model'
    parameters = {}
    if report_type == 'journal':

        s = ''
        s += _('Dates: %s - %s') % (subtitle['start_date'], subtitle['end_date'])
        s += '\n'
        s += _('Journals: %s') % subtitle['journals']
        s += '\n'
        s += _('Periods: %s') % subtitle['periods']
        parameters['SUBTITLE'] = s

        if start_date:
            start_date = "aml.date >= '%s' AND" % str(start_date)
        else:
            start_date = ''
        if end_date:
            end_date = "aml.date <= '%s' AND" % str(end_date)
        else:
            end_date = ''
        if journals:
            journals = ','.join( [str(x) for x in journals] )
            journals = 'aml.journal_id IN (%s) AND' % journals
        else:
            journals = ''
        if periods:
            periods = ','.join( [str(x) for x in periods] )
            periods = 'aml.period_id IN (%s) AND' % periods
        else:
            periods = ''
        
        if order == 'number':
            order_by = 'am.name, aml.date'
        else:
            order_by = 'aml.date, am.name'

        cr.execute("""
            SELECT 
                aml.id 
            FROM 
                account_move am, 
                account_move_line aml 
            WHERE 
                %s
                %s 
                %s
                %s
                am.id=aml.move_id
            ORDER BY 
                %s
        """ % (
            journals,
            periods,    
            start_date,
            end_date,
            order_by,
        ) )
        ids = [x[0] for x in cr.fetchall()]
        name = 'report.account.journal'
        model = 'account.move.line'
        data_source = 'model'

    elif report_type == 'general-ledger':
        s = ''
        s += _('Dates: %s - %s') % (subtitle['start_date'], subtitle['end_date'])
        s += '\n'
        s += _('Journals: %s') % subtitle['journals']
        s += '\n'
        s += _('Accounts: %s') % subtitle['accounts']
        parameters['SUBTITLE'] = s

        domain = []
        fy_periods = []

        if accounts:
            accounts = [('account_id','in',accounts)]
            domain += accounts
        if periods:
            domain += [('period_id','in',periods)]
            for p in pool.get('account.period').browse(cr, uid, periods, context):
                for pp in p.fiscalyear_id.period_ids:
                    fy_periods.append( pp.id )
            
        if start_date:
            domain += [('date','>=',start_date)]
        if end_date:
            domain += [('date','<=',end_date)]
        visibleIds = pool.get('account.move.line').search(cr, uid, domain, context=context)
        lineDomain = accounts
        if fy_periods:
            lineDomain += [('period_id','in',fy_periods)]
        lineIds = pool.get('account.move.line').search(cr, uid, lineDomain, order='account_id, date, name', context=context)

        if order == 'number':
            order_by = 'am.name, aml.date'
        else:
            order_by = 'aml.date, am.name'

        cr.execute("""
            SELECT
                aml.id
            FROM
                account_move_line aml,
                account_move am
            WHERE
                am.id = aml.move_id AND
                aml.id in (%s)
            ORDER BY
                aml.account_id,
                %s
            """ % (','.join([str(x) for x in lineIds]), order_by) )
        lineIds = [x[0] for x in cr.fetchall()]

        lastAccount = None
        sequence = 0
        for line in pool.get('account.move.line').browse(cr, uid, lineIds, context):
            if lastAccount != line.account_id.id:
                lastAccount = line.account_id.id
                balance = 0.0
            balance += line.debit - line.credit
            if line.id in visibleIds:
                if line.partner_id:
                    partner_name = line.partner_id.name
                else:
                    partner_name = ''
                sequence += 1
                records.append({
                    'sequence': sequence,
                    'account_code': line.account_id.code,
                    'account_name': line.account_id.name,
                    'date': line.date + ' 00:00:00',
                    'move_line_name': line.name,
                    'ref': line.ref,
                    'move_name': line.move_id.name,
                    'partner_name': partner_name,
                    'credit': line.credit,
                    'debit': line.debit,
                    'balance': balance
                })
        name = 'report.account.general.ledger'
        model = 'account.move.line'
        data_source = 'records'
    elif report_type == 'trial-balance':
        s = ''
        s += _('Dates: %s - %s') % (subtitle['start_date'], subtitle['end_date'])
        s += '\n'
        s += _('Periods: %s') % subtitle['periods']
        s += '\n'
        s += _('Accounts: %s') % subtitle['accounts']
        parameters['SUBTITLE'] = s

        if accounts:
            accounts = [('id','in',accounts)]
        else:
            accounts = []
        accounts.append( ('parent_id','!=',False) )
        name = 'report.account.trial.balance'
        model = ''
        data_source = 'records'
        accountIds = pool.get('account.account').search(cr, uid, accounts, order='code', context=context)
        periodContext = context.copy()
        if start_date:
            periodContext['start_date'] = start_date 
        if end_date:
            periodContext['end_date'] = end_date 
        if periods:
            periodContext['periods'] = periods
            fiscal_years = []
            for period in pool.get('account.period').browse(cr, uid, periods, context):
                fiscal_years.append( period.fiscalyear_id.id )
            periodContext['fiscalyear'] = ','.join([str(x) for x in fiscal_years])

        accumulatedContext = context.copy()
        if accumulatedContext:
            accumulatedContext['periods'] = accumulated_periods
            fiscal_years = []
            for period in pool.get('account.period').browse(cr, uid, accumulated_periods, context):
                fiscal_years.append( period.fiscalyear_id.id )
            accumulatedContext['fiscalyear'] = ','.join([str(x) for x in fiscal_years])

        accumulated_records = pool.get('account.account').read(cr, uid, accountIds, ['credit','debit','balance'], accumulatedContext)
        accumulated_dict = dict([(x['id'], x) for x in accumulated_records])

        for account in pool.get('account.account').browse(cr, uid, accountIds, periodContext):
            # Only print accounts that have moves.
            if not account.debit and not account.credit:
                continue
            accumulated_values = accumulated_dict[account.id]
            record = {
                'code': account.code,
                'name': account.name,
                'type': account.type, # Useful for the report designer so accounts of type 'view' may be discarded in aggregation.
                'period_credit': account.credit,
                'period_debit': account.debit,
                'period_balance': account.balance,
                'credit': accumulated_values['credit'],
                'debit': accumulated_values['debit'],
                'balance': accumulated_values['balance'],
            }
            records.append( record )
    elif report_type == 'taxes-by-invoice':
        s = ''
        s += _('Dates: %s - %s') % (subtitle['start_date'], subtitle['end_date'])
        s += '\n'
        s += _('Periods: %s') % subtitle['periods']
        parameters['SUBTITLE'] = s

        name = 'report.account.taxes.by.invoice'
        model = 'account.invoice'

        domain = []
        if start_date:
            domain += [('date_invoice','>=',start_date)]
        if end_date:
            domain += [('date_invoice','<=',end_date)]

        if periods:
            domain += [('period_id','in',periods)]

        if partner_type == 'customers':
            domain += [('type','in',('out_invoice','out_refund'))]
        else:
            domain += [('type','in',('in_invoice','in_refund'))]

        ids = pool.get('account.invoice').search(cr, uid, domain, context=context)


    return { 
        'ids': ids, 
        'name': name, 
        'model': model, 
        'records': records, 
        'data_source': data_source,
        'parameters': parameters,
    }
Example #54
0
class partner(osv.osv):
    _name = 'res.partner'
    _inherit = 'res.partner'

    def _unpayed_amount(self, cr, uid, ids, name, arg, context=None):
        res = {}
        today = now().strftime('%Y-%m-%d')
        for partner in self.browse(cr, uid, ids, context):
            accounts = []
            if partner.property_account_receivable:
                accounts.append(partner.property_account_receivable.id)
            if partner.property_account_payable:
                accounts.append(partner.property_account_payable.id)
            line_ids = self.pool.get('account.move.line').search(
                cr,
                uid, [
                    ('partner_id', '=', partner.id),
                    ('account_id', 'in', accounts),
                    ('reconcile_id', '=', False),
                    ('date_maturity', '<', today),
                ],
                context=context)
            # Those that have amount_to_pay == 0, will mean that they're circulating. The payment request has been sent
            # to the bank but have not yet been reconciled (or the date_maturity has not been reached).
            amount = 0.0
            for line in self.pool.get('account.move.line').browse(
                    cr, uid, line_ids, context):
                #amount += -line.amount_to_pay
                amount += line.debit - line.credit
            res[partner.id] = amount
        return res

    def _circulating_amount(self, cr, uid, ids, name, arg, context=None):
        res = {}
        today = now().strftime('%Y-%m-%d')
        for partner in self.browse(cr, uid, ids, context):
            accounts = []
            if partner.property_account_receivable:
                accounts.append(partner.property_account_receivable.id)
            if partner.property_account_payable:
                accounts.append(partner.property_account_payable.id)
            line_ids = self.pool.get('account.move.line').search(
                cr,
                uid, [('partner_id', '=', partner.id),
                      ('account_id', 'in', accounts),
                      ('reconcile_id', '=', False), '|',
                      ('date_maturity', '>=', today),
                      ('date_maturity', '=', False)],
                context=context)
            # Those that have amount_to_pay == 0, will mean that they're circulating. The payment request has been sent
            # to the bank but have not yet been reconciled (or the date_maturity has not been reached).
            amount = 0.0
            for line in self.pool.get('account.move.line').browse(
                    cr, uid, line_ids, context):
                amount += line.debit - line.credit
            res[partner.id] = amount
        return res

    def _pending_amount(self, cr, uid, ids, name, arg, context=None):
        res = {}
        today = now().strftime('%Y-%m-%d')
        for partner in self.browse(cr, uid, ids, context):
            accounts = []
            if partner.property_account_receivable:
                accounts.append(partner.property_account_receivable.id)
            if partner.property_account_payable:
                accounts.append(partner.property_account_payable.id)
            line_ids = self.pool.get('account.move.line').search(
                cr,
                uid, [('partner_id', '=', partner.id),
                      ('account_id', 'in', accounts),
                      ('reconcile_id', '=', False), '|',
                      ('date_maturity', '>=', today),
                      ('date_maturity', '=', False)],
                context=context)
            # Those that have amount_to_pay == 0, will mean that they're circulating. The payment request has been sent
            # to the bank but have not yet been reconciled (or the date_maturity has not been reached).
            amount = 0.0
            for line in self.pool.get('account.move.line').browse(
                    cr, uid, line_ids, context):
                amount += line.debit - line.credit
            res[partner.id] = amount
        return res

    def _draft_invoices_amount(self, cr, uid, ids, name, arg, context=None):
        res = {}
        today = now().strftime('%Y-%m-%d')
        for id in ids:
            invids = self.pool.get('account.invoice').search(
                cr,
                uid, [('partner_id', '=', id), ('state', '=', 'draft'), '|',
                      ('date_due', '>=', today), ('date_due', '=', False)],
                context=context)
            val = 0.0
            for invoice in self.pool.get('account.invoice').browse(
                    cr, uid, invids, context):
                # Note that even if the invoice is in 'draft' state it can have an account.move because it
                # may have been validated and brought back to draft. Here we'll only consider invoices with
                # NO account.move as those will be added in other fields.
                if invoice.move_id:
                    continue
                if invoice.type in ('out_invoice', 'in_refund'):
                    val += invoice.amount_total
                else:
                    val -= invoice.amount_total
            res[id] = val
        return res

    def _pending_orders_amount(self, cr, uid, ids, name, arg, context=None):
        res = {}
        for id in ids:
            sids = self.pool.get('sale.order').search(
                cr,
                uid, [('partner_id', '=', id),
                      ('state', 'not in', ['draft', 'cancel', 'wait_risk'])],
                context=context)
            total = 0.0
            for order in self.pool.get('sale.order').browse(
                    cr, uid, sids, context):
                total += order.amount_total - order.amount_invoiced
            res[id] = total
        return res

    def _total_debt(self, cr, uid, ids, name, arg, context=None):
        res = {}
        for partner in self.browse(cr, uid, ids, context):
            pending_orders = partner.pending_orders_amount or 0.0
            circulating = partner.circulating_amount or 0.0
            unpayed = partner.unpayed_amount or 0.0
            pending = partner.pending_amount or 0.0
            draft_invoices = partner.draft_invoices_amount or 0.0
            res[partner.
                id] = pending_orders + circulating + unpayed + pending + draft_invoices
        return res

    def _available_risk(self, cr, uid, ids, name, arg, context=None):
        res = {}
        for partner in self.browse(cr, uid, ids, context):
            res[partner.id] = partner.credit_limit - partner.total_debt
        return res

    def _total_risk_percent(self, cr, uid, ids, name, arg, context=None):
        res = {}
        for partner in self.browse(cr, uid, ids, context):
            if partner.credit_limit:
                res[partner.
                    id] = 100.0 * partner.total_debt / partner.credit_limit
            else:
                res[partner.id] = 100
        return res

    _columns = {
        'unpayed_amount':
        fields.function(_unpayed_amount,
                        method=True,
                        string=_('Expired Unpaid Payments'),
                        type='float'),
        'pending_amount':
        fields.function(_pending_amount,
                        method=True,
                        string=_('Unexpired Pending Payments'),
                        type='float'),
        'draft_invoices_amount':
        fields.function(_draft_invoices_amount,
                        method=True,
                        string=_('Draft Invoices'),
                        type='float'),
        'circulating_amount':
        fields.function(_circulating_amount,
                        method=True,
                        string=_('Payments Sent to Bank'),
                        type='float'),
        'pending_orders_amount':
        fields.function(_pending_orders_amount,
                        method=True,
                        string=_('Uninvoiced Orders'),
                        type='float'),
        'total_debt':
        fields.function(_total_debt,
                        method=True,
                        string=_('Total Debt'),
                        type='float'),
        'available_risk':
        fields.function(_available_risk,
                        method=True,
                        string=_('Available Credit'),
                        type='float'),
        'total_risk_percent':
        fields.function(_total_risk_percent,
                        method=True,
                        string=_('Credit Usage (%)'),
                        type='float')
    }
Example #55
0
        if deferred_proc_module and deferred_proc_module['state'] in ('installed', 'to upgrade'):
            result.append('deferred_processing')
        ############################################
        return dict.fromkeys(ids, ','.join(result))

    _columns = {
        'charset':fields.selection(_get_encodings, string='Charset', required=True),
        'content_fname': fields.char('Override Extension',size=64, help='Here you can override output file extension'),
        'styles_mode': fields.selection([
            ('default','Not used'),
            ('global', 'Global'),
            ('specified', 'Specified'),
            ], string='Stylesheet'),
        'stylesheet_id':fields.many2one('report.stylesheets', 'Template Stylesheet'),
        'preload_mode':fields.selection([
            ('static',_('Static')),
            ('preload',_('Preload')),
        ],'Preload Mode'),
        'tml_source':fields.selection([
            ('database','Database'),
            ('file','File'),
            ('parser','Parser'),
        ],'Template source', select=True),
        'parser_def': fields.text('Parser Definition'),
        'parser_loc':fields.char('Parser location', size=128, help="Path to the parser location. Beginning of the path must be start with the module name!\nLike this: {module name}/{path to the parser.py file}"),
        'parser_state':fields.selection([
            ('default',_('Default')),
            ('def',_('Definition')),
            ('loc',_('Location')),
        ],'State of Parser', select=True),
        'in_format': fields.selection(_get_in_mimetypes, 'Template Mime-type'),
Example #56
0
    def set_done(self, cr, uid, ids, context=None):
        result = super(payment_order, self).set_done(cr, uid, ids, context)

        company_currency_id = self.pool.get('res.users').browse(
            cr, uid, uid, context).company_id.currency_id.id

        for order in self.browse(cr, uid, ids, context):
            if order.create_account_moves != 'direct-payment':
                continue

            # This process creates a simple account move with bank and line accounts and line's amount. At the end
            # it will reconcile or partial reconcile both entries if that is possible.

            move_id = self.pool.get('account.move').create(
                cr, uid, {
                    'name': '/',
                    'journal_id': order.mode.journal.id,
                    'period_id': order.period_id.id,
                }, context)

            for line in order.line_ids:
                if not line.amount:
                    continue

                if not line.account_id:
                    raise osv.except_osv(
                        _('Error!'),
                        _('Payment order should create account moves but line with amount %.2f for partner "%s" has no account assigned.'
                          ) % (line.amount, line.partner_id.name))

                currency_id = order.mode.journal.currency and order.mode.journal.currency.id or company_currency_id

                if line.type == 'payable':
                    line_amount = line.amount_currency or line.amount
                else:
                    line_amount = -line.amount_currency or -line.amount

                if line_amount >= 0:
                    account_id = order.mode.journal.default_credit_account_id.id
                else:
                    account_id = order.mode.journal.default_debit_account_id.id
                acc_cur = ((line_amount <= 0)
                           and order.mode.journal.default_debit_account_id
                           ) or line.account_id

                ctx = context.copy()
                ctx['res.currency.compute.account'] = acc_cur
                amount = self.pool.get('res.currency').compute(
                    cr,
                    uid,
                    currency_id,
                    company_currency_id,
                    line_amount,
                    context=ctx)

                val = {
                    'name': line.move_line_id and line.move_line_id.name
                    or '/',
                    'move_id': move_id,
                    'date': order.date_done,
                    'ref': line.move_line_id and line.move_line_id.ref
                    or False,
                    'partner_id': line.partner_id and line.partner_id.id
                    or False,
                    'account_id': line.account_id.id,
                    'debit': ((amount > 0) and amount) or 0.0,
                    'credit': ((amount < 0) and -amount) or 0.0,
                    'journal_id': order.mode.journal.id,
                    'period_id': order.period_id.id,
                    'currency_id': currency_id,
                }

                amount = self.pool.get('res.currency').compute(
                    cr,
                    uid,
                    currency_id,
                    company_currency_id,
                    line_amount,
                    context=ctx)
                if currency_id <> company_currency_id:
                    amount_cur = self.pool.get('res.currency').compute(
                        cr,
                        uid,
                        company_currency_id,
                        currency_id,
                        amount,
                        context=ctx)
                    val['amount_currency'] = -amount_cur

                if line.account_id and line.account_id.currency_id and line.account_id.currency_id.id <> company_currency_id:
                    val['currency_id'] = line.account_id.currency_id.id
                    if company_currency_id == line.account_id.currency_id.id:
                        amount_cur = line_amount
                    else:
                        amount_cur = self.pool.get('res.currency').compute(
                            cr,
                            uid,
                            company_currency_id,
                            line.account_id.currency_id.id,
                            amount,
                            context=ctx)
                    val['amount_currency'] = amount_cur

                partner_line_id = self.pool.get('account.move.line').create(
                    cr, uid, val, context, check=False)

                # Fill the secondary amount/currency
                # if currency is not the same than the company
                if currency_id <> company_currency_id:
                    amount_currency = line_amount
                    move_currency_id = currency_id
                else:
                    amount_currency = False
                    move_currency_id = False

                self.pool.get('account.move.line').create(
                    cr, uid, {
                        'name': line.move_line_id and line.move_line_id.name
                        or '/',
                        'move_id': move_id,
                        'date': order.date_done,
                        'ref': line.move_line_id and line.move_line_id.ref
                        or False,
                        'partner_id': line.partner_id and line.partner_id.id
                        or False,
                        'account_id': account_id,
                        'debit': ((amount < 0) and -amount) or 0.0,
                        'credit': ((amount > 0) and amount) or 0.0,
                        'journal_id': order.mode.journal.id,
                        'period_id': order.period_id.id,
                        'amount_currency': amount_currency,
                        'currency_id': move_currency_id,
                    }, context)

                aml_ids = [
                    x.id for x in self.pool.get('account.move').browse(
                        cr, uid, move_id, context).line_id
                ]
                for x in self.pool.get('account.move.line').browse(
                        cr, uid, aml_ids, context):
                    if x.state <> 'valid':
                        raise osv.except_osv(
                            _('Error !'),
                            _('Account move line "%s" is not valid') % x.name)

                if line.move_line_id and not line.move_line_id.reconcile_id:
                    # If payment line has a related move line, we try to reconcile it with the move we just created.
                    lines_to_reconcile = [
                        partner_line_id,
                    ]

                    # Check if payment line move is already partially reconciled and use those moves in that case.
                    if line.move_line_id.reconcile_partial_id:
                        for rline in line.move_line_id.reconcile_partial_id.line_partial_ids:
                            lines_to_reconcile.append(rline.id)
                    else:
                        lines_to_reconcile.append(line.move_line_id.id)

                    amount = 0.0
                    for rline in self.pool.get('account.move.line').browse(
                            cr, uid, lines_to_reconcile, context):
                        amount += rline.debit - rline.credit

                    currency = self.pool.get('res.users').browse(
                        cr, uid, uid, context).company_id.currency_id

                    if self.pool.get('res.currency').is_zero(
                            cr, uid, currency, amount):
                        self.pool.get('account.move.line').reconcile(
                            cr,
                            uid,
                            lines_to_reconcile,
                            'payment',
                            context=context)
                    else:
                        self.pool.get('account.move.line').reconcile_partial(
                            cr, uid, lines_to_reconcile, 'payment', context)

                if order.mode.journal.entry_posted:
                    self.pool.get('account.move').write(
                        cr, uid, [move_id], {
                            'state': 'posted',
                        }, context)

                self.pool.get('payment.line').write(cr, uid, [line.id], {
                    'payment_move_id': move_id,
                }, context)

        return result
Example #57
0
    def price_get_multi(self,
                        cr,
                        uid,
                        pricelist_ids,
                        products_by_qty_by_partner,
                        context=None):
        """multi products 'price_get'.
           @param pricelist_ids:
           @param products_by_qty:
           @param partner:
           @param context: {
             'date': Date of the pricelist (%Y-%m-%d),}
           @return: a dict of dict with product_id as key and a dict 'price by pricelist' as value
        """
        def _create_parent_category_list(id, lst):
            if not id:
                return []
            parent = product_category_tree.get(id)
            if parent:
                lst.append(parent)
                return _create_parent_category_list(parent, lst)
            else:
                return lst

        # _create_parent_category_list

        if context is None:
            context = {}

        date = time.strftime('%Y-%m-%d')
        if 'date' in context:
            date = context['date']

        currency_obj = self.pool.get('res.currency')
        product_obj = self.pool.get('product.product')
        product_category_obj = self.pool.get('product.category')
        product_uom_obj = self.pool.get('product.uom')
        supplierinfo_obj = self.pool.get('product.supplierinfo')
        price_type_obj = self.pool.get('product.price.type')

        # product.pricelist.version:
        if not pricelist_ids:
            pricelist_ids = self.pool.get('product.pricelist').search(
                cr, uid, [], context=context)

        pricelist_version_ids = self.pool.get(
            'product.pricelist.version').search(cr, uid, [
                ('pricelist_id', 'in', pricelist_ids),
                '|',
                ('date_start', '=', False),
                ('date_start', '<=', date),
                '|',
                ('date_end', '=', False),
                ('date_end', '>=', date),
            ])
        if len(pricelist_ids) != len(pricelist_version_ids):
            raise osv.except_osv(
                _('Warning!'),
                _("At least one pricelist has no active version !\nPlease create or activate one."
                  ))

        # product.product:
        product_ids = [i[0] for i in products_by_qty_by_partner]
        #products = dict([(item['id'], item) for item in product_obj.read(cr, uid, product_ids, ['categ_id', 'product_tmpl_id', 'uos_id', 'uom_id'])])
        products = product_obj.browse(cr, uid, product_ids, context=context)
        products_dict = dict([(item.id, item) for item in products])

        # product.category:
        product_category_ids = product_category_obj.search(cr, uid, [])
        product_categories = product_category_obj.read(cr, uid,
                                                       product_category_ids,
                                                       ['parent_id'])
        product_category_tree = dict([(item['id'], item['parent_id'][0])
                                      for item in product_categories
                                      if item['parent_id']])

        results = {}
        for product_id, qty, partner in products_by_qty_by_partner:
            for pricelist_id in pricelist_ids:
                price = False

                tmpl_id = products_dict[
                    product_id].product_tmpl_id and products_dict[
                        product_id].product_tmpl_id.id or False

                categ_id = products_dict[product_id].categ_id and products_dict[
                    product_id].categ_id.id or False
                categ_ids = _create_parent_category_list(categ_id, [categ_id])
                if categ_ids:
                    categ_where = '(categ_id IN (' + ','.join(
                        map(str, categ_ids)) + '))'
                else:
                    categ_where = '(categ_id IS NULL)'

                if partner:
                    partner_where = 'base <> -2 OR %s IN (SELECT name FROM product_supplierinfo WHERE product_id = %s) '
                    partner_args = (partner, tmpl_id)
                else:
                    partner_where = 'base <> -2 '
                    partner_args = ()

                #And
                pl = self.pool.get('product.pricelist').browse(cr,
                                                               uid,
                                                               pricelist_id,
                                                               context=context)
                if pl.type == "purchase":
                    product = products_dict[product_id]
                    if 'uom' in context:
                        uom = product.uom_po_id
                        if uom.id != context['uom']:
                            qty = qty * product.uom_po_id.factor / product.uom_id.factor

                cr.execute(
                    'SELECT i.*, pl.currency_id '
                    'FROM product_pricelist_item AS i, '
                    'product_pricelist_version AS v, product_pricelist AS pl '
                    'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = %s) '
                    'AND (product_id IS NULL OR product_id = %s) '
                    'AND (' + categ_where + ' OR (categ_id IS NULL)) '
                    'AND (' + partner_where + ') '
                    'AND price_version_id = %s '
                    'AND (min_quantity IS NULL OR min_quantity <= %s) '
                    'AND i.price_version_id = v.id AND v.pricelist_id = pl.id '
                    'ORDER BY sequence', (tmpl_id, product_id) + partner_args +
                    (pricelist_version_ids[0], qty))
                res1 = cr.dictfetchall()
                uom_price_already_computed = False
                for res in res1:
                    if res:
                        if res['base'] == -1:
                            if not res['base_pricelist_id']:
                                price = 0.0
                            else:
                                price_tmp = self.price_get(
                                    cr,
                                    uid, [res['base_pricelist_id']],
                                    product_id,
                                    qty,
                                    context=context)[res['base_pricelist_id']]
                                ptype_src = self.browse(
                                    cr, uid,
                                    res['base_pricelist_id']).currency_id.id
                                uom_price_already_computed = True
                                price = currency_obj.compute(
                                    cr,
                                    uid,
                                    ptype_src,
                                    res['currency_id'],
                                    price_tmp,
                                    round=False)
                        elif res['base'] == -2:
                            # this section could be improved by moving the queries outside the loop:
                            where = []
                            if partner:
                                where = [('name', '=', partner)]
                            sinfo = supplierinfo_obj.search(
                                cr, uid,
                                [('product_id', '=', tmpl_id)] + where)
                            price = 0.0
                            if sinfo:
                                qty_in_product_uom = qty
                                product_default_uom = product_obj.read(
                                    cr, uid, [product_id],
                                    ['uom_id'])[0]['uom_id'][0]
                                supplier = supplierinfo_obj.browse(
                                    cr, uid, sinfo, context=context)[0]
                                seller_uom = supplier.product_uom and supplier.product_uom.id or False
                                if seller_uom and product_default_uom and product_default_uom != seller_uom:
                                    uom_price_already_computed = True
                                    qty_in_product_uom = product_uom_obj._compute_qty(
                                        cr,
                                        uid,
                                        product_default_uom,
                                        qty,
                                        to_uom_id=seller_uom)
                                cr.execute('SELECT * ' \
                                        'FROM pricelist_partnerinfo ' \
                                        'WHERE suppinfo_id IN %s' \
                                            'AND min_quantity <= %s ' \
                                        'ORDER BY min_quantity DESC LIMIT 1', (tuple(sinfo), qty_in_product_uom,))
                                res2 = cr.dictfetchone()
                                if res2:
                                    price = res2['price']
                        #Add by Andy
                        elif res['base'] == -3:
                            price = False
                        else:
                            price_type = price_type_obj.browse(
                                cr, uid, int(res['base']))
                            uom_price_already_computed = True
                            price = currency_obj.compute(
                                cr,
                                uid,
                                price_type.currency_id.id,
                                res['currency_id'],
                                product_obj.price_get(
                                    cr,
                                    uid, [product_id],
                                    price_type.field,
                                    context=context)[product_id],
                                round=False,
                                context=context)

                        if price is not False:
                            price_limit = price
                            price = price * (1.0 +
                                             (res['price_discount'] or 0.0))
                            price = rounding(
                                price, res['price_round']
                            )  #TOFIX: rounding with tools.float_rouding
                            price += (res['price_surcharge'] or 0.0)
                            if res['price_min_margin']:
                                price = max(
                                    price,
                                    price_limit + res['price_min_margin'])
                            if res['price_max_margin']:
                                price = min(
                                    price,
                                    price_limit + res['price_max_margin'])
                            break
                        #Add by Andy
                        else:
                            if res['base'] == -3:
                                price = res['price_surcharge'] or 0.0
                                product = products_dict[product_id]
                                if 'uom' in context:
                                    uom = product.uom_po_id
                                    if uom.id != context['uom']:
                                        price = product_uom_obj._compute_price(
                                            cr, uid, uom.id, price,
                                            context['uom'])
                                uom_price_already_computed = True
                                #Todo: # Use company currency?
                                if 'currency_id' in context:
                                    price = currency_obj.compute(
                                        cr,
                                        uid,
                                        1,
                                        context['currency_id'],
                                        price,
                                        context=context)
                                if price:
                                    break
                    else:
                        # False means no valid line found ! But we may not raise an
                        # exception here because it breaks the search
                        price = False

                if price:
                    results['item_id'] = res['id']
                    if 'uom' in context and not uom_price_already_computed:
                        product = products_dict[product_id]
                        uom = product.uos_id or product.uom_id
                        price = product_uom_obj._compute_price(
                            cr, uid, uom.id, price, context['uom'])

                if results.get(product_id):
                    results[product_id][pricelist_id] = price
                else:
                    results[product_id] = {pricelist_id: price}

        return results
Example #58
0
    def write(self, cr, user, ids, vals, context={}):
        if 'report_sxw_content_data' in vals:
            if vals['report_sxw_content_data']:
                try:
                    base64.decodestring(vals['report_sxw_content_data'])
                except binascii.Error:
                    vals['report_sxw_content_data'] = False
        if type(ids)==list:
            ids = ids[0]
        record = self.browse(cr, user, ids)
        #if context and 'model' in vals and not self.pool.get('ir.model').search(cr, user, [('model','=',vals['model'])]):
        #    raise osv.except_osv(_('Object model is not correct !'),_('Please check "Object" field !') )
        if vals.get('report_type', record.report_type) == 'aeroo':
            if vals.get('report_wizard') and vals.get('active', record.active) and \
                        (record.replace_report_id and vals.get('replace_report_id',True) or not record.replace_report_id):
                vals['wizard_id'] = self._set_report_wizard(cr, user, ids, ids, linked_report_id=vals.get('replace_report_id'), context=context)
                record.report_wizard = True
                record.wizard_id = vals['wizard_id']
            elif 'report_wizard' in vals and not vals['report_wizard'] and record.report_wizard:
                self._unset_report_wizard(cr, user, ids, context)
                vals['wizard_id'] = False
                record.report_wizard = False
                record.wizard_id = False
            parser=rml_parse
            if vals.get('parser_state', False)=='loc':
                parser = self.load_from_file(vals.get('parser_loc', False) or record.parser_loc, cr.dbname, record.id) or parser
            elif vals.get('parser_state', False)=='def':
                parser = self.load_from_source("from report import report_sxw\n"+(vals.get('parser_loc', False) or record.parser_def or '')) or parser
            elif vals.get('parser_state', False)=='default':
                parser = rml_parse
            elif record.parser_state=='loc':
                parser = self.load_from_file(record.parser_loc, cr.dbname, record.id) or parser
            elif record.parser_state=='def':
                parser = self.load_from_source("from report import report_sxw\n"+record.parser_def) or parser
            elif record.parser_state=='default':
                parser = rml_parse

            if vals.get('parser_loc', False):
                parser=self.load_from_file(vals['parser_loc'], cr.dbname, record.id) or parser
            elif vals.get('parser_def', False):
                parser=self.load_from_source("from report import report_sxw\n"+vals['parser_def']) or parser
            if vals.get('report_name', False) and vals['report_name']!=record.report_name:
                self.delete_report_service(record.report_name)
                report_name = vals['report_name']
            else:
                self.delete_report_service(record.report_name)
                report_name = record.report_name
            ##### Link / unlink inherited report #####
            link_vals = {}
            now_unlinked = False
            if 'replace_report_id' in vals and vals.get('active', record.active):
                if vals['replace_report_id']:
                    if record.replace_report_id and vals['replace_report_id']!=record.replace_report_id.id:
                        ctx = context.copy()
                        ctx['keep_wizard'] = True # keep window action for wizard, if only inherit report changed
                        link_vals.update(self.unlink_inherit_report(cr, user, ids, ctx))
                        now_unlinked = True
                    link_vals.update(self.link_inherit_report(cr, user, record, new_replace_report_id=vals['replace_report_id'], context=context))
                    self.register_report(cr, report_name, vals.get('model', record.model), vals.get('report_rml', record.report_rml), parser)
                else:
                    link_vals.update(self.unlink_inherit_report(cr, user, ids, context=context))
                    now_unlinked = True
            ##########################################
            try:
                if vals.get('active', record.active):
                    self.register_report(cr, report_name, vals.get('model', record.model), vals.get('report_rml', record.report_rml), parser)
                    if not record.active and vals.get('replace_report_id',record.replace_report_id):
                        link_vals.update(self.link_inherit_report(cr, user, record, new_replace_report_id=vals.get('replace_report_id',False), context=context))
                elif not vals.get('active', record.active):
                    self.unregister_report(cr, report_name)
                    if not now_unlinked:
                        link_vals.update(self.unlink_inherit_report(cr, user, ids, context=context))
            except Exception, e:
                print e
                raise osv.except_osv(_('Report registration error !'), _('Report was not registered in system !'))

            vals.update(link_vals)
            res = super(report_xml, self).write(cr, user, ids, vals, context)
            return res
Example #59
0
    def _price_field_get(self, cr, uid, context=None):
        result = super(product_pricelist_item,
                       self)._price_field_get(cr, uid, context=context)

        result.append((-3, _('Fix Price based on UoP')))
        return result
Example #60
0
    def action_invoice_create(self,
                              cr,
                              uid,
                              ids,
                              journal_id=False,
                              group=False,
                              type='out_invoice',
                              context=None):
        """ Creates invoice based on the invoice state selected for picking.
        @param journal_id: Id of journal
        @param group: Whether to create a group invoice or not
        @param type: Type invoice to be created
        @return: Ids of created invoices for the pickings
        """

        if type == 'in_invoice':
            return super(stock_picking,
                         self).action_invoice_create(cr,
                                                     uid,
                                                     ids,
                                                     journal_id=journal_id,
                                                     group=group,
                                                     type=type,
                                                     context=context)

        if context is None:
            context = {}

        #Lahko se zgodi, da uporabnik ne izbere datuma na wizardu, ponastavimo na danasnji datum
        if not context.get('date_inv', False):
            context['date_inv'] = datetime.now().strftime("%Y-%m-%d")

        invoice_obj = self.pool.get('account.invoice')
        invoice_line_obj = self.pool.get('account.invoice.line')
        partner_obj = self.pool.get('res.partner')
        invoices_group = {}
        res = {}
        inv_type = type

        _picking_ids = self.search(cr,
                                   uid, [('id', 'in', ids)],
                                   order='partner_id,date_done')
        for picking in self.browse(cr, uid, _picking_ids, context=context):
            #for picking in self.browse(cr, uid, ids, context=context):
            if picking.invoice_state != '2binvoiced':
                continue
            #Pridobimo naslov za racun in naslov za grupiranje________________________________
            partner_vals = self._get_partner_obj(cr,
                                                 uid,
                                                 picking,
                                                 context=context)
            partner = partner_vals['parner_invoice']
            partner_id_group = partner_vals['partner_group']
            #_________________________________________________________________________________

            if isinstance(partner, int):
                partner = partner_obj.browse(cr,
                                             uid, [partner],
                                             context=context)[0]
            if not partner:
                raise osv.except_osv(
                    _('Error, no partner !'),
                    _('Please put a partner on the picking list if you want to generate invoice.'
                      ))

            if not inv_type:
                inv_type = self._get_invoice_type(picking)

            if group and partner_id_group in invoices_group:
                invoice_id = invoices_group[partner_id_group]
                invoice = invoice_obj.browse(cr, uid, invoice_id)
                invoice_vals_group = self._prepare_invoice_group(
                    cr, uid, picking, partner, invoice, context=context)
                invoice_vals_group[
                    'delivery_order_origin'] = invoice.delivery_order_origin + ', ' + picking.name
                invoice_vals_group[
                    'name'] = ''  #customer reference - je ne vpisujejo, naj bo prazna
                invoice_obj.write(cr,
                                  uid, [invoice_id],
                                  invoice_vals_group,
                                  context=context)
            else:
                invoice_vals = self._prepare_invoice(cr,
                                                     uid,
                                                     picking,
                                                     partner,
                                                     inv_type,
                                                     journal_id,
                                                     context=context)
                invoice_vals['address_shipping_id'] = partner_id_group
                invoice_vals['delivery_order_origin'] = picking.name

                invoice_vals['decade_date'] = self._get_decade_date(
                    cr, uid, picking, inv_type, partner, context)

                invoice_id = invoice_obj.create(cr,
                                                uid,
                                                invoice_vals,
                                                context=context)
                invoices_group[partner_id_group] = invoice_id

            if not invoice_id in res.values():
                res[picking.id] = invoice_id

            for move_line in picking.move_lines:
                if move_line.state == 'cancel':
                    continue
                if move_line.scrapped:
                    # do no invoice scrapped products
                    continue
                vals = self._prepare_invoice_line(cr,
                                                  uid,
                                                  False,
                                                  picking,
                                                  move_line,
                                                  invoice_id,
                                                  invoice_vals,
                                                  context=context)
                if vals:
                    vals[
                        'product_qty_returned'] = move_line.product_qty_returned  #products that were returned
                    if not self._merge_invoice_lines(cr, uid, vals, context):
                        invoice_line_id = invoice_line_obj.create(
                            cr, uid, vals, context=context)
                        self._invoice_line_hook(cr, uid, move_line,
                                                invoice_line_id)

            invoice_obj.button_compute(cr,
                                       uid, [invoice_id],
                                       context=context,
                                       set_total=(inv_type in ('in_invoice',
                                                               'in_refund')))
            self.write(cr,
                       uid, [picking.id], {
                           'invoice_state': 'invoiced',
                       },
                       context=context)
            self._invoice_hook(cr, uid, picking, invoice_id)

        #raise osv.except_osv(_('Error!'),  _('Safe braking.'))
        #TODO: Moramo spremeniti vrstni red
        #Ker ne poznam id-jev faktur se morap po njih sprehoditi in za vsakega narediti search po linijah sortiranih po imenu
        for invoice_id in res:
            line_ids = invoice_line_obj.search(
                cr, uid, [('invoice_id', '=', res[invoice_id])], order='name')
            sequence = 1
            for line_id in line_ids:
                invoice_line_obj.write(cr, uid, [line_id],
                                       {'sequence': sequence})
                sequence += 1

        self.write(cr,
                   uid,
                   res.keys(), {
                       'invoice_state': 'invoiced',
                   },
                   context=context)
        return res