Exemplo n.º 1
0
    def state_running_set(self, cr, uid, ids, *args):
        # TODO check that all subcampaigns are running
        campaign = self.browse(cr, uid, ids[0])

        if not campaign.activity_ids:
            raise osv.except_osv(_("Error"), _("The campaign cannot be started: there are no activities in it"))

        has_start = False
        has_signal_without_from = False

        for activity in campaign.activity_ids:
            if activity.start:
                has_start = True
            if activity.signal and len(activity.from_ids) == 0:
                has_signal_without_from = True

            if activity.type != 'email':
                continue
            if not activity.email_template_id.from_account:
                raise osv.except_osv(_("Error"), _("The campaign cannot be started: the email account is missing in email activity '%s'")%activity.name)
            if activity.email_template_id.from_account.state != 'approved':
                raise osv.except_osv(_("Error"), _("The campaign cannot be started: the email account is not approved in email activity '%s'")%activity.name)

        if not has_start and not has_signal_without_from:
            raise osv.except_osv(_("Error"), _("The campaign cannot be started: it doesn't have any starting activity (or any activity with a signal and no previous activity)"))

        return self.write(cr, uid, ids, {'state': 'running'})
Exemplo n.º 2
0
    def get_user_related_details(self, cr, uid, user_id):
        res = {}
        emp_obj = self.pool.get('hr.employee')
        emp_id = emp_obj.search(cr, uid, [('user_id', '=', user_id)])
        if not emp_id:
            user_name = self.pool.get('res.users').read(cr, uid, [user_id], ['name'])[0]['name']
            raise osv.except_osv(_('Bad Configuration !'),
                 _('No employee defined for user "%s". You must create one.')% (user_name,))
        emp = self.pool.get('hr.employee').browse(cr, uid, emp_id[0])
        if not emp.product_id:
            raise osv.except_osv(_('Bad Configuration !'),
                 _('No product defined on the related employee.\nFill in the timesheet tab of the employee form.'))

        if not emp.journal_id:
            raise osv.except_osv(_('Bad Configuration !'),
                 _('No journal defined on the related employee.\nFill in the timesheet tab of the employee form.'))

        a = emp.product_id.product_tmpl_id.property_account_expense.id
        if not a:
            a = emp.product_id.categ_id.property_account_expense_categ.id
            if not a:
                raise osv.except_osv(_('Bad Configuration !'),
                        _('No product and product category property account defined on the related employee.\nFill in the timesheet tab of the employee form.'))
        res['product_id'] = emp.product_id.id
        res['journal_id'] = emp.journal_id.id
        res['general_account_id'] = a
        res['product_uom_id'] = emp.product_id.uom_id.id
        return res
	def check_tax_lines(self, cr, uid, inv, compute_taxes, ait_obj):
		company_currency = self.pool['res.company'].browse(cr, uid, inv.company_id.id).currency_id
		if not inv.tax_line:

			for tax in compute_taxes.values():
				ait_obj.create(cr, uid, tax)

		else:
			tax_key = []
			for tax in inv.tax_line:
				key = (tax.tax_code_id.id, tax.base_code_id.id, tax.account_id.id, tax.account_analytic_id.id)
				tax_key.append(key)
				if tax.manual:
					continue
				
				if not key in compute_taxes:
					raise osv.except_osv(_('Warning!'), _('Global taxes defined, but they are not in invoice lines !'))
				base = compute_taxes[key]['base']
				if abs(base - tax.base) > company_currency.rounding:
					raise osv.except_osv(_('Warning!'), _('Tax base different!\nClick on compute to update the tax base.'))

			for key in compute_taxes:
				
				if not key in tax_key:
					raise osv.except_osv(_('Warning!'), _('Taxes are missing!\nClick on compute button.'))
Exemplo n.º 4
0
 def change_sent_customer(self, cr, uid, ids, context=None):
     contract_obj = self.pool.get('account.analytic.account')
     
     schedule_mail_object = self.pool.get('mail.message')
     data_obj = self.pool.get('ir.model.data')
     group_object = self.pool.get('res.groups')
     obj_mail_server = self.pool.get('ir.mail_server')
     mail_server_ids = obj_mail_server.search(cr, uid, [], context=context)
     if not mail_server_ids:
         raise osv.except_osv(_('Mail Error'), _('No mail server found!'))
     mail_server_record = obj_mail_server.browse(cr, uid, mail_server_ids)[0]
     email_from = mail_server_record.smtp_user
     if not email_from:
         raise osv.except_osv(_('Mail Error'), _('No mail found for smtp user!'))
     member_email_list=[]
     for data in self.browse(cr, uid, ids):
         member_email_list.append(data.partner_id.email)
             
         message_body = 'Hello, ' + data.partner_id.name + '<br/><br/>Changes done in your Contract ' + data.project_id.name + '.<br/><br/>Contract Information<br/><br/>Contract ID : ' + tools.ustr(data.project_id.contract_id) + '<br/><br/>Contract Date : ' + tools.ustr(data.project_id.contract_date) + '<br/><br/>Contract Amount : ' + tools.ustr(data.project_id.amount) + '<br/><br/>Deposite Amount : ' + tools.ustr(data.project_id.deposit) + '<br/><br/> Thank You.'
     message_hrmanager  = obj_mail_server.build_email(
         email_from=email_from, 
         email_to=member_email_list, 
         subject='Changes done in your Contract', 
         body=message_body, 
         body_alternative=message_body, 
         email_cc=None, 
         email_bcc=None, 
         attachments=None, 
         references = None, 
         object_id=None, 
         subtype='html', 
         subtype_alternative=None, 
         headers=None)
     self.send_email(cr, uid, message_hrmanager, mail_server_id=mail_server_ids[0], context=context)
     return True
Exemplo n.º 5
0
    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',
            }
Exemplo n.º 6
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'}
Exemplo n.º 7
0
    def _hook_invoice_vals_before_invoice_creation(self, cr, uid, ids, invoice_vals, picking):
        """
        Update journal by an inkind journal if we come from an inkind donation PO.
        Update partner account
        BE CAREFUL : For FO with PICK/PACK/SHIP, the invoice is not created on picking but on shipment
        """
        super(stock_picking, self)._hook_invoice_vals_before_invoice_creation(cr, uid, ids, invoice_vals, picking)
        if not invoice_vals.get('date_invoice',False):
            invoice_vals['date_invoice'] = time.strftime('%Y-%m-%d',time.localtime())
        journal_ids = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'inkind'),
                                                                        ('is_current_instance', '=', True)])
        if picking and picking.purchase_id and picking.purchase_id.order_type == "in_kind":
            if not journal_ids:
                raise osv.except_osv(_('Error'), _('No In-kind donation journal found!'))
            account_id = picking.partner_id and picking.partner_id.donation_payable_account and picking.partner_id.donation_payable_account.id or False
            if not account_id:
                raise osv.except_osv(_('Error'), _('No Donation Payable account for this partner: %s') % (picking.partner_id.name or '',))
            invoice_vals.update({'journal_id': journal_ids[0], 'account_id': account_id, 'is_inkind_donation': True,})
        if picking and picking.partner_id and picking.partner_id.partner_type == 'intermission':
            invoice_vals.update({'is_intermission': True})

        if picking and picking.type == 'in' and picking.partner_id and (not picking.partner_id.property_account_payable or not picking.partner_id.property_account_receivable):
            raise osv.except_osv(_('Error'), _('Partner of this incoming shipment has no account set. Please set appropriate accounts (receivable and payable) in order to process this IN'))

        return invoice_vals
Exemplo n.º 8
0
    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 {}
Exemplo n.º 9
0
 def check_tax_lines(self, cr, uid, inv, compute_taxes, ait_obj):
     avatax_config_obj = self.pool.get('avalara.salestax')
     avatax_config = avatax_config_obj._get_avatax_config_company(cr, uid)
     partner_obj = self.pool.get('res.partner')
     res_obj = partner_obj.browse(cr, uid, inv.partner_id.id)
     
     if avatax_config and not avatax_config.disable_tax_calculation:
         if not inv.tax_line:
             for tax in compute_taxes.values():
                 ait_obj.create(cr, uid, tax)
         else:
             tax_key = []
             for tax in inv.tax_line:
                 if tax.manual:
                     continue
                 key = (tax.tax_code_id.id, tax.base_code_id.id, tax.account_id.id)
                 tax_key.append(key)
                 if not key in compute_taxes:
                     raise osv.except_osv(_('Warning!'), _('Global taxes defined, but they are not in invoice lines !'))
                 base = compute_taxes[key]['base']
                 if abs(base - tax.base) > inv.company_id.currency_id.rounding:
                     raise osv.except_osv(_('Warning!'), _('Tax base different!\nClick on compute to update the tax base.'))
             for key in compute_taxes:
                 if not key in tax_key:
                     raise osv.except_osv(_('Warning!'), _('Taxes are missing!\nClick on compute button.'))
         
             for tax in inv.tax_line:
                 key = (tax.tax_code_id.id, tax.base_code_id.id, tax.account_id.id)
                 if abs(compute_taxes[key]['amount'] - tax.amount) > inv.company_id.currency_id.rounding:
                     raise osv.except_osv(_('Warning !'), _('Tax amount different !\nClick on compute to update tax base'))
     else:
         super(account_invoice, self).check_tax_lines(cr, uid, inv, compute_taxes, ait_obj)
    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}
 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
Exemplo n.º 12
0
    def _suma_total(self, cr, r, context=None):

        # variable con el valor total a pagar
        total_pago = 0.0
        #analizo las lineas de cobro que tengo
        for r_l in r.detalle_pago_ids:
            
            #verifico si se va o no a cancelar un valor
            if r_l.cancelado:
                # se esta cancelando este haber, se suma completo lo que falta abonar
                # ademas se suma el interes acumulado por mora
                if r_l.interes_mora < 0:
                    # no se puede calcular, el interes no puede ser negativo
                    raise osv.except_osv(_('Error !'), _('Existe un valor negativo como valor de interes!!'))
                    
                total_pago = total_pago + float(r_l.valor_interes - r_l.valor_abonado) + r_l.interes_mora
                
            else:
                # caso contrario, debe sumarse el valor asignado en el pago
                # se verifica que el valor sea mayor a 0
                if r_l.valor_pago >= 0.0:
                    
                    if r_l.interes_mora < 0:
                        # no se puede calcular, el interes no puede ser negativo
                        raise osv.except_osv(_('Error !'), _('Existe un valor negativo como valor de interes!!'))

                    total_pago = total_pago + r_l.valor_pago#  + r_l.interes_mora
                     
                else:
                    # no se puede calcular, hay un valor negativo
                    raise osv.except_osv(_('Error !'), _('Existe un valor negativo como pago!!'))
            
        return total_pago
Exemplo n.º 13
0
 def unlink(self, cr, uid, ids, context=None):
     for sale_product_id in self.browse(cr, uid, ids, context=context):
         if sale_product_id.state != 'draft': 
             raise osv.except_osv(_('Error'),_("Only MFG ID(%s) with Draft state can be delete!"%(sale_product_id.name,)))
         elif sale_product_id.project_ids or sale_product_id.mrp_prod_ids:
             raise osv.except_osv(_('Error'),_("This ID '%s' already have related projects or manufacture order, can not be delete!"%(sale_product_id.name,)))
     return super(sale_product,self).unlink(cr, uid, ids, context=context)
Exemplo n.º 14
0
    def _connect_to_asterisk(self, cr, uid, context=None):
        '''
        Open the connection to the asterisk manager
        Returns an instance of the Asterisk Manager

        '''
        user = self.pool.get('res.users').browse(cr, uid, uid, context=context)

        # Note : if I write 'Error' without ' :', it won't get translated...
        # I don't understand why !

        ast_server = self._get_asterisk_server_from_user(cr, uid, user, context=context)
        # We check if the current user has a chan type
        if not user.asterisk_chan_type:
            raise osv.except_osv(_('Error :'), _('No channel type configured for the current user.'))

        # We check if the current user has an internal number
        if not user.resource:
            raise osv.except_osv(_('Error :'), _('No resource name configured for the current user'))


        _logger.debug("User's phone : %s/%s" % (user.asterisk_chan_type, user.resource))
        _logger.debug("Asterisk server = %s:%d" % (ast_server.ip_address, ast_server.port))

        # Connect to the Asterisk Manager Interface
        try:
            ast_manager = Manager.Manager((ast_server.ip_address, ast_server.port), ast_server.login, ast_server.password)
        except Exception, e:
            _logger.error("Error in the Originate request to Asterisk server %s" % ast_server.ip_address)
            _logger.error("Here is the detail of the error : '%s'" % unicode(e))
            raise osv.except_osv(_('Error :'), _("Problem in the request from OpenERP to Asterisk. Here is the detail of the error: '%s'" % unicode(e)))
            return False
Exemplo n.º 15
0
    def _check_validity(self, cr, uid, ids):
        for server in self.browse(cr, uid, ids):
            country_prefix = ('Country prefix', server.country_prefix)
            international_prefix = ('International prefix', server.international_prefix)
            out_prefix = ('Out prefix', server.out_prefix)
            national_prefix = ('National prefix', server.national_prefix)
            dialplan_context = ('Dialplan context', server.context)
            alert_info = ('Alert-Info SIP header', server.alert_info)
            login = ('AMI login', server.login)
            password = ('AMI password', server.password)

            for digit_prefix in [country_prefix, international_prefix, out_prefix, national_prefix]:
                if digit_prefix[1] and not digit_prefix[1].isdigit():
                    raise osv.except_osv(_('Error :'), _("Only use digits for the '%s' on the Asterisk server '%s'" % (digit_prefix[0], server.name)))
            if server.wait_time < 1 or server.wait_time > 120:
                raise osv.except_osv(_('Error :'), _("You should set a 'Wait time' value between 1 and 120 seconds for the Asterisk server '%s'" % server.name))
            if server.extension_priority < 1:
                raise osv.except_osv(_('Error :'), _("The 'extension priority' must be a positive value for the Asterisk server '%s'" % server.name))
            if server.port > 65535 or server.port < 1:
                raise osv.except_osv(_('Error :'), _("You should set a TCP port between 1 and 65535 for the Asterik server '%s'" % server.name))
            for check_string in [dialplan_context, alert_info, login, password]:
                if check_string[1]:
                    try:
                        string = check_string[1].encode('ascii')
                    except UnicodeEncodeError:
                        raise osv.except_osv(_('Error :'), _("The '%s' should only have ASCII caracters for the Asterisk server '%s'" % (check_string[0], server.name)))
        return True
Exemplo n.º 16
0
    def change_currency(self, cr, uid, ids, context=None):
        obj_inv = self.pool.get('account.invoice')
        obj_inv_line = self.pool.get('account.invoice.line')
        obj_currency = self.pool.get('res.currency')
        if context is None:
            context = {}
        data = self.browse(cr, uid, ids, context=context)[0]
        new_currency = data.currency_id.id

        invoice = obj_inv.browse(cr, uid, context['active_id'], context=context)
        if invoice.currency_id.id == new_currency:
            return {}
        rate = obj_currency.browse(cr, uid, new_currency, context=context).rate
        for line in invoice.invoice_line:
            new_price = 0
            if invoice.company_id.currency_id.id == invoice.currency_id.id:
                new_price = line.price_unit * rate
                if new_price <= 0:
                    raise osv.except_osv(_('Error'), _('New currency is not confirured properly !'))

            if invoice.company_id.currency_id.id != invoice.currency_id.id and invoice.company_id.currency_id.id == new_currency:
                old_rate = invoice.currency_id.rate
                if old_rate <= 0:
                    raise osv.except_osv(_('Error'), _('Currnt currency is not confirured properly !'))
                new_price = line.price_unit / old_rate

            if invoice.company_id.currency_id.id != invoice.currency_id.id and invoice.company_id.currency_id.id != new_currency:
                old_rate = invoice.currency_id.rate
                if old_rate <= 0:
                    raise osv.except_osv(_('Error'), _('Current currency is not confirured properly !'))
                new_price = (line.price_unit / old_rate ) * rate
            obj_inv_line.write(cr, uid, [line.id], {'price_unit': new_price})
        obj_inv.write(cr, uid, [invoice.id], {'currency_id': new_currency}, context=context)
        return {'type': 'ir.actions.act_window_close'}
Exemplo n.º 17
0
 def _check_key(self, cr, uid, ids):
     """Check the RIB key"""
     for bank_acc in self.browse(cr, uid, ids):
         # Ignore the accounts of type other than rib
         if bank_acc.state != 'rib':
             continue
         # Fail if the needed values are empty of too short 
         if (not bank_acc.bank_code
         or len(bank_acc.bank_code) != 5
         or not bank_acc.office or len(bank_acc.office) != 5
         or not bank_acc.rib_acc_number or len(bank_acc.rib_acc_number) != 11
         or not bank_acc.key or len(bank_acc.key) != 2):
             return False
         # Get the rib data (without the key)
         rib = "%s%s%s" % (bank_acc.bank_code, bank_acc.office, bank_acc.rib_acc_number)
         # Translate letters into numbers according to a specific table
         #    (notice how s -> 2)
         table = dict((ord(a), b) for a, b in zip(
             u'abcdefghijklmnopqrstuvwxyz', u'12345678912345678923456789'))
         rib = rib.lower().translate(table)
         # compute the key	
         key = 97 - (100 * int(rib)) % 97
         if int(bank_acc.key) != key:
             raise osv.except_osv(_('Error!'),
                 _("The RIB key %s does not correspond to the other codes: %s %s %s.") % \
                     (bank_acc.key, bank_acc.bank_code, bank_acc.office, bank_acc.rib_acc_number) )
         if bank_acc.acc_number:
             if not self.is_iban_valid(cr, uid, bank_acc.acc_number):
                 raise osv.except_osv(_('Error!'), _("The IBAN %s is not valid.") % bank_acc.acc_number)
     return True
Exemplo n.º 18
0
 def create_analytic_lines(self, cr, uid, ids, context=None):
     """
     Create analytic line for given commitment voucher.
     """
     # Some verifications
     if not context:
         context = {}
     if isinstance(ids, (int, long)):
         ids = [ids]
     # Browse commitments
     for c in self.browse(cr, uid, ids, context=context):
         for cl in c.line_ids:
             # Continue if we come from yaml tests
             if c.from_yml_test or cl.from_yml_test:
                 continue
             # Verify that analytic distribution is present
             if cl.analytic_distribution_state != 'valid':
                 raise osv.except_osv(_('Error'), _('Analytic distribution is not valid for account "%s %s".') %
                     (cl.account_id and cl.account_id.code, cl.account_id and cl.account_id.name))
             # Take analytic distribution either from line or from commitment voucher
             distrib_id = cl.analytic_distribution_id and cl.analytic_distribution_id.id or c.analytic_distribution_id and c.analytic_distribution_id.id or False
             if not distrib_id:
                 raise osv.except_osv(_('Error'), _('No analytic distribution found!'))
             # Search if analytic lines exists for this commitment voucher line
             al_ids = self.pool.get('account.analytic.line').search(cr, uid, [('commitment_line_id', '=', cl.id)], context=context)
             if not al_ids:
                 # Create engagement journal lines
                 self.pool.get('analytic.distribution').create_analytic_lines(cr, uid, [distrib_id], c.name, c.date,
                     cl.amount, c.journal_id and c.journal_id.id, c.currency_id and c.currency_id.id, c.date or False,
                     (c.purchase_id and c.purchase_id.name) or c.name or False, c.date, cl.account_id and cl.account_id.id or False, False, False,
                     cl.id, context=context)
     return True
Exemplo n.º 19
0
 def create(self, cr, uid, vals, context=None):
     """
     Verify that given account_id (in vals) is not 'view'.
     Update initial amount with those given by 'amount' field.
     Verify amount sign.
     """
     # Some verifications
     if not context:
         context = {}
     # Change 'first' value to False (In order view correctly displayed)
     if not 'first' in vals:
         vals.update({'first': False})
     # Copy initial_amount to amount
     vals.update({'amount': vals.get('initial_amount', 0.0)})
     if 'account_id' in vals:
         account_id = vals.get('account_id')
         account = self.pool.get('account.account').browse(cr, uid, [account_id], context=context)[0]
         if account.type in ['view']:
             raise osv.except_osv(_('Error'), _("You cannot create a commitment voucher line on a 'view' account type!"))
     # Verify amount validity
     if 'amount' in vals and vals.get('amount', 0.0) < 0.0:
         raise osv.except_osv(_('Warning'), _('Total amount should be equal or superior to 0!'))
     if 'initial_amount' in vals and vals.get('initial_amount', 0.0) <= 0.0:
         raise osv.except_osv(_('Warning'), _('Initial Amount should be superior to 0!'))
     if 'initial_amount' in vals and 'amount' in vals:
         if vals.get('initial_amount') < vals.get('amount'):
             raise osv.except_osv(_('Warning'), _('Initial Amount should be superior to Amount Left'))
     res = super(account_commitment_line, self).create(cr, uid, vals, context={})
     if res:
         for cl in self.browse(cr, uid, [res], context=context):
             if 'amount' in vals and cl.commit_id and cl.commit_id.state and cl.commit_id.state == 'open':
                 self.update_analytic_lines(cr, uid, [cl.id], vals.get('amount'), context=context)
     return res
Exemplo n.º 20
0
 def write_ciril_engage(self, cr, uid, ids, context=None):
     ret = ''
     template = template_ciril_txt_file_engagement()
     mail_template_obj = self.pool.get('email.template')
     mail_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'openstc_achat_stock','openstc_email_template_purchase_engaged')[1]
     for po in self.browse(cr, uid, ids ,context=context):
         ret = template.create_file(po)
         #write file on remote CIRIL server
         base_path = '%s/%s/%s' % (os.getenv('HOME', '.'),config.options.get('openerp_ciril_repository',''),cr.dbname)
         file_path = '%s/todo/%s.txt' % (base_path,po.name.replace('/','_'))
         ret_file = open(file_path, 'w')
         ret_file.write(ret.encode('utf-8'))
         ret_file.close()
         #perform push of the created file
         try:
             ret = urllib2.urlopen('http://%s:%s/%s/%s' % (config.options.get('push_service_host','localhost'),
                                                       config.options.get('push_service_port','44001'),
                                                       config.options.get('push_service_base_url','push_service'),
                                                       cr.dbname))
         except URLError as e:
             raise osv.except_osv(_('Error'), _('Internal server error, please contact your supplier.\n Technical error : "%s"') % e.reason)
         if ret.getcode() != 200:
             raise osv.except_osv(_('Error'), _('Internal server error, please contact your supplier.\n Technical error : "%s"') % ret.read())
         shutil.copy(file_path, base_path + '/archive')
         os.remove(file_path)
         #indicates that engage is sent by buyer (to the accounting department)
         now = datetime.now().strftime('%Y-%m-%d')
         po.write({'validation':'purchase_engaged','date_engage_sent':now})
         #@todo: send mail to accounting department to notify that a new file can be imported to their 3rd part accounting software
         mail_template_obj.send_mail(cr, uid, mail_id, po.id, force_send=True, context=context)
     return {'type':'ir.actions.act_window_close'}
Exemplo n.º 21
0
 def write(self, cr, uid, ids, vals, context=None):
     """
     Update analytic lines date if date in vals for validated commitment voucher.
     """
     # Some verifications
     if not context:
         context = {}
     if isinstance(ids, (int, long)):
         ids = [ids]
     # Browse elements if 'date' in vals
     if vals.get('date', False):
         date = vals.get('date')
         period_ids = get_period_from_date(self, cr, uid, date, context=context)
         vals.update({'period_id': period_ids and period_ids[0]})
         for c in self.browse(cr, uid, ids, context=context):
             if c.state == 'open':
                 for cl in c.line_ids:
                     # Verify that date is compatible with all analytic account from distribution
                     if cl.analytic_distribution_id:
                         distrib = cl.analytic_distribution_id
                     elif cl.commit_id and cl.commit_id.analytic_distribution_id:
                         distrib = cl.commit_id.analytic_distribution_id
                     else:
                         raise osv.except_osv(_('Warning'), _('No analytic distribution found for %s %s') % (cl.account_id.code, cl.initial_amount))
                     for distrib_lines in [distrib.cost_center_lines, distrib.funding_pool_lines, distrib.free_1_lines, distrib.free_2_lines]:
                         for distrib_line in distrib_lines:
                             if (distrib_line.analytic_id.date_start and date < distrib_line.analytic_id.date_start) or (distrib_line.analytic_id.date and date > distrib_line.analytic_id.date):
                                 raise osv.except_osv(_('Error'), _('The analytic account %s is not active for given date.') % (distrib_line.analytic_id.name,))
                     self.pool.get('account.analytic.line').write(cr, uid, [x.id for x in cl.analytic_lines], {'date': date, 'source_date': date, 'document_date': date,}, context=context)
     # Default behaviour
     res = super(account_commitment, self).write(cr, uid, ids, vals, context=context)
     return res
Exemplo n.º 22
0
 def wkf_confirm_order(self, cr, uid, ids, context=None):
     print 'confirm'
     todo = []
     wf_service = netsvc.LocalService("workflow")
     
     for po in self.browse(cr, uid, ids, context=context):
         if not po.order_line:
             raise osv.except_osv(_('Error !'),_('You can not confirm purchase order without Purchase Order Lines.'))
         for line in po.order_line:
             if line.state=='draft':
                 todo.append(line.id)
         message = _("Purchase order '%s' is confirmed.") % (po.name,)
         self.log(cr, uid, po.id, message)
     self.pool.get('purchase.order.line').action_confirm(cr, uid, todo, context)
     if self.pool.get('ingram_config').search(cr,uid,[('xml_active','=','True'),]):
         idsearch=self.pool.get('ingram_config').search(cr,uid,[('xml_active','=','True'),])
         config=self.pool.get('ingram_config').read(cr,uid,idsearch,['supplier_id'])
         id=config[0]['supplier_id']
         if po.partner_id.id == id[0] and po.skipxml==False:
             result= self.send_order(cr,uid,ids,context)
             for i in ids:
                 if result['warning']['message']=="Successful Order":
                     self.write(cr, uid, [i], {'state' : 'confirmed', 'validator' : uid})
                 elif result['warning']['message']=="Miss order":
                     self.write(cr, uid, [i], {'state' : 'draft', 'validator' : False, 'sendorder': False,})
                 else:
                     self.write(cr, uid, [i], {'state' : 'draft', 'validator' : False, 'sendorder': False,})
                     raise osv.except_osv(_('Error'),_(result))
         else:
             for id in ids:
                 self.write(cr, uid, [id], {'state' : 'confirmed', 'validator' : uid})
     return True
    def action_close(self, cr, uid, ids, context=None):
        # All establishment lines must be done or canceled
        line_ids = set()
        for o in self.browse(cr, uid, ids, context=context):
            topup_ids = set(map(lambda x: x.id, o.top_ups))
            expense_ids = set(map(lambda x: x.id, o.expenses))
            disbursement_ids = set(map(lambda x: x.id, o.disbursements))
            line_ids = line_ids.union(topup_ids).union(expense_ids).union(disbursement_ids)

        line_pool = self.pool.get("cash.advance.establishment.line")
        for l in line_pool.browse(cr, uid, list(line_ids), context=context):
            if l.state == "pending" or l.state == "draft":
                raise osv.except_osv(
                    _("Error !"), _('%s %s "%s" prevents closing !' % (l.state.capitalize(), l.line_type, l.name))
                )

        # Outstanding balance must be zero
        currency_pool = self.pool.get("res.currency")
        if filter(
            lambda e: not currency_pool.is_zero(cr, uid, e.currency, e.outstanding),
            self.browse(cr, uid, ids, context=context),
        ):
            raise osv.except_osv(_("Error !"), _("Outstanding balance is not zero !"))

        self.write(cr, uid, ids, {"state": "done"}, context=context)
Exemplo n.º 24
0
    def action_revert_done(self, cr, uid, ids, context=None):
        if not len(ids):
            return False
        for picking in self.browse(cr, uid, ids, context):
            if self.has_invoices(cr, uid, picking, context):
                raise osv.except_osv(_('Error'),
                    _('Picking %s has invoices. Remove them first')
                    % (picking.name,))
            if self.has_valuation_moves(cr, uid, picking,context):
                raise osv.except_osv(_('Error'),
                    _('Picking %s has valuation moves. Remove them first')
                    % (picking.name,))
            if self.has_stock_matching(cr, uid, picking,context):
                raise osv.except_osv(_('Error'),
                    _('Picking %s has stocking out moves generated, can not reopen it.')
                    % (picking.name,))                
            for line in picking.move_lines:
                line.write({'state': 'draft'})                            
            self.write(cr, uid, [picking.id], {'state': 'draft'})
            if picking.invoice_state == 'invoiced':
                self.write(cr, uid, [picking.id], {'invoice_state': '2binvoiced'})
            wf_service = netsvc.LocalService("workflow")
            # Deleting the existing instance of workflow
            wf_service.trg_delete(uid, 'stock.picking', picking.id, cr)
            wf_service.trg_create(uid, 'stock.picking', picking.id, cr)
#        for (id,name) in self.name_get(cr, uid, ids):
#            message = _("The stock picking '%s' has been set in draft state.") %(name,)
#            self.log(cr, uid, id, message)
            #johnw,  09/26/2014, set po's shipped status to false
            if picking.purchase_id and picking.purchase_id.shipped:
                self.pool.get('purchase.order').write(cr, uid, [picking.purchase_id.id], {'shipped':False}, context=context)
                
        return True
    def create(self, cr, uid, vals, context=None):
        journal_obj = self.pool.get('account.journal')
        ana_plan_instance_obj = self.pool.get('account.analytic.plan.instance')
        acct_anal_acct = self.pool.get('account.analytic.account')
        acct_anal_plan_line_obj = self.pool.get('account.analytic.plan.line')
        if context and 'journal_id' in context:
            journal = journal_obj.browse(cr, uid, context['journal_id'], context=context)

            pids = ana_plan_instance_obj.search(cr, uid, [('name','=',vals['name']), ('code','=',vals['code']), ('plan_id','<>',False)], context=context)
            if pids:
                raise osv.except_osv(_('Error'), _('A model having this name and code already exists !'))

            res = acct_anal_plan_line_obj.search(cr, uid, [('plan_id','=',journal.plan_id.id)], context=context)
            for i in res:
                total_per_plan = 0
                item = acct_anal_plan_line_obj.browse(cr, uid, i, context=context)
                temp_list = ['account1_ids','account2_ids','account3_ids','account4_ids','account5_ids','account6_ids']
                for l in temp_list:
                    if vals.has_key(l):
                        for tempo in vals[l]:
                            if acct_anal_acct.search(cr, uid, [('parent_id', 'child_of', [item.root_analytic_id.id]), ('id', '=', tempo[2]['analytic_account_id'])], context=context):
                                total_per_plan += tempo[2]['rate']
                if total_per_plan < item.min_required or total_per_plan > item.max_required:
                    raise osv.except_osv(_('Value Error'),_('The Total Should be Between %s and %s') % (str(item.min_required), str(item.max_required)))

        return super(account_analytic_plan_instance, self).create(cr, uid, vals, context=context)
Exemplo n.º 26
0
	def action_cancel(self, cr, uid, ids, context=None):
		wf_service = netsvc.LocalService("workflow")
		for purchase in self.browse(cr, uid, ids, context=context):
			cek=self.pool.get('detail.order.line').search(cr,uid,[('order_line_id', '=' ,ids)])
			order_line =self.pool.get('detail.order.line').browse(cr,uid,cek)
			for val in order_line:
				# ================== Update Detail PB menjadi Confirm ===================
				self.pool.get('detail.pb').write(cr, uid, [val.detail_pb_id], {'state':'onproses'})
				
				# ================== Cek Qty Detail PB =================================
				Qty_PB=self.pool.get('detail.pb').search(cr,uid,[('id', '=' ,val.detail_pb_id)])
				QtyDetail = self.pool.get('detail.pb').browse(cr,uid, Qty_PB[0])
				self.pool.get('detail.pb').write(cr, uid, [val.detail_pb_id], {'qty_available':QtyDetail.qty_available+val.qty})

			for pick in purchase.picking_ids:
				if pick.state not in ('draft','cancel'):
					raise osv.except_osv(
						_('Unable to cancel this purchase order.'),
						_('First cancel all receptions related to this purchase order.'))
			for pick in purchase.picking_ids:
				wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_cancel', cr)
			for inv in purchase.invoice_ids:
				if inv and inv.state not in ('cancel','draft'):
					raise osv.except_osv(
						_('Unable to cancel this purchase order.'),
						_('You must first cancel all receptions related to this purchase order.'))
				if inv:
					wf_service.trg_validate(uid, 'account.invoice', inv.id, 'invoice_cancel', cr)
					
				#self.write(cr,uid,ids,{'state':'approved'})
				self.write(cr,uid,ids,{'state':'cancel'})
				
			for (id, name) in self.name_get(cr, uid, ids):
				wf_service.trg_validate(uid, 'purchase.order', id, 'purchase_cancel', cr)
		return True
    def view_init(self, cr, uid, fields, context=None):
        """
        This function checks for precondition before wizard executes
        @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
        """
        idea_obj = self.pool.get('idea.idea')
        vote_obj = self.pool.get('idea.vote')

        for idea in idea_obj.browse(cr, uid, context.get('active_ids', []), context=context):

            for active_id in context.get('active_ids'):

                vote_ids = vote_obj.search(cr, uid, [('user_id', '=', uid), ('idea_id', '=', active_id)])
                vote_obj_id = vote_obj.browse(cr, uid, vote_ids)
                count = 0
                for vote in vote_obj_id:
                    count += 1

                user_limit = idea.vote_limit
                if  count >= user_limit:
                   raise osv.except_osv(_('Warning !'),_("You can not give Vote for this idea more than %s times") % (user_limit))

            if idea.state != 'open':
                raise osv.except_osv(_('Warning !'), _('Idea must be in \
\'Open\' state before vote for that idea.'))
        return False
Exemplo n.º 28
0
    def envoieCommande(self,cr,uid,ids,context):
        idPo=self.pool.get('purchase.order.line').search(cr,uid,[('order_id','=',ids[0]),])
        requete=self.requeteCode(cr,uid,idPo,ids[0])
        try:
            idsearch=self.pool.get('ingram_config').search(cr,uid,[('xml_active','=','True'),])
            config=self.pool.get('ingram_config').read(cr,uid,idsearch,['xml_address'])#
            ip=str(config[0]['xml_address'])
            if ip :
                ip=ip.split('/')
                chm=""
                for i in range(len(ip)):
                    if i>0:
                        chm+="/"+ip[i]
                conn = httplib.HTTPSConnection(ip[0],443)#environment prod
                if sys.version >= '2.7':
                    sock = socket.create_connection((conn.host, conn.port), conn.timeout, conn.source_address)
                else:
                    sock = socket.create_connection((conn.host, conn.port), conn.timeout)
                conn.sock = ssl.wrap_socket(sock, conn.key_file, conn.cert_file, ssl_version=ssl.PROTOCOL_TLSv1)
                conn.request("POST",chm,requete ) 
        except:
            raise osv.except_osv(_('Warning!'),_('Connection failed'))
        response = conn.getresponse()
        if response.status == 200:
            data = response.read()
            _logger.info(data) 
            conn.close()

            return  self.traitement(cr,uid,ids,data)
        else:
            raise osv.except_osv(_('Information!'),_('Connection failed'))
        
        return  self.traitement(cr,uid,ids,data)
    def select_existing_sequence(self, cr, uid, ids, context=None):
        if len(context.get('active_ids', [])) > 1:
            raise osv.except_osv('Warning', 'Only one taxform can be processed at a time!')
        _taxform_id = context.get('active_id', False)
        if not _taxform_id:
            raise osv.except_osv('Warning', 'No taxform is selected!')

        data = self.pool.get('account.taxform.select_existing_sequence').browse(cr, uid, ids[0], context=context)

        _reusable = data.reusable_id
        _vals = {
            'taxform_id': _reusable.taxform_sequence,
            'trx_code': data.trx_code,
            'branch_code': data.branch_code,
        }
        self.pool.get('account.taxform').write(cr, uid, _taxform_id, _vals, context=context)
        _reusable.write({'reusable': False}, context=context)

        rv = {
            'name': _("Taxform"),
            'res_id': _taxform_id,
            'view_mode': 'form',
            'view_type': 'form',
            'res_model': 'account.taxform',
            'view_id': False,
            'type': 'ir.actions.act_window',
            'nodestroy': True,
            'target': 'current',
            'domain': '[]',
            'context': context
        }

        return rv
Exemplo n.º 30
0
    def save_product (self,cr,uid,product_id,customer_id,qty_product,date_order):
        magento_connect = self.pool.get('sneldev.magento')

        #First check if the product don't exist in the stadistic
        list_stadistic = self.pool.get('magento.stadistic').search(cr, uid, 
                                                                   [('product_ids', '=', product_id),
                                                                    ('customer_ids','=',customer_id),
                                                                    ('date_out_of_stock','=',date_order)])
        if len(list_stadistic) == 0:                
            #Import the product. If exist, update the info
            result = magento_connect.import_products(cr, uid,product_id)
            
            if result == 0:
                #search the product in openerp and save in the magento_stadistic object
                product_ids = []
                product_ids_search = self.pool.get('product.product').search(cr, uid, [('magento_id', '=', product_id)])     
                product_ids_browse = self.pool.get('product.product').browse(cr, uid, product_ids_search)
                for product in product_ids_browse:
                    if product.id not in product_ids:
                        product_ids.append(product.id)
                
                #Search the customer, if exist, update info and        
                magento_connect.import_customers(cr,uid,customer_id)
                customer_ids = []
                customer_ids_search = self.pool.get('res.partner').search(cr,uid,[('magento_id','=',customer_id)])
                customer_ids_browse = self.pool.get('res.partner').browse(cr,uid,customer_ids_search)
                for customer in customer_ids_browse:
                    if customer.id not in customer_ids:
                        customer_ids.append(customer.id)
                
                indice = 0
                
                day = int(date_order[0:2])
                month = int(date_order[3:5])
                year = int(date_order[6:11])
                
                hour = int(date_order[11:13])
                minute = int(date_order[14:16])
                second = int(date_order[17:19])
                
                date_object = datetime.datetime(year,month,day,hour,minute,second)
                                                        
                for p in product_ids:                
                    product_of_stock = {
                        'product_ids':product_ids[indice],
                        'date_out_of_stock': date_object,
                        'customer_ids':customer_ids[0],
                        'qty_product':qty_product,
                    } 
                    indice + 1                 
                    self.pool.get('magento.stadistic').create(cr, uid, product_of_stock)
                return 0
                    
            else:
                raise osv.except_osv(_('Error !'), _('Cannot get product, check Magento web user config'))
                return -1
                    
        else:
            raise osv.except_osv(_('Error !'), _('Already exist the stadistic'))
            return -1
Exemplo n.º 31
0
 def copy(self, cr, uid, ids, *args, **argv):
     raise osv.except_osv(_('Error !'),
                          _('You cannot duplicate a timesheet !'))
Exemplo n.º 32
0
    def action_confirm(self, cr, uid, ids, context=None):
        """
        Called when the user clicks the confirm button.
        """
        if context is None:
            context = {}
        #
        # Make sure the lang is defined on the context
        #
        user = self.pool.get('res.users').browse(cr, uid, uid, context)
        context['lang'] = context.get('lang') or user.lang

        for fyc in self.browse(cr, uid, ids, context):
            #
            # Require the L&P, closing, and opening moves to exist (NL&P is optional)
            #
            if not fyc.loss_and_profit_move_id:
                raise osv.except_osv(
                    _("Not all the operations have been performed!"),
                    _("The Loss & Profit move is required"))
            if not fyc.closing_move_id:
                raise osv.except_osv(
                    _("Not all the operations have been performed!"),
                    _("The Closing move is required"))
            if not fyc.opening_move_id:
                raise osv.except_osv(
                    _("Not all the operations have been performed!"),
                    _("The Opening move is required"))
            ''' needed ?
            
            #
            # Calculate the moves to check
            #
            moves = []
            moves.append(fyc.loss_and_profit_move_id)
            if fyc.net_loss_and_profit_move_id:
                moves.append(fyc.net_loss_and_profit_move_id)
            moves.append(fyc.closing_move_id)
            moves.append(fyc.opening_move_id)

            #
            # Check and reconcile each of the moves
            #
            for move in moves:
                netsvc.Logger().notifyChannel('fyc', netsvc.LOG_DEBUG, "Checking %s" % move.ref)
                #
                # Check if it has been confirmed
                #
                if move.state == 'draft':
                    raise osv.except_osv(_("Some moves are in draft state!"), _("You have to review and confirm each of the moves before continuing"))
                #
                # Check the balance
                #
                amount = 0
                for line in move.line_id:
                    amount += (line.debit - line.credit)
                if abs(amount) > 0.5 * 10 ** -int(self.pool.get('decimal.precision').precision_get(cr, uid, 'Account')):
                    raise osv.except_osv(_("Some moves are unbalanced!"), _("All the moves should be balanced before continuing"))

                #
                # Reconcile the move
                #
                # Note: We will reconcile all the lines, even the 'not reconcile' ones,
                #       to prevent future problems (the user may change the
                #       reconcile option of an account in the future)
                #
                netsvc.Logger().notifyChannel('fyc', netsvc.LOG_DEBUG, "Reconcile %s" % move.ref)
                tmp_context = context.copy()
                tmp_context['fy_closing'] = True # Fiscal year closing = reconcile everything
                line_ids = [line.id for line in move.line_id]
                self.pool.get('account.move.line').reconcile(cr, uid, line_ids, context=tmp_context)

            #
            # Close the fiscal year and it's periods
            #
            # Note: We can not just do a write, cause it would raise a
            #       "You can not modify/delete a journal with entries for this period!"
            #       so we have to do it on SQL level :(
            #       This is based on the "account.fiscalyear.close.state" wizard.
            #
            netsvc.Logger().notifyChannel('fyc', netsvc.LOG_DEBUG, "Closing fiscal year")
            query = """
                    UPDATE account_journal_period
                    SET state = 'done'
                    WHERE period_id IN (SELECT id FROM account_period WHERE fiscalyear_id = %d)
                    """
            cr.execute(query % fyc.closing_fiscalyear_id.id)
            query = """
                    UPDATE account_period
                    SET state = 'done'
                    WHERE fiscalyear_id = %d
                    """
            cr.execute(query % fyc.closing_fiscalyear_id.id)
            query = """
                    UPDATE account_fiscalyear
                    SET state = 'done'
                    WHERE id = %d
                    """
            cr.execute(query % fyc.closing_fiscalyear_id.id)
            
            '''

        # Done
        self.write(cr, uid, ids, {'state': 'done'})
        return True
Exemplo n.º 33
0
    def action_draft(self, cr, uid, ids, context=None):
        """
        Called when the user clicks the confirm button.
        """
        if context is None:
            context = {}
        #
        # Make sure the lang is defined on the context
        #
        user = self.pool.get('res.users').browse(cr, uid, uid, context)
        context['lang'] = context.get('lang') or user.lang

        for fyc in self.browse(cr, uid, ids, context):
            #
            # Check for duplicated entries
            #
            fyc_ids = self.search(cr, uid, [('name', '=', fyc.name)])
            if len(fyc_ids) > 1:
                raise osv.except_osv(
                    _('Error'),
                    _('There is already a fiscal year closing with this name.')
                )

            assert fyc.closing_fiscalyear_id and fyc.closing_fiscalyear_id.id
            fyc_ids = self.search(
                cr, uid,
                [('closing_fiscalyear_id', '=', fyc.closing_fiscalyear_id.id)])
            if len(fyc_ids) > 1:
                raise osv.except_osv(
                    _('Error'),
                    _('There is already a fiscal year closing for the fiscal year to close.'
                      ))

            assert fyc.opening_fiscalyear_id and fyc.opening_fiscalyear_id.id
            fyc_ids = self.search(
                cr, uid,
                [('opening_fiscalyear_id', '=', fyc.opening_fiscalyear_id.id)])
            if len(fyc_ids) > 1:
                raise osv.except_osv(
                    _('Error'),
                    _('There is already a fiscal year closing for the fiscal year to open.'
                      ))

            #
            # Check whether the default values of the fyc object have to be computed
            # or they have already been computed (restarted workflow)
            #
            if fyc.c_account_mapping_ids:
                # Fyc wizard reverted to 'new' after canceled

                self.write(cr, uid, [fyc.id], {'state': 'draft'})
            else:
                # New fyc wizard object

                vals = {
                    #
                    # Perform all the operations by default
                    #
                    'create_loss_and_profit': True,
                    'create_net_loss_and_profit': False,
                    'create_closing': True,
                    'create_opening': True,
                    'check_invalid_period_moves': True,
                    'check_draft_moves': True,
                    'check_unbalanced_moves': True,

                    #
                    # L&P options
                    #
                    'lp_description': _("Loss & Profit"),
                    'lp_journal_id':
                    self._get_journal_id(cr, uid, fyc, context),
                    'lp_period_id':
                    self._get_lp_period_id(cr, uid, fyc, context),
                    'lp_date': fyc.closing_fiscalyear_id.date_stop,
                    #                    'lp_account_mapping_ids': self._get_account_mappings(cr, uid, fyc, _LP_ACCOUNT_MAPPING, context),

                    #
                    # Net L&P options
                    #
                    'nlp_description': _("Net Loss & Profit"),
                    'nlp_journal_id':
                    self._get_journal_id(cr, uid, fyc, context),
                    'nlp_period_id':
                    self._get_lp_period_id(cr, uid, fyc, context),
                    'nlp_date': fyc.closing_fiscalyear_id.date_stop,
                    #                    'nlp_account_mapping_ids': self._get_account_mappings(cr, uid, fyc, _NLP_ACCOUNT_MAPPING, context),

                    #
                    # Closing options
                    #
                    'c_description': _("Fiscal Year Closing"),
                    'c_journal_id':
                    self._get_journal_id(cr, uid, fyc, context),
                    'c_period_id':
                    self._get_c_period_id(cr, uid, fyc, context),
                    'c_date': fyc.closing_fiscalyear_id.date_stop,
                    #                    'c_account_mapping_ids': self._get_account_mappings(cr, uid, fyc, _C_ACCOUNT_MAPPING, context),

                    #
                    # Opening options
                    #
                    'o_description': _("Fiscal Year Opening"),
                    'o_journal_id':
                    self._get_journal_id(cr, uid, fyc, context),
                    'o_period_id':
                    self._get_o_period_id(cr, uid, fyc, context),
                    'o_date': fyc.opening_fiscalyear_id.date_start,

                    # *** New state ***
                    'state': 'draft',
                }
                self.write(cr, uid, [fyc.id], vals)
        return True
Exemplo n.º 34
0
    def update(self, cr, uid, ids, context={}):
        """Browse attachments and store .odt into pxgo_openoffixe_reprots/custom_reports
        directory. Also add or update ir.values data so they're shown on model views."""
        for report in self.browse(cr, uid, ids):
            has_default = False

            for attachment in report.openoffice_file_ids:
                content = attachment.file
                fileName = attachment.filename

                if not fileName or not content:
                    continue

                path = self.save_file(fileName, content)
                for extension in [
                        '.odt', '.pdf', '.html', '.doc', '.rtf', '.txt',
                        '.ods', '.xls', '.csv', '.odp', '.ppt', '.swf'
                ]:
                    if extension in fileName:
                        if attachment.default:
                            if has_default:
                                raise osv.except_osv(
                                    _('Error'),
                                    _('There is more than one report marked as default'
                                      ))

                            has_default = True
                            # Update path into report_rml field.
                            self.write(cr, uid, [report.id],
                                       {'report_rml': path})

                            valuesId = self.pool.get('ir.values').search(
                                cr, uid,
                                [('value', '=',
                                  'ir.actions.report.xml,%s' % report.id)])
                            data = {
                                'name': report.name,
                                'model': report.model,
                                'key': 'action',
                                'object': True,
                                'key2': 'client_print_multi',
                                'value': 'ir.actions.report.xml,%s' % report.id
                            }

                            if not valuesId:
                                valuesId = self.pool.get('ir.values').create(
                                    cr, uid, data, context=context)
                            else:
                                self.pool.get('ir.values').write(
                                    cr, uid, valuesId, data, context=context)
                                valuesId = valuesId[0]

            if not has_default:
                raise osv.except_osv(
                    _('Error'), _('No report has been marked as default.'))

            # Ensure the report is registered so it can be used immediately
            openoffice_report.openoffice_report(report.report_name,
                                                report.model)

        return True
Exemplo n.º 35
0
    def imp_file(self, cr, uid, ids, context):
        """ function to import bank statement csv file  """
        statement_obj = self.pool.get('account.bank.statement')
        statement_line_obj = self.pool.get('account.bank.statement.line')
        currency_obj = self.pool.get('res.currency')
        journal_obj = self.pool.get('account.journal')
        account_obj = self.pool.get('account.account')
        period_obj = self.pool.get('account.period')
        invoice_obj = self.pool.get('account.invoice')
        company_obj = self.pool.get('res.company')
        user_obj = self.pool.get('res.users')
        current_user = user_obj.browse(cr, uid, uid, context=context)
        company_brw = current_user.company_id
        word_list = []
        val_list = []
        all_val = []
        start_end_bal = True
        statement_line_list = []
        bank_dict = {}
        end_bal = []
        date_val = []
        descr_list = []
        inv_refrence = ''
        index_kp = ''
        s1 = 'KP'
        s2 = 'kp'
        end_bal_list = []
        strt_bal_lst = []
        strt_bal_lst = []
        row_count = 0
        amount = 0.0
        transaction_date = ''
        search_ids = statement_obj.search(cr, uid, [])
        last_id = search_ids and max(search_ids)  #searching last record id
        last_stmnt_brw = statement_obj.browse(cr, uid, last_id)
        last_ending_bal = last_stmnt_brw.balance_end_real  #getting ending balance of last record

        if isinstance(ids, list):
            ids = ids[0]

        for line in company_brw.bank_lines:
            search_word = str(line.search_word)
            search_word_1 = search_word.strip()
            word_list.append(search_word_1)
        for word in word_list:
            for line in company_brw.bank_lines:
                if word == line.search_word:
                    bank_dict[word] = {
                        'account': line.account.id,
                        'sales_tax': line.sales_tax
                    }  #making dictionary as search word as key

    #  file_data = self.browse(cr,uid,ids).import_file
    # filename= self.browse(cr,uid,ids).filename
        csvfile = self.browse(cr, uid, ids).import_file

        if csvfile:
            csvfile = base64.b64decode(csvfile)
            for row in csv.reader(
                    csIO(csvfile),
                    dialect='mydialect'):  # reading data from csv
                s_ref = ''
                inv_ref = ''
                desc_str = ''
                in_ref = ''
                inv_no = ''
                inv_type = ''
                six_dig_no = ''
                partner_id = False
                csv_account_no = ''
                inv_srch = ''
                tax_amount = 0.0
                flag = False
                kp_flag = False
                else_flag = False
                if len(row):
                    count = len(row)
                    while count >= 0:
                        count = count - 1
                        if count == -1:
                            count = 0
                            break

                        value = row[count]
                        if row_count == 0 and value and count == 3:
                            journal = value
                            journal_search = journal_obj.search(
                                cr, uid, [('name', 'ilike', journal)])
                        if count == 1 and value and row_count == 0:
                            reference = value
                        if row_count == 1 and value and count == 1:
                            statement_date = value
                        if count == 3 and value and row_count == 1:
                            period = value
                            period_search = period_obj.search(
                                cr, uid, [('name', 'ilike', period)])
                        if count == 6 and value and row_count >= 4:
                            amount = value
                        if count == 5 and value and row_count >= 4:
                            ending_balance = value
                            end_bal_list.append(ending_balance)
                        if count == 0 and value and row_count >= 4:
                            csv_account_no = value
                        if count == 4 and value and row_count == 4 and start_end_bal == True:
                            start_end_bal = False
                            starting_balance = value
                            if float(
                                    starting_balance
                            ) != last_ending_bal:  #checking starting balance of a sheet with ending of last bank stmnt record
                                raise osv.except_osv(
                                    _('Warning!'),
                                    _('''You cannot import bank statement 
                                                  as last statement's ending balance and current starting balance did not match!!!'''
                                      ))
                        if count == 2 and value and row_count >= 4:
                            transac_date = value
                            datetimeobject = datetime.strptime(
                                transac_date, '%Y%m%d')
                            transaction_date = datetimeobject.strftime(
                                '%Y/%m/%d')

                        if count == 7 and value and row_count >= 4:

                            desc_str = value
                            upper_case_desc = desc_str.upper()
                            lower_case_desc = desc_str.lower()
                            six_dig_list = []
                            six_dig = []
                            split_descr = desc_str.split(' ')
                            #                            [int(s)
                            for s in desc_str.split():
                                if s.isdigit():
                                    if len(s) == 6:
                                        ints = 'KP' + s
                                        six_dig_list.append(ints)
#                            for word in split_descr:
#                                #logic to extract digits
#                                if word and not '.' in word :
#                                     six_dig = re.findall(r'\b\d{6}\b' , word)
#                                elif word.isdigit():
#                                     if len(word) == 6:
#                                        six_dig.append(word)  #appending six digit

                    if row_count >= 4:  #starting condition to append values in line_ids

                        if flag == False:
                            inv_ids = invoice_obj.search(
                                cr, uid, [('number', 'in', six_dig_list),
                                          ('state', '=', 'open')])
                            if six_dig_list and (
                                    s1 and s2
                            ) not in desc_str and inv_ids:  # checking if six digit no is there in description
                                for no in six_dig_list:
                                    invoice_no = no
                                    inv_srch = invoice_obj.search(
                                        cr, uid,
                                        [('number', '=', invoice_no), '|',
                                         ('state', '=', 'open'),
                                         ('state', '=', 'paid')])
                                    #searching invoice which is not in paid state
                                    if inv_srch:
                                        if statement_line_list and statement_line_list[
                                                0]:
                                            for each_statement_line_list in statement_line_list:
                                                if each_statement_line_list[
                                                        2].get(
                                                            'ref') == in_ref:
                                                    flag = False
                                                    inv_type = 'customer'
                                                    inv_brws = invoice_obj.browse(
                                                        cr, uid, inv_srch)
                                                    inv_no = inv_brws[0].number
                                                    account_ids = account_obj.search(
                                                        cr, uid,
                                                        [('code', '=', '99999')
                                                         ])
                                                    account_id = invoice_obj.browse(
                                                        cr, uid,
                                                        account_ids[0]).id
                                                    amount = amount
                                                    partner_id = inv_brws[
                                                        0].partner_id.id
                                    if inv_srch:
                                        flag = False
                                        inv_type = 'customer'
                                        inv_brws = invoice_obj.browse(
                                            cr, uid, inv_srch)
                                        inv_no = inv_brws[0].number
                                        partner_id = inv_brws[0].partner_id.id
                                        account_id = inv_brws[0].account_id.id
                                        if float(amount
                                                 ) == inv_brws[0].amount_total:
                                            amount = amount
                                            break
                                        else:
                                            account_ids = account_obj.search(
                                                cr, uid,
                                                [('code', '=', '99999')])
                                            account_id = invoice_obj.browse(
                                                cr, uid, account_ids[0]).id
                                            amount = amount
                                            partner_id = ''
                                            break
                                        if inv_brws[0].state == 'paid':
                                            account_ids = account_obj.search(
                                                cr, uid,
                                                [('code', '=', '99999')])
                                            account_id = invoice_obj.browse(
                                                cr, uid, account_ids[0]).id
                                            amount = amount
                                            break
                                    else:
                                        flag = True
                            elif s1 in desc_str:  # checking if s1='KP' is present in description
                                #                                    index_kp = desc_str.find(s2)  #find index of KP
                                s_ref = desc_str[desc_str.find("KP"):].replace(
                                    "KP ", "KP")
                                inv_ref = s_ref.find('KP')
                                in_ref = s_ref[inv_ref:inv_ref + 8]
                                #searching invoice which is not in paid state
                                inv_srch = invoice_obj.search(
                                    cr, uid, [('number', 'ilike', in_ref), '|',
                                              ('state', '=', 'open'),
                                              ('state', '=', 'paid')])
                                if inv_srch:
                                    flag = False
                                    inv_type = 'customer'
                                    inv_brws = invoice_obj.browse(
                                        cr, uid, inv_srch)
                                    inv_no = inv_brws[0].number
                                    partner_id = inv_brws[0].partner_id.id
                                    account_id = inv_brws[0].account_id.id
                                    if float(amount
                                             ) == inv_brws[0].amount_total:
                                        amount = amount
                                    else:
                                        account_ids = account_obj.search(
                                            cr, uid, [('code', '=', '99999')])
                                        account_id = invoice_obj.browse(
                                            cr, uid, account_ids[0]).id
                                        amount = amount
                                        partner_id = ''
                                    if inv_brws[0].state == 'paid':
                                        account_ids = account_obj.search(
                                            cr, uid, [('code', '=', '99999')])
                                        account_id = invoice_obj.browse(
                                            cr, uid, account_ids[0]).id
                                        amount = amount
                                    if statement_line_list and statement_line_list[
                                            0]:
                                        for each_statement_line_list in statement_line_list:
                                            if each_statement_line_list[2].get(
                                                    'ref') == in_ref:
                                                flag = False
                                                inv_type = 'customer'
                                                inv_brws = invoice_obj.browse(
                                                    cr, uid, inv_srch)
                                                inv_no = inv_brws[0].number
                                                account_ids = account_obj.search(
                                                    cr, uid,
                                                    [('code', '=', '99999')])
                                                account_id = invoice_obj.browse(
                                                    cr, uid, account_ids[0]).id
                                                amount = amount
                                                partner_id = inv_brws[
                                                    0].partner_id.id
                                else:
                                    flag = True
                            elif s2 in desc_str:  # checking if s2='kp' is present in description
                                #                                index_kp = desc_str.find(s2)
                                s_ref = desc_str[desc_str.find("kp"):].replace(
                                    "kp ", "kp")
                                inv_ref = s_ref.find('kp')
                                in_ref = s_ref[inv_ref:inv_ref + 8]
                                #searching invoice which is not in paid state
                                inv_srch = invoice_obj.search(
                                    cr, uid, [('number', 'ilike', in_ref), '|',
                                              ('state', '=', 'open'),
                                              ('state', '=', 'paid')])
                                if inv_srch:
                                    flag = False
                                    inv_type = 'customer'
                                    inv_brws = invoice_obj.browse(
                                        cr, uid, inv_srch)
                                    inv_no = inv_brws[0].number
                                    partner_id = inv_brws[0].partner_id.id
                                    account_id = inv_brws[0].account_id.id
                                    if float(amount
                                             ) == inv_brws[0].amount_total:
                                        amount = amount
                                    else:
                                        account_ids = account_obj.search(
                                            cr, uid, [('code', '=', '99999')])
                                        account_id = invoice_obj.browse(
                                            cr, uid, account_ids[0]).id
                                        amount = amount
                                        partner_id = ''

                                    if inv_brws[0].state == 'paid':
                                        account_ids = account_obj.search(
                                            cr, uid, [('code', '=', '99999')])
                                        account_id = invoice_obj.browse(
                                            cr, uid, account_ids[0]).id
                                        amount = amount
                                    if statement_line_list and statement_line_list[
                                            0]:
                                        for each_statement_line_list in statement_line_list:
                                            if each_statement_line_list[2].get(
                                                    'ref') == in_ref:
                                                flag = False
                                                inv_type = 'customer'
                                                inv_brws = invoice_obj.browse(
                                                    cr, uid, inv_srch)
                                                inv_no = inv_brws[0].number
                                                account_ids = account_obj.search(
                                                    cr, uid,
                                                    [('code', '=', '99999')])
                                                account_id = invoice_obj.browse(
                                                    cr, uid, account_ids[0]).id
                                                amount = amount
                                                partner_id = inv_brws[
                                                    0].partner_id.id
                                else:
                                    flag = True
                            else:
                                flag = True
                            if inv_srch and inv_type == 'customer':  # creating line if invoice is present and invoice type is customer
                                statement_line_list.append((0, 0, {
                                    'date':
                                    transaction_date,
                                    'name':
                                    desc_str if desc_str else False,
                                    'ref':
                                    inv_no if inv_no else '',
                                    'type':
                                    inv_type,
                                    'account_id':
                                    account_id,
                                    'amount':
                                    amount,
                                    'partner_id':
                                    partner_id,
                                }))
                                count = 0
                                row_count += 1
                                continue
                        if flag == True:
                            my_count = 0
                            else_count = 0  # this count is used for when all key not in csv description
                            base_amount = 0.0
                            actual_amount = 0.0
                            for key in bank_dict:
                                if key.strip() in desc_str or key.upper(
                                ) in upper_case_desc or key.lower(
                                ) in lower_case_desc and (
                                        s1 and s2
                                ) not in desc_str and not six_dig_list:  # checking if key is present in description
                                    else_count = 0
                                    for val in bank_dict.items():
                                        account_id = val[1].get('account')
                                        if key == str(val[0]):
                                            if val[1].get(
                                                    'sales_tax'
                                            ) and not my_count > 1:  # checking condition if key(search word) of dict matches with val
                                                # checking sales tax is true if true then create another line
                                                #                                               tax_amount = float(amount) * 0.21
                                                my_count += 1
                                                base_amount = float(
                                                    amount) / 1.21
                                                actual_amount = float(
                                                    base_amount) * 0.21
                                                #take sales tax account for sales tax line
                                                acc_id = account_obj.search(
                                                    cr, uid, [
                                                        '|',
                                                        ('name', '=',
                                                         'BTW VAT Paid'),
                                                        ('code', '=', '110300')
                                                    ])
                                                statement_line_list.append(
                                                    (0, 0, {
                                                        'date':
                                                        transaction_date
                                                        if transaction_date
                                                        else False,
                                                        'name':
                                                        desc_str
                                                        if desc_str else False,
                                                        'ref':
                                                        '',
                                                        'type':
                                                        'general',
                                                        'account_id':
                                                        acc_id[0]
                                                        if acc_id else False,
                                                        'amount':
                                                        actual_amount,
                                                    }))
                                                flag = True
                                        if not inv_type and key == str(
                                                val[0]
                                        ):  # checking condition if key of dict matches with val and there is no inv type
                                            inv_type = 'general'
                                            #creating line if key(search word) is present
                                            my_count += 1
                                            statement_line_list.append((0, 0, {
                                                'date':
                                                transaction_date,
                                                'name':
                                                desc_str
                                                if desc_str else False,
                                                'ref':
                                                '',
                                                'type':
                                                inv_type,
                                                'account_id':
                                                account_id,
                                                'amount':
                                                base_amount or float(amount),
                                            }))
                                            account_id = ''
                                            flag = True
                                else:
                                    else_count += 1
                            if else_count == len(bank_dict):
                                if csv_account_no:
                                    account_id = account_obj.search(
                                        cr, uid,
                                        [('code', '=', csv_account_no)])
                                    if not account_id:
                                        account_id = account_obj.search(
                                            cr, uid, [('code', '=', '99999')])
                                else:
                                    account_id = account_obj.search(
                                        cr, uid, [('code', '=', '99999')])
                                statement_line_list.append((0, 0, {
                                    'date':
                                    transaction_date,
                                    'name':
                                    desc_str if desc_str else False,
                                    'ref':
                                    '',
                                    'type':
                                    inv_type,
                                    'account_id':
                                    account_id[0],
                                    'amount':
                                    amount,
                                }))

                    count = 0
                    row_count += 1

            stmnt_search = statement_obj.search(cr, uid,
                                                [('name', '=', reference)])
            if stmnt_search:
                raise osv.except_osv(
                    _('Warning!'),
                    _('Bank Statement is already created for this reference!!')
                )
            else:
                stmnt_id = statement_obj.create(
                    cr, uid, {
                        'name': reference,
                        'journal_id': journal_search[0],
                        'date': statement_date if statement_date else False,
                        'period_id': period_search[0],
                        'balance_start': starting_balance,
                        'balance_end_real': end_bal_list[-1],
                        'line_ids': statement_line_list
                    })
                stmnt_brws = statement_obj.browse(cr, uid, stmnt_id)
                for each_line in stmnt_brws.line_ids:
                    ref = each_line.ref
                    amount = each_line.amount
                    same_line_invoic = statement_line_obj.search(
                        cr, uid,
                        [('statement_id', '=', each_line.statement_id.id),
                         ('ref', '=', ref), ('account_id', '=', 173),
                         ('id', '=', each_line.id)])
                    # above serach if avoiding to creating voiucher if statement line have have 2 or more than 2 invoices
                    # if same_line_invoic is not found then vouche create for that id
                    inv_srch = invoice_obj.search(
                        cr, uid, [('number', '=', ref), ('state', '=', 'open'),
                                  ('amount_total', '=', amount)])
                    if inv_srch and not same_line_invoic:
                        move_id = invoice_obj.browse(cr, uid,
                                                     inv_srch[0]).move_id
                        voucher_id = self.create_voucher_id(
                            cr, uid, move_id, stmnt_brws, ref, context)
                        each_line.write({'voucher_id': voucher_id})
                if float(end_bal_list[-1]) != stmnt_brws.balance_end:
                    stmnt_brws.write(
                        {'balance_end_real': stmnt_brws.balance_end})
        else:
            raise osv.except_osv(_('Warning!'), _('Please select csv file!!'))
Exemplo n.º 36
0
    def price_get_multi(self, cr, uid, pricelist_ids, products_by_qty_by_partner, context=None):

        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_obj = self.pool.get('product.pricelist.version')

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

        pricelist_version_ids = list(set(pricelist_version_ids))
        plversions_search_args = [
            ('pricelist_id', 'in', pricelist_version_ids),
            '|',
            ('date_start', '=', False),
            ('date_start', '<=', date),
            '|',
            ('date_end', '=', False),
            ('date_end', '>=', date),
        ]

        plversion_ids = product_pricelist_version_obj.search(cr, uid, plversions_search_args)
        if len(pricelist_version_ids) != len(plversion_ids):
            msg = "At least one pricelist has no active version !\nPlease create or activate one."
            raise osv.except_osv(_('Warning !'), _(msg))

        # 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_version_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)'

                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 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, plversion_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
                                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, [tmpl_id], ['uom_id'])[0]['uom_id'][0]
                                seller_uom = supplierinfo_obj.read(cr, uid, sinfo, ['product_uom'])[0]['product_uom'][0]
                                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']

                        #This is added by product_pricelist_fixed_price
                        elif res['base'] == -3:
                            price = res['fixed_price']
                            break
                        #End

                        else:
                            price_type = price_type_obj.browse(cr, uid, int(res['base']))
                            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 and res['base'] != -3: #Modified by product_pricelist_fixed_price
                            price_limit = price

                            price = price * (1.0+(res['price_discount'] or 0.0))
                            price = rounding(price, res['price_round'])
                            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

                    else:
                        # False means no valid line found ! But we may not raise an
                        # exception here because it breaks the search
                        price = False

                if price:
                    if 'uom' in context and not uom_price_already_computed:
                        product = products_dict[product_id]
                        uom = product.uos_id or product.uom_id
                        price = self.pool.get('product.uom')._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
Exemplo n.º 37
0
def _create_dta(obj, cr, uid, data, context=None):
    v = {}
    v['uid'] = str(uid)
    v['creation_date'] = time.strftime('%y%m%d')
    dta = ''

    pool = pooler.get_pool(cr.dbname)
    payment_obj = pool.get('payment.order')
    attachment_obj = pool.get('ir.attachment')
    if context is None:
        context = {}
    payment = payment_obj.browse(cr, uid, data['id'], context=context)

    if not payment.mode:
        raise osv.except_osv(_('Error'), _('No payment mode'))
    bank = payment.mode.bank_id
    if not bank:
        raise osv.except_osv(_('Error'), _('No bank account for the company.'))

    v['comp_bank_name'] = bank.bank and bank.bank.name or False
    v['comp_bank_clearing'] = bank.bank.clearing

    if not v['comp_bank_clearing']:
        raise osv.except_osv(
            _('Error'),
            _('You must provide a Clearing Number for your bank account.'))

    user = pool.get('res.users').browse(cr, uid, [uid])[0]
    company = user.company_id
    #XXX dirty code use get_addr
    co_addr = company.partner_id.address[0]
    v['comp_country'] = co_addr.country_id and co_addr.country_id.name or ''
    v['comp_street'] = co_addr.street or ''
    v['comp_zip'] = co_addr.zip
    v['comp_city'] = co_addr.city
    v['comp_name'] = co_addr.name
    v['comp_dta'] = bank.dta_code or ''  #XXX not mandatory in pratice

    v['comp_bank_number'] = bank.acc_number or ''
    if bank.iban:
        v['comp_bank_iban'] = bank.iban.replace(' ', '') or ''
    else:
        v['comp_bank_iban'] = ''
    if not v['comp_bank_iban']:
        raise osv.except_osv(_('Error'),
                             _('No IBAN for the company bank account.'))

    dta_line_obj = pool.get('account.dta.line')
    res_partner_bank_obj = pool.get('res.partner.bank')

    seq = 1
    amount_tot = 0
    amount_currency_tot = 0

    for pline in payment.line_ids:
        if not pline.bank_id:
            raise osv.except_osv(_('Error'), _('No bank account defined\n' \
                    'on line: %s') % pline.name)
        if not pline.bank_id.bank:
            raise osv.except_osv(_('Error'), _('No bank defined\n' \
                    'for the bank account: %s\n' \
                    'on the partner: %s\n' \
                    'on line: %s') + (pline.bank_id.state, pline.partner_id.name, pline.name))

        v['sequence'] = str(seq).rjust(5).replace(' ', '0')
        v['amount_to_pay'] = str(pline.amount_currency).replace('.', ',')
        v['number'] = pline.name
        v['currency'] = pline.currency.name

        v['partner_bank_name'] = pline.bank_id.bank.name or False
        v['partner_bank_clearing'] = pline.bank_id.bank.clearing or False
        if not v['partner_bank_name']:
            raise osv.except_osv(_('Error'), _('No bank name defined\n' \
                    'for the bank account: %s\n' \
                    'on the partner: %s\n' \
                    'on line: %s') % (pline.bank_id.state, pline.partner_id.name, pline.name))

        v['partner_bank_iban'] = pline.bank_id.iban or False
        v['partner_bank_number'] =  pline.bank_id.acc_number  \
                and pline.bank_id.acc_number.replace('.','').replace('-','') \
                or  False
        v['partner_post_number']=  pline.bank_id.post_number \
                and pline.bank_id.post_number.replace('.', '').replace('-', '') \
                or  False
        v['partner_bvr'] = pline.bank_id.post_number or ''
        if v['partner_bvr']:
            v['partner_bvr'] = v['partner_bvr'].replace('-', '')
            if len(v['partner_bvr']) < 9:
                v['partner_bvr'] = v['partner_bvr'][:2] + '0' * \
                        (9 - len(v['partner_bvr'])) + v['partner_bvr'][2:]

        if pline.bank_id.bank:
            v['partner_bank_city'] = pline.bank_id.bank.city or False
            v['partner_bank_street'] = pline.bank_id.bank.street or ''
            v['partner_bank_zip'] = pline.bank_id.bank.zip or ''
            v['partner_bank_country'] = pline.bank_id.bank.country and \
                    pline.bank_id.bank.country.name or ''

        v['partner_bank_code'] = pline.bank_id.bank.bic
        v['reference'] = pline.move_line_id.ref
        # Add support for owner of the account if exists..
        if pline.bank_id.owner_name:
            v['partner_name'] = pline.bank_id.owner_name
        else:
            v['partner_name'] = pline.partner_id and pline.partner_id.name or ''

        if pline.partner_id and pline.partner_id.address \
                and pline.partner_id.address[0]:
            v['partner_street'] = pline.partner_id.address[0].street
            v['partner_city'] = pline.partner_id.address[0].city
            v['partner_zip'] = pline.partner_id.address[0].zip
            # If iban => country=country code for space reason
            elec_pay = pline.bank_id.state  #Bank type
            if elec_pay == 'iban':
                v['partner_country']= pline.partner_id.address[0].country_id \
                        and pline.partner_id.address[0].country_id.code+'-' \
                        or ''
            else:
                v['partner_country']= pline.partner_id.address[0].country_id \
                        and pline.partner_id.address[0].country_id.name \
                        or ''
        else:
            v['partner_street'] = ''
            v['partner_city'] = ''
            v['partner_zip'] = ''
            v['partner_country'] = ''
            raise osv.except_osv('Error', 'No address defined \n' \
                    'for the partner: ' + pline.partner_id.name + '\n' \
                    'on line: ' + pline.name)

        if pline.order_id.date_scheduled:
            date_value = datetime.strptime(pline.order_id.date_scheduled,
                                           '%Y-%m-%d')
        elif pline.date:
            date_value = datetime.strptime(pline.date, '%Y-%m-%d')
        else:
            date_value = datetime.now()
        v['date_value'] = date_value.strftime("%y%m%d")

        # si compte iban -> iban (836)
        # si payment structure  -> bvr (826)
        # si non -> (827)

        if elec_pay == 'dta_iban':
            # If iban => country=country code for space reason
            v['comp_country'] = co_addr.country_id and co_addr.country_id.code + '-' or ''
            record_type = record_gt836
            if not v['partner_bank_iban']:
                raise osv.except_osv(_('Error'), _('No IBAN defined \n' \
                        'for the bank account: %s\n' + \
                        'on line: %s') % (res_partner_bank_obj.name_get(cr, uid, [pline.bank_id.id], context)[0][1] , pline.name))

            if v['partner_bank_code']:  # bank code is swift (BIC address)
                v['option_id_bank'] = 'A'
                v['partner_bank_ident'] = v['partner_bank_code']
            elif v['partner_bank_city']:

                v['option_id_bank'] = 'D'
                v['partner_bank_ident']= v['partner_bank_name'] \
                        + ' ' + v['partner_bank_street'] \
                        + ' ' + v['partner_bank_zip'] \
                        + ' ' + v['partner_bank_city'] \
                        + ' ' + v['partner_bank_country']
            else:
                raise osv.except_osv(_('Error'), _('You must provide the bank city '
                        'or the bic code for the partner bank: \n %d\n' + \
                        'on line: %s') %(res_partner_bank_obj.name_get(cr, uid, [pline.bank_id.id], context)[0][1], pline.name))

        elif elec_pay == 'bvrbank' or elec_pay == 'bvrpost':
            from tools import mod10r
            if v['reference']:
                v['reference'] = v['reference'].replace(' ',
                                                        '').rjust(27).replace(
                                                            ' ', '0')
                if not v['reference'] \
                    or (mod10r(v['reference'][:-1]) != v['reference'] and \
                    not len(v['reference']) == 15):
                    raise osv.except_osv(_('Error'), _('You must provide ' \
                        'a valid BVR reference number \n' \
                        'for the line: %s') % pline.name)
            if not v['partner_bvr']:
                raise osv.except_osv(_('Error'), _('You must provide a BVR number\n'
                    'for the bank account: %s' \
                    'on line: %s') % (res_partner_bank_obj.name_get(cr, uid, [pline.bank_id.id],context)[0][1] ,pline.name))
            record_type = record_gt826

        elif elec_pay == 'bvbank':
            if not v['partner_bank_number']:
                if v['partner_bank_iban']:
                    v['partner_bank_number'] = v['partner_bank_iban']
                else:
                    raise osv.except_osv(_('Error'), _('You must provide ' \
                            'a bank number \n' \
                            'for the partner bank: %s\n' \
                            'on line: %s') % (res_partner_bank_obj.name_get(cr, uid, [pline.bank_id.id], context)[0][1] , pline.name))
            if not v['partner_bank_clearing']:
                raise osv.except_osv(_('Error'), _('You must provide ' \
                        'a Clearing Number\n' \
                        'for the partner bank: %s\n' \
                        'on line %s') % (res_partner_bank_obj.name_get(cr, uid, [pline.bank_id.id], context)[0][1] , pline.name))
            v['partner_bank_number'] = '/C/' + v['partner_bank_number']
            record_type = record_gt827
        elif elec_pay == 'bvpost':
            if not v['partner_post_number']:
                raise osv.except_osv(_('Error'), _('You must provide ' \
                        'a post number \n' \
                        'for the partner bank: %s\n' \
                        'on line: %s') % (res_partner_bank_obj.name_get(cr, uid, [pline.bank_id.id], context)[0][1] ,pline.name))
            v['partner_bank_clearing'] = ''
            v['partner_bank_number'] = '/C/' + v['partner_post_number']
            record_type = record_gt827
        else:
            raise osv.except_osv(_('Error'), _('The Bank type %s of the bank account: %s is not supported') \
                    % (elec_pay, res_partner_bank_obj.name_get(cr, uid, [pline.bank_id.id], context)[0][1],))

        dta_line = record_type(v).generate()

        dta = dta + dta_line
        amount_tot += pline.amount
        amount_currency_tot += pline.amount_currency
        seq += 1

    # segment total
    v['amount_total'] = str(amount_currency_tot).replace('.', ',')
    v['sequence'] = str(seq).rjust(5).replace(' ', '0')
    if dta:
        dta = dta + record_gt890(v).generate()

    dta_data = base64.encodestring(dta)
    payment_obj.set_done(cr, uid, [data['id']], context)
    attachment_obj.create(cr,
                          uid, {
                              'name': 'DTA',
                              'datas': dta_data,
                              'datas_fname': 'DTA.txt',
                              'res_model': 'payment.order',
                              'res_id': data['id'],
                          },
                          context=context)
    return {'dta': dta_data}
Exemplo n.º 38
0
    def calculate(self, cr, uid, ids, context=None):

        if context is None:
            context = {}
        active_ids = context.get('active_ids',[])
        
        date_from = self.browse(cr,uid,ids)[0].date_from
        date_to = self.browse(cr,uid,ids)[0].date_to
        interest_rate = self.browse(cr,uid,ids)[0].interest_rate
        limit_value = self.browse(cr,uid,ids)[0].invoice_over_value
        
        if date_to <= date_from:
            raise osv.except_osv(_('Warning!'), _('Date to cannot be lower or equal to Date from.'))
        
        journal_id = [1,3,15]  #Izdane fakture, Izdani dobropisi, Temeljnica-prenos prometa kupci
        account_id = ['120000', '120100'] #Kratkorocne terjatve do kupcev v drzavi / v tujini
        
        #partner_obj = self.pool.get('res.partner')
        invoice_obj = self.pool.get('account.invoice')
        invoice_line_obj = self.pool.get('account.invoice.line')
        
        for partner_id in active_ids:
            
            postavke = {}
            interest = 0
            account_move_line_obj = self.pool.get('account.move.line')
            move_line_ids =  account_move_line_obj.search(cr, uid, [
                                                   ('partner_id', '=', partner_id),
                                                   ('journal_id', 'in', journal_id),
                                                   ('account_id.code', 'in', account_id),
                                                   ('date_maturity', '<', date_to)
                                                   ], order='date_maturity')
            
            #0. Se sprehajamo po racunih stranke
            for line in account_move_line_obj.browse(cr, uid, move_line_ids):
                
                #1.kateri zacetni datum jemljemo
                if line.date_maturity < date_from:
                    date_start = date_from
                else:
                    date_start = line.date_maturity
                    
                saldo = line.debit
                
                #2. Ze bilo delno ali polno placilo
                if line.reconcile:
                    
                    move_line_all_ids =  account_move_line_obj.search(cr, uid, ['|',
                                                                                ('reconcile_id.name', '=', line.reconcile),
                                                                                ('reconcile_partial_id.name', '=', line.reconcile),
                                                                                ('id', '!=', line.id),
                                                                                ('date', '<', date_to),
                                                                                ], order='date')
                    #2. Gledamo vsa placila za ta racun - vse linije z istim reconsilom
                    for line_all in account_move_line_obj.browse(cr, uid, move_line_all_ids):
                        
                        #2.1 Preverimo ali je bilo placilo izvedeno pred date_start, potem ga odstejemo od debita
                        if line_all.date <= date_start:
                            saldo -= line_all.credit
                        else:
                            interest_res = self.calc_interests(cr, uid, date_start, line_all.date, saldo, interest_rate)
                            
                            comment = self._prepare_description(cr, uid, line, date_start, line_all.date, saldo, interest_rate)
                            postavke[len(postavke)] = [comment, round(interest_res,2), line.move_id.id]
                            
                            interest += interest_res
                            saldo -= line_all.credit
                            date_start = line_all.date
                    
                    if round(saldo,2) > 0: #ni vec placil, torej obresti do koncnega datuma
                        interest_res = self.calc_interests(cr, uid, date_start, date_to, saldo, interest_rate)
                        comment = self._prepare_description(cr, uid, line, date_start, date_to, saldo, interest_rate)
                        postavke[len(postavke)] = [comment, round(interest_res,2), line.move_id.id]
                        interest += interest_res
                    
                    
                #3. Se sploh ni bilo placano 
                else: 
                    interest_res = self.calc_interests(cr, uid, date_start, date_to, saldo, interest_rate)
                    comment = self._prepare_description(cr, uid, line, date_start, date_to, saldo, interest_rate)
                    postavke[len(postavke)] = [comment, round(interest_res,2), line.move_id.id]
                    interest += interest_res
                    
                
            #4. Konec enega racuna - mam zbrane postavke, samo racun se naredim
            if postavke and round(interest,2) >= limit_value:
                #Priprava Racuna
                invoice_vals = self._prepare_invoice(cr, uid, partner_id, 2)
                tmp_date_from = datetime.strptime(date_from, '%Y-%m-%d')
                tmp_date_from = tmp_date_from.strftime('%d-%m-%Y')
                
                tmp_date_to = datetime.strptime(date_to, '%Y-%m-%d')
                tmp_date_to = tmp_date_to.strftime('%d-%m-%Y')
                
                invoice_vals['comment'] = 'Obračun zamudnih obresti za obdobje med ' + tmp_date_from + ' in ' + tmp_date_to
                inv_id = invoice_obj.create(cr, uid, invoice_vals)
                
                #Priprava postavk
                for pos in postavke:
                    if postavke[pos][1] > 0:
                        analytic_id = self._prepare_analytic_account_id(cr, uid, postavke[pos][2], context)
                        invoice_line_obj.create(cr, uid, {
                                                          'name': postavke[pos][0],
                                                          'origin': '',
                                                          'invoice_id': inv_id,
                                                          'account_id': self._prepare_account_id(cr, uid, '777000', context),
                                                          'account_analytic_id': analytic_id,
                                                          'price_unit': postavke[pos][1],
                                                          'quantity': 1 
                                                          })
        
        return {
                'type': 'ir.actions.act_window_close',
        }
Exemplo n.º 39
0
    def run(self, cr, uid, ids, context=None):
        logger = logging.getLogger(self._name)
        if context is None:
            context = {}
        for action in self.browse(cr, uid, ids, context):
            obj_pool = self.pool.get(action.model_id.model)
            obj = obj_pool.browse(cr,
                                  uid,
                                  context['active_id'],
                                  context=context)
            cxt = {
                'context':
                dict(context),  # copy context to prevent side-effects of eval
                'object': obj,
                'time': time,
                'cr': cr,
                'pool': self.pool,
                'uid': uid
            }
            expr = eval(str(action.condition), cxt)
            if not expr:
                continue

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

            if action.state == 'code':
                localdict = {
                    'self': self.pool.get(action.model_id.model),
                    'context':
                    dict(context
                         ),  # copy context to prevent side-effects of eval
                    'time': time,
                    'ids': ids,
                    'cr': cr,
                    'uid': uid,
                    'object': obj,
                    'obj': obj,
                }
                eval(action.code, localdict, mode="exec",
                     nocopy=True)  # nocopy allows to return 'action'
                if 'action' in localdict:
                    return localdict['action']

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

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

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

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

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

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

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

                return res

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

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

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

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

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

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

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

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

                obj_pool = None
                res_id = False

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

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

        if not args['account_id']:
            if not args['partner_id']:
                msg = _(
                    'There is no receivable account defined to make payment')
            else:
                msg = _(
                    'There is no receivable account defined to make payment for the partner: "%s" (id:%d)'
                ) % (
                    order.partner_id.name,
                    order.partner_id.id,
                )
            raise osv.except_osv(_('Configuration Error !'), msg)
        print data, "DATA===================DATA"
        statement_id = statement_obj.search(
            cr,
            uid, [('journal_id', '=', data['journal'][0]),
                  ('company_id', '=', curr_company), ('user_id', '=', uid),
                  ('state', '=', 'open')],
            context=context)
        if len(statement_id) == 0:
            raise osv.except_osv(_('Error !'),
                                 _('You have to open at least one cashbox'))
        if statement_id:
            statement_id = statement_id[0]
        args['statement_id'] = statement_id
        args['pos_statement_id'] = order_id
        args['journal_id'] = data['journal'][0]
        args['type'] = 'customer'
        args['ref'] = order.name
        statement_line_obj.create(cr, uid, args, context=context)
        ids_new.append(statement_id)

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

        return statement_id
    def action_post(self, cr, uid, ids, context=None):

        if context is None:
            context = {}

        move_pool = self.pool.get('account.move')
        move_line_pool = self.pool.get('account.move.line')
        period_obj = self.pool.get('account.period')
        tax_obj = self.pool.get('account.tax')
        seq_obj = self.pool.get('ir.sequence')
        for _doc in self.browse(cr, uid, ids, context=context):
            if _doc.state in [
                    'submit',
            ]:
                company_currency = _doc.journal_id.company_id.currency_id.id
                _line_to_recon = []

                if _doc.journal_id.sequence_id:
                    name = seq_obj.get_id(cr, uid,
                                          _doc.journal_id.sequence_id.id)
                else:
                    raise osv.except_osv(
                        _('Error !'),
                        _('Please define a sequence for journal %s!') %
                        (_doc.journal_id.name))
                if not name:
                    raise osv.except_osv(
                        _('Error !'),
                        _('Cannot get sequence for journal %s for company %s!')
                        % (_doc.journal_id.name,
                           self.pool.get('res.users').browse(
                               cr, uid, uid, context=context).company_id.name))
                ref = name.replace('/', '')

                _period = period_obj.find(
                    cr, uid, dt=_doc.assign_date, context=context) or False
                move = {
                    'name': name,
                    'journal_id': _doc.journal_id.id,
                    'date': _doc.assign_date,
                    'ref': ref,
                    'period_id': _period and _period[0] or False
                }
                move_id = move_pool.create(cr, uid, move)

                # Create move line for each assignment_lines
                for _line in _doc.assignment_lines:
                    if (_line.credit != 0) and (_line.debit != 0):
                        raise osv.except_osv(
                            _('Error'),
                            _("Please enter only debit or credit for line %s of voucher %s!"
                              ) % (_line.name, _doc.id))
                    if (_line.credit == 0) and (_line.debit == 0):
                        raise osv.except_osv(
                            _('Error'),
                            _("Please enter debit or credit for for line %s of voucher %s!"
                              ) % (_line.name, _doc.id))

                    debit = _line.debit
                    credit = _line.credit

                    if debit < 0:
                        credit = -debit
                        debit = 0.0
                    if credit < 0:
                        debit = -credit
                        credit = 0.0
                    sign = debit - credit < 0 and -1 or 1

                    move_line = {
                        'name': _line.name or '/',
                        'debit': debit,
                        'credit': credit,
                        'account_id': _line.account_id.id,
                        'move_id': move_id,
                        'journal_id': _doc.journal_id.id,
                        'period_id': _period and _period[0] or False,
                        'partner_id': _line.partner_id and _line.partner_id.id
                        or False,
                        'date': _doc.assign_date,
                    }
                    move_line_pool.create(cr, uid, move_line)

                # Create move line for each bank_lines, reverse the credit and debit
                for _line in _doc.bank_lines:
                    # Only if amount to use is there, if not, ignore it.
                    if _line.amount_to_use:
                        debit = 0.0
                        credit = _line.amount_to_use

                        if debit < 0:
                            credit = -debit
                            debit = 0.0
                        if credit < 0:
                            debit = -credit
                            credit = 0.0
                        sign = debit - credit < 0 and -1 or 1

                        move_line = {
                            'name':
                            _line.name or '/',
                            'debit':
                            debit,
                            'credit':
                            credit,
                            'account_id':
                            _line.account_id.id,
                            'move_id':
                            move_id,
                            'journal_id':
                            _doc.journal_id.id,
                            'period_id':
                            _period and _period[0] or False,
                            'partner_id':
                            _line.partner_id and _line.partner_id.id or False,
                            'date':
                            _doc.assign_date,
                        }
                        id = move_line_pool.create(cr, uid, move_line)
                        _line_to_recon.append([id, _line.move_line_id.id])

                # Create move line for write-off if any
                if _doc.writeoff_amount:
                    debit = 0.0
                    credit = _doc.writeoff_amount

                    if debit < 0:
                        credit = -debit
                        debit = 0.0
                    if credit < 0:
                        debit = -credit
                        credit = 0.0
                    sign = debit - credit < 0 and -1 or 1

                    move_line = {
                        'name': _doc.comment,
                        'debit': debit,
                        'credit': credit,
                        'account_id': _doc.writeoff_acc_id.id,
                        'move_id': move_id,
                        'journal_id': _doc.journal_id.id,
                        'period_id': _period and _period[0] or False,
                        'date': _doc.assign_date,
                    }
                    move_line_pool.create(cr, uid, move_line)

                move_pool.post(cr, uid, [move_id], context={})

                for _pair in _line_to_recon:
                    move_line_pool.reconcile_partial(cr,
                                                     uid,
                                                     _pair,
                                                     'manual',
                                                     context=context)

                _doc.write({'state': 'posted', 'move_id': move_id})

            return True

        return False
    def write(self, cr, uid, ids, vals, context=None):
        for order in self.browse(cr, uid, ids, context):
            if (vals.get('prices_used')
                    and vals['prices_used'] == 'openerp_prices') or (
                        not vals.get('prices_used')
                        and order.prices_used == 'openerp_prices'):
                continue
            if vals.get('order_line'):
                for orderline in vals['order_line']:
                    if orderline[
                            1] == 0 and order.prices_used == 'external_total_prices':
                        raise osv.except_osv(
                            _('Error'),
                            _("Sale order %s can not have a non-imported line (%s) because total amounts are not calculated, they are imported from an external application/shop."
                              ) % (order.name, orderline[2]['name']))
                    order_line_stored = self.pool.get(
                        'sale.order.line').browse(cr,
                                                  uid,
                                                  orderline[1],
                                                  context=context)
                    field_mod = []
                    if order_line_stored.product_uos_qty != orderline[2][
                            'product_uos_qty']:
                        field_mod.append(_("Quantity (UoS)"))
                    if order_line_stored.product_uom_qty != orderline[2][
                            'product_uom_qty']:
                        field_mod.append(_("Quantity (UoM)"))
                    if order_line_stored.price_unit != orderline[2][
                            'price_unit']:
                        field_mod.append(_("Unit Price"))
                    if order_line_stored.discount != orderline[2]['discount']:
                        field_mod.append(_("Discount (%)"))
                    if order_line_stored.tax_id and len(
                            order_line_stored.tax_id
                    ) != 1 or order_line_stored.tax_id[0].id != orderline[2][
                            'tax_id'][0][2][0]:
                        field_mod.append(_("Taxes"))

                    if field_mod:
                        field_mod = ",".join(field_mod)
                        raise osv.except_osv(
                            _('Error'),
                            _("Field(s) %s of line %s in sale order %s can not be edited because total amounts are not calculated, they are imported from an external application/shop."
                              ) %
                            (field_mod, order_line_stored.name, order.name))

        result = super(sale_order, self).write(cr, uid, ids, vals, context)

        for order in self.browse(cr, uid, ids, context):
            for orderline in order.order_line:
                #if order.prices_used == 'external_total_prices' and orderline.prices_used != 'external_total_prices':
                if (vals.get('prices_used')
                        and vals['prices_used'] == 'external_total_prices'
                        or order.prices_used == 'external_total_prices'
                    ) and orderline.prices_used != 'external_total_prices':
                    raise osv.except_osv(
                        _('Error'),
                        _("Sale order %s can not have a non-imported line because total amounts are not calulated, they are imported from an external application/shop."
                          ) % order.name)

        return result
Exemplo n.º 43
0
    def action_create_picking(self,cr,uid,ids,context=None):
        """ 
        Workflow Function to change state to picking and create picking.

        @return: Boolean True
        """
        pick_name = ''
	# Fuel Picking Objects
        fuel_picking_obj = self.pool.get('fuel.picking')
        fuel_picking_line_obj = self.pool.get('stock.move')
        fuel_request_lines_obj = self.pool.get('fuel.request.lines')
        payment_enrich_obj = self.pool.get('payment.enrich')
        payment_enrich_lines_obj = self.pool.get('payment.enrich.lines')
        for record in self.browse(cr, uid, ids):
	       if record.purpose =='mission' or record.purpose =='emergency' :
                if not record.fuel_lines:
                       raise osv.except_osv(_('No Fuel  !'), _('Please Fuel Item Details ..'))
                if record.payment_selection == 'enrich':
                    #details = smart_str('Public Relation Request No:'+record.name+'\nProcedure For:'+record.procedure_for+'\nprocedure:'+record.procedure_id.name+'\nPurpose:'+record.purpose.name)
                    details = 'Extra Fuel Request No:'+record.name+"\nPurpose:"+record.purpose
                    enrich_payment_lines_id = payment_enrich_lines_obj.create(cr, uid, {
					            'enrich_id':record.enrich_category.id,
                        		'cost': record.cost,
					            'date':time.strftime('%Y-%m-%d'),
					            'state':'draft',
                        		'name':details,
					            'department_id':record.department.id,
                            				}, context=context)
                    self.write(cr, uid, ids, {'state':'done'},context=context)
                elif record.payment_selection == 'stock' :    
                # Creating Piciking
                    pick_name = self.pool.get('ir.sequence').get(cr, uid, 'fuel.picking.out')
                    picking_id = fuel_picking_obj.create(cr, uid, {
                                'name': pick_name,
            					'origin': record.name,
            					'date': record.date,
            					'type': 'out',
           					    'state': 'draft',
						        'move_type':'direct',
            					'note': record.notes,
            					'department_id':record.department.id,
						        'fuel_request_id':record.id
                                         })
            	# Creating Picking Lines
                    for line in record.fuel_lines:
                        if not line.product_id.property_fuel_customer.id :
                            raise osv.except_osv(_('No Location  !'), _('Please Insert Fuel Destination Location ..'))
                        picking_line_id = fuel_picking_line_obj.create(cr, uid, {
                                                   'name': line.name,
            					   'fuel_picking_id': picking_id,
            					   'product_id': line.product_id.id,
            					   'product_qty': line.product_qty,
            					   'product_uom': line.product_uom.id,
						   #'product_uos_qty':line.product_qty,
            					   'state': 'draft',
            					   'location_id': line.product_id.property_fuel_extra.id ,
            					   'location_dest_id': line.product_id.property_fuel_customer.id ,
                                    'fuel_request_line_id': line.id,
                                         })
                        fuel_request_lines_obj.write(cr, uid, [line.id], {'move_id':picking_line_id})
                    self.write(cr, uid, ids, {'state':'picking','picking_no':pick_name})
        return True
Exemplo n.º 44
0
    def create_membership_invoice(self,
                                  cr,
                                  uid,
                                  ids,
                                  product_id=None,
                                  datas=None,
                                  context=None):
        """ Create Customer Invoice of Membership for partners.
        @param datas: datas has dictionary value which consist Id of Membership product and Cost Amount of Membership.
                      datas = {'membership_product_id': None, 'amount': None}
        """
        invoice_obj = self.pool.get('account.invoice')
        invoice_line_obj = self.pool.get('account.invoice.line')
        invoice_tax_obj = self.pool.get('account.invoice.tax')
        product_id = product_id or datas.get('membership_product_id', False)
        amount = datas.get('amount', 0.0)
        invoice_list = []
        if type(ids) in (
                int,
                long,
        ):
            ids = [ids]
        for partner in self.browse(cr, uid, ids, context=context):
            account_id = partner.property_account_receivable and partner.property_account_receivable.id or False
            fpos_id = partner.property_account_position and partner.property_account_position.id or False
            addr = self.address_get(cr, uid, [partner.id], ['invoice'])
            if partner.free_member:
                raise osv.except_osv(_('Error !'),
                                     _("Partner is a free Member."))
            if not addr.get('invoice', False):
                raise osv.except_osv(
                    _('Error !'),
                    _("Partner doesn't have an address to make the invoice."))
            quantity = 1
            line_value = {
                'product_id': product_id,
            }

            line_dict = invoice_line_obj.product_id_change(cr,
                                                           uid, {},
                                                           product_id,
                                                           False,
                                                           quantity,
                                                           '',
                                                           'out_invoice',
                                                           partner.id,
                                                           fpos_id,
                                                           price_unit=amount,
                                                           context=context)
            line_value.update(line_dict['value'])
            line_value['price_unit'] = amount
            if line_value.get('invoice_line_tax_id', False):
                tax_tab = [(6, 0, line_value['invoice_line_tax_id'])]
                line_value['invoice_line_tax_id'] = tax_tab

            invoice_id = invoice_obj.create(
                cr,
                uid, {
                    'partner_id': partner.id,
                    'account_id': account_id,
                    'fiscal_position': fpos_id or False
                },
                context=context)
            line_value['invoice_id'] = invoice_id
            invoice_line_id = invoice_line_obj.create(cr,
                                                      uid,
                                                      line_value,
                                                      context=context)
            invoice_obj.write(cr,
                              uid,
                              invoice_id,
                              {'invoice_line': [(6, 0, [invoice_line_id])]},
                              context=context)
            invoice_list.append(invoice_id)
            if line_value['invoice_line_tax_id']:
                tax_value = invoice_tax_obj.compute(cr, uid,
                                                    invoice_id).values()
                for tax in tax_value:
                    invoice_tax_obj.create(cr, uid, tax, context=context)
        #recompute the membership_state of those partners
        self.pool.get('res.partner').write(cr, uid, ids, {})
        return invoice_list
Exemplo n.º 45
0
 def write(self, cr, uid, ids, vals, context={}):
     if vals.has_key('code'):
         if vals['code'].find('-') != -1:
             raise osv.except_osv("Error",
                                  "Use '_' in code instead of '-' ")
     return super(dm_dtp_plugin, self).write(cr, uid, ids, vals, context)
Exemplo n.º 46
0
        if self.pidfile:
            f = open(self.pidfile, 'w')
            try:
                f.write(str(process.pid))
            finally:
                f.close()

    def execute(self, *args):
        """
		Render report and return the number of pages generated.
		"""
        try:
            return self.proxy.Report.execute(*args)
        except (xmlrpclib.ProtocolError, socket.error), e:
            #self.info("First try did not work: %s / %s" % (str(e), str(e.args)) )
            self.start()
            for x in xrange(40):
                time.sleep(1)
                try:
                    return self.proxy.Report.execute(*args)
                except (xmlrpclib.ProtocolError, socket.error), e:
                    self.error("EXCEPTION: %s %s" % (str(e), str(e.args)))
                    pass
                except xmlrpclib.Fault, e:
                    raise osv.except_osv(_('Report Error'), e.faultString)
        except xmlrpclib.Fault, e:
            raise osv.except_osv(_('Report Error'), e.faultString)


# vim:noexpandtab:smartindent:tabstop=8:softtabstop=8:shiftwidth=8:
Exemplo n.º 47
0
    def _do_create_saleorder(self, cr, uid, data, context):
        today = datetime.datetime.today()
        order_cr = pooler.get_pool(cr.dbname).get('sale.order')

        partner_cr = pooler.get_pool(cr.dbname).get('res.partner')
        address_cr = pooler.get_pool(cr.dbname).get('res.partner.address')
        product_cr = pooler.get_pool(cr.dbname).get('product.product')
        sale_order_cr = pooler.get_pool(cr.dbname).get('sale.order')
        line_cr = pooler.get_pool(cr.dbname).get('sale.order.line')
        tax_cr = pooler.get_pool(cr.dbname).get('sale.order.tax')

        import_order_cr = pooler.get_pool(cr.dbname).get('ica.import_order')

        logger = netsvc.Logger()

        ord_nr = []

        for jid in data['ids']:  # Om det är flera markerade dagjournaler
            journal = pooler.get_pool(cr.dbname).get('ica.mrpjournal').read(
                cr, uid, jid)
            #            raise osv.except_osv(_('Journal'), _('Data\n%s') % (journal))

            # Just a search to check order_ids is growing
            print journal
            if journal['status'] == 'i':  # Journal ready for create saleorder

                import_order_ids = import_order_cr.search(
                    cr, uid, [("status", "=", "n"),
                              ("mrpjournal_id", "=", jid)])

                print "import_order_ids", import_order_ids

                if import_order_ids:

                    for order_record in import_order_cr.read(
                            cr, uid, import_order_ids):
                        order = json.loads(order_record['blob'])

                        # Partner / shop
                        #partner_id = sock.execute(dbname, uid, pwd, 'res.partner', 'search',[("shop_iln","=",order['HEA']['EANSHOP'])])   # Use EANSHOP as key in partner
                        #if not partner_id:
                        #    partner_id = sock.execute(dbname, uid, pwd, 'res.partner', 'create', { 'consignee_iln':  order['HEA']['EANCONSIGNEE'], 'shop_iln': order['HEA']['EANSHOP'], 'customernumber': order['HEA']['CUSTOMERNUMBER'], 'name': 'Saknad kund %s' % order['HEA']['EANSHOP']})
                        #    partner_id = sock.execute(dbname, uid, pwd, 'res.partner', 'search',[("shop_iln","=",order['HEA']['EANSHOP'])])   # Use EANSHOP as key in partner
                        #partner = sock.execute(dbname, uid, pwd, 'res.partner', 'read', partner_id[0])
                        #addr =  {}
                        #for addr_rec in sock.execute(dbname, uid, pwd, 'res.partner.address', 'read', partner['address'] ):
                        #    addr[addr_rec['type']] = addr_rec
                        #adress_order    = addr.get('default',{'id': 1})
                        #adress_invoice  = addr.get('invoice',addr.get('default',{'id': 1}))
                        #adress_shipping = addr.get('delivery',addr.get('default',{'id': 1}))
                        # Partner / shop
                        partner_id = partner_cr.search(cr, uid, [
                            ("shop_iln", "=", order['HEA']['EANDELIVERY'])
                        ])  # Use EANDELIVERY as key in partner
                        if not partner_id:
                            partner_id = partner_cr.create(
                                cr, uid, {
                                    'consignee_iln':
                                    order['HEA']['EANCONSIGNEE'],
                                    'shop_iln':
                                    order['HEA']['EANDELIVERY'],
                                    'customernumber':
                                    order['HEA']['CUSTOMERNUMBER'],
                                    'name':
                                    'Saknad kund %s' %
                                    order['HEA']['EANDELIVERY']
                                })
                            partner_id = partner_cr.search(
                                cr, uid,
                                [("shop_iln", "=", order['HEA']['EANDELIVERY'])
                                 ])  # Use EANDELIVERY as key in partner
                        partner = partner_cr.read(cr, uid, partner_id)
                        print "partner ", partner
                        print "address", partner[0]['address']
                        addr = {}
                        for addr_rec in address_cr.read(
                                cr, uid, partner[0]['address']):
                            addr[addr_rec['type']] = addr_rec
                        adress_order = addr.get('default', {'id': 1})
                        adress_invoice = addr.get(
                            'invoice', addr.get('default', {'id': 1}))
                        adress_shipping = addr.get(
                            'delivery', addr.get('default', {'id': 1}))

                        # Buyer / ICA
                        buyer_id = partner_cr.search(cr, uid, [
                            ("shop_iln", "=", order['HEA']['EANBUYER'])
                        ])  # Use EANSHOP as key in partner
                        if not buyer_id:
                            buyer_id = partner_cr.create(
                                cr, uid, {
                                    'consignee_iln':
                                    order['HEA']['EANCONSIGNEE'],
                                    'shop_iln':
                                    order['HEA']['EANBUYER'],
                                    'customernumber':
                                    order['HEA']['CUSTOMERNUMBER'],
                                    'name':
                                    'Saknad kund %s' % order['HEA']['EANBUYER']
                                })
                            buyer_id = partner_cr.search(
                                cr, uid, [
                                    ("shop_iln", "=", order['HEA']['EANBUYER'])
                                ])  # Use EANSHOP as key in partner
                        buyer = partner_cr.read(cr, uid, buyer_id)

                        # Sender / ICA
                        sender_id = partner_cr.search(cr, uid, [
                            ("shop_iln", "=", order['HEA']['EANSENDER'])
                        ])  # Use EANSHOP as key in partner
                        if not sender_id:
                            sender_id = partner_cr.create(
                                cr, uid, {
                                    'consignee_iln':
                                    order['HEA']['EANCONSIGNEE'],
                                    'shop_iln':
                                    order['HEA']['EANSENDER'],
                                    'customernumber':
                                    order['HEA']['CUSTOMERNUMBER'],
                                    'name':
                                    'Saknad kund %s' %
                                    order['HEA']['EANSENDER']
                                })
                            sender_id = partner_cr.search(
                                cr, uid,
                                [("shop_iln", "=", order['HEA']['EANSENDER'])
                                 ])  # Use EANSHOP as key in partner
                        sender = partner_cr.read(cr, uid, sender_id)

                        # Create sale.order when mrpjournal are marked with state = s for orders in that journal
                        if order_record['saleorder_id'] == 0:
                            print "Skapa sale.order", partner[0]['id']

                            ord_nr.append(order['HEA']['ORDERNUMBER'])
                            # print mrpjournal, order, "Saleorder"
                            saleorder_id = sale_order_cr.create(
                                cr,
                                uid,
                                {
                                    'partner_id':
                                    buyer[0]['id'],
                                    'ica_status':
                                    'u',
                                    'client_order_ref':
                                    order['HEA']['ORDERNUMBER'],
                                    'origin':
                                    order['HEA']['ORDERNUMBER'],
                                    'date_order':
                                    order['HEA']['ORDERDATE'],
                                    'date_requested':
                                    order['HEA']['DELDATESTORE'],
                                    'date_promised':
                                    order['HEA']['DELDATELE'],
                                    'date_delfromica':
                                    order['HEA']['SHIPDATEFROMLE'],
                                    'partner_order_id':
                                    adress_order['id'],
                                    'partner_invoice_id':
                                    adress_invoice['id'],
                                    'partner_shipping_id':
                                    adress_shipping['id'],
                                    'pricelist_id':
                                    partner[0]['property_product_pricelist']
                                    [0],
                                    'ica_mrpjournal':
                                    journal['id'],
                                    'eansender':
                                    order['HEA']['EANSENDER'],
                                    'eanreceiver':
                                    order['HEA']['EANRECEIVER'],
                                    'eandelivery':
                                    order['HEA']['EANDELIVERY'],
                                    'eanconsignee':
                                    order['HEA']['EANCONSIGNEE'],
                                    'eanshop':
                                    order['HEA']['EANSHOP'],
                                    'eanbuyer':
                                    order['HEA']['EANBUYER'],
                                    'eansupplier':
                                    order['HEA']['EANSUPPLIER'],
                                    'customernumber':
                                    order['HEA']['CUSTOMERNUMBER'],
                                    # Retrieve freigh information
                                    #"FREIGHTLABEL1": "03/05/527/02/005/011",
                                    'utlevomr':
                                    order['HEA']['FREIGHTLABEL1'].split(
                                        '/')[0],
                                    'port':
                                    order['HEA']['FREIGHTLABEL1'].split(
                                        '/')[1],
                                    'lass':
                                    order['HEA']['FREIGHTLABEL1'].split(
                                        '/')[2],
                                    'pl':
                                    order['HEA']['FREIGHTLABEL1'].split(
                                        '/')[3],
                                    'ruta1':
                                    order['HEA']['FREIGHTLABEL1'].split(
                                        '/')[4],
                                    'ruta2':
                                    order['HEA']['FREIGHTLABEL1'].split(
                                        '/')[5],
                                    'state':
                                    'progress',
                                })

                            #            saleorder = sock.execute(dbname, uid, pwd, 'sale.order', 'read', saleorder_id)

                            #            print "Saleorder_id ", saleorder_id, order['HEA']['LIN']

                            for line in order['HEA']['LIN']:
                                # Product
                                product_id = product_cr.search(
                                    cr, uid, [("ean14", "=", line['EAN'])
                                              ])  # Use EAN as key in product

                                if not product_id:  # Create missing products
                                    logger.notifyChannel(
                                        "do_create_saleorder",
                                        netsvc.LOG_WARNING,
                                        "Missing product '%s' '%s'  ." %
                                        (line['SU_ARTICLECODE'], line['EAN']))
                                    cr.rollback()
                                    raise osv.except_osv(
                                        _('Saknad produkt'),
                                        _('%s %s') %
                                        (line['SU_ARTICLECODE'], line['EAN']))
                                    return {}
                                    #partner_id = product_cr.create(cr, uid,  {'su_articlecode': line['SU_ARTICLECODE'], 'ean14': line['EAN'], 'name': 'Saknad produkt %s'  % line['SU_ARTICLECODE'], 'categ_id': 1,})
                                    #product_id = product_cr.search(cr, uid, [("ean14","=",line['EAN'])])

                                product = product_cr.read(
                                    cr, uid, product_id[0])
                                print product_id, product
                                tax_id = int(product['taxes_id'][0])
                                print "tax_id", tax_id

                                saleorderline_id = line_cr.create(
                                    cr,
                                    uid,
                                    {
                                        #                    'address_allotment_id': ,
                                        'delay': 0.0,
                                        'discount': 0.0,
                                        'invoiced': 0,
                                        #                   'invoice_lines': fields.many2many('account.invoice.line', 'sale_order_line_invoice_rel', 'order_line_id', 'invoice_id', 'Invoice Lines', readonly=True),
                                        #                   'move_ids': fields.one2many('stock.move', 'sale_line_id', 'Inventory Moves', readonly=True),
                                        'name': product['name'],
                                        'notes': '',
                                        #                    'number_packages': fields.function(_number_packages, method=True, type='integer', string='Number Packages'),
                                        'order_id': saleorder_id,
                                        #                    'order_partner_id': fields.related('order_id', 'partner_id', type='many2one', relation='res.partner', string='Customer')
                                        #                    'price_net': fields.function(_amount_line_net, method=True, string='Net Price', digits=(16, int(config['price_accuracy']))),
                                        #                    'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal', digits=(16, int(config['price_accuracy']))),
                                        #                    'price_unit':       product['uos_id'],
                                        'price_unit': product['list_price'],
                                        #                    'procurement_id': fields.many2one('mrp.procurement', 'Procurement'),
                                        'product_id': product['id'],
                                        'product_packaging': 0,
                                        #                    'product_uom':      product['list_price'],
                                        'product_uom': product['uom_id'][0],
                                        'product_uom_qty': line['QTY_ORDERED'],
                                        'product_uos': 1,
                                        'product_uos_qty': 1,
                                        #                    'property_ids': fields.many2many('mrp.property', 'sale_order_line_property_rel', 'order_id', 'property_id', 'Properties', readonly=True, states={'draft':[('readonly',False)]}),
                                        'sequence': 10,
                                        'state': 'confirmed',
                                        'th_weight': 0,
                                        'type': 'make_to_stock',
                                        'tax_id': product['taxes_id'],
                                    })

                                print "Sale order line id", saleorderline_id

                                for tax in product['taxes_id']:
                                    #    saleordertax_id = tax_cr.create(cr, uid,  {'order_line_id': saleorderline_ids, 'tax_id': int(tax)})
                                    cr.execute(
                                        'INSERT INTO sale_order_tax ("order_line_id", "tax_id", "create_uid", "create_date") VALUES ('
                                        + str(saleorderline_id) + ',' +
                                        str(tax) + ', ' + str(uid) + ', ' +
                                        today.strftime("'%Y-%m-%d %H:%M'") +
                                        ' )')

                            # Mark import_order imported / Confirmed
                            # Knyt ica.import_order till mrpjournal
                            # Create tax-lines
                            #print sale_order_cr.amount_tax(cr,uid,saleorder_id)

                            order_marked = import_order_cr.write(
                                cr, uid, order_record['id'], {
                                    'status': 'c',
                                    'saleorder_id': saleorder_id,
                                })
                            pooler.get_pool(
                                cr.dbname).get('ica.mrpjournal').write(
                                    cr, uid, jid, {
                                        'saleorder_imported':
                                        today.strftime('%Y-%m-%d %H:%M'),
                                        'status':
                                        's'
                                    })
                else:
                    pooler.get_pool(cr.dbname).get('ica.mrpjournal').write(
                        cr, uid, jid, {
                            'saleorder_imported':
                            today.strftime('%Y-%m-%d %H:%M'),
                            'status': 's'
                        })

        cr.commit()

        doubles = check_ordernumber(cr, uid,
                                    ord_nr)  # Kontrollerar orderdubletter
        if len(doubles) > 0:
            logger.notifyChannel("warning", netsvc.LOG_WARNING,
                                 "Orderdubletter '%s'  ." % (doubles))
            raise osv.except_osv(
                _('Dublettorder'),
                _('Dessa ordernumber (Client ref) finns redan\n%s') %
                (doubles))


# Kontroll order_requested före dagens datum, meddela ordernummer för manuell kontroll

        return {}
Exemplo n.º 48
0
    def internal_supply(self, cr, uid, ids, context, *args):
        for obj in self.browse(cr, uid, ids, context=context):
            if obj.incoming_left <= 0:
                raise osv.except_osv(_('Error !'), _('Incoming Left must be greater than 0 !'))
            if not obj.supply_warehouse_id:
                raise osv.except_osv(_('Error !'), _('You must specify a Source Warehouse !'))
            if obj.supply_warehouse_id.id == obj.warehouse_id.id:
                raise osv.except_osv(_('Error !'), _('You must specify a Source Warehouse different than calculated (destination) Warehouse !'))
            uom_qty, uom, uos_qty, uos = self._qty_to_standard(cr, uid, obj, context)
            user = self.pool.get('res.users').browse(cr, uid, uid, context)
            picking_id = self.pool.get('stock.picking').create(cr, uid, {
                        'origin': _('MPS(%s) %s') %(user.login, obj.period_id.name),
                        'type': 'internal',
                        'state': 'auto',
                        'date': obj.period_id.date_start,
                        'move_type': 'direct',
                        'invoice_state':  'none',
                        'company_id': obj.company_id.id,
                        'note': _('Pick created from MPS by user: %s   Creation Date: %s \
                                    \nFor period: %s   according to state: \
                                    \n Warehouse Forecast: %s \
                                    \n Initial Stock: %s \
                                    \n Planned Out: %s  Planned In: %s \
                                    \n Already Out: %s  Already In: %s \
                                    \n Confirmed Out: %s   Confirmed In: %s \
                                    \n Planned Out Before: %s   Confirmed In Before: %s \
                                    \n Expected Out: %s   Incoming Left: %s \
                                    \n Stock Simulation: %s   Minimum stock: %s ')
                                    % (user.login, time.strftime('%Y-%m-%d %H:%M:%S'), obj.period_id.name, obj.warehouse_forecast,
                                       obj.stock_start, obj.planned_outgoing, obj.to_procure, obj.already_out, obj.already_in,
                                       obj.outgoing, obj.incoming, obj.outgoing_before, obj.incoming_before,
                                       obj.outgoing_left, obj.incoming_left, obj.stock_simulation, obj.minimum_op)
                        })

            move_id = self.pool.get('stock.move').create(cr, uid, {
                        'name': _('MPS(%s) %s') %(user.login, obj.period_id.name),
                        'picking_id': picking_id,
                        'product_id': obj.product_id.id,
                        'date': obj.period_id.date_start,
                        'product_qty': uom_qty,
                        'product_uom': uom,
                        'product_uos_qty': uos_qty,
                        'product_uos': uos,
                        'location_id': obj.stock_supply_location and obj.supply_warehouse_id.lot_stock_id.id or \
                                                                obj.supply_warehouse_id.lot_output_id.id,
                        'location_dest_id': obj.procure_to_stock and obj.warehouse_id.lot_stock_id.id or \
                                                                obj.warehouse_id.lot_input_id.id,
                        'tracking_id': False,
                        'company_id': obj.company_id.id,
                    })
            wf_service = netsvc.LocalService("workflow")
            wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)

        self.calculate_planning(cr, uid, ids, context)
        prev_text = obj.history or ""
        pick_name = self.pool.get('stock.picking').browse(cr, uid, picking_id).name
        self.write(cr, uid, ids, {
                    'history': _('%s Pick List %s (%s,  %s) %s %s \n') % (prev_text, pick_name, user.login, time.strftime('%Y.%m.%d %H:%M'),
                    obj.incoming_left, obj.product_uom.name)
                })

        return True
Exemplo n.º 49
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
Exemplo n.º 50
0
 def generate_record(self,
                     cr,
                     uid,
                     ids,
                     record_list,
                     row_number,
                     context={}):
     result = []
     if len(record_list):
         for template in self.browse(cr, uid, ids, context=context):
             target_model_pool = self.pool.get(
                 template.target_model_id.model)
             record = {}
             upd_key = []
             updated = False
             ready_to_create_new = True
             for template_line in template.line_ids:
                 field_name = template_line.target_field.name
                 value = template_line.get_field(record_list,
                                                 row_number,
                                                 testing=True,
                                                 context=context)
                 if value:
                     record.update({field_name: value})
                     if template_line.key_field:
                         upd_key.append(
                             (template_line.target_field.name, '=', value))
                 else:
                     if template_line.required:
                         ready_to_create_new = False
             if template.create_new and template.create_unique_only and upd_key:
                 #check if record matching key already exists
                 if self.low_level_search(cr,
                                          uid,
                                          ids,
                                          upd_key,
                                          context=context):
                     log_notes = "Record already exists - skipping ", record
                     context['import_log'].append(log_notes)
                     return result
                 #checking if record matching key already exists in fields defined in matching rules
                 matching_model_field_ids = []
                 for template_line in template.line_ids:
                     field_name = template_line.target_field.name
                     value = template_line.get_field(record_list,
                                                     row_number,
                                                     testing=True,
                                                     context=context)
                     for matching_value in template.matching_rules_ids:
                         if matching_value.source_field_id.name == field_name:
                             matching_model = matching_value.comparison_model_id.model
                             matching_model_upd_key = []
                             matching_model_upd_key.append(
                                 (matching_value.target_field_id.name, '=',
                                  value))
                             kwargs = {
                                 'matching_model_name': matching_model
                             }
                             matching_model_field_ids = self.low_level_search(
                                 cr,
                                 uid,
                                 ids,
                                 matching_model_upd_key,
                                 context=context,
                                 **kwargs)
                             if matching_model_field_ids:
                                 log_notes = (
                                     "Rules on other models checking:\
                                               record already exists in model '%s';\
                                               field: %s; value: %s - skipping "
                                     % (matching_model,
                                        matching_value.target_field_id.name,
                                        value)), record
                                 context['import_log'].append(log_notes)
                 if matching_model_field_ids:
                     return result
                 else:
                     try:
                         new_rec_id = target_model_pool.create(
                             cr, uid, record, context=context)
                     except Exception, e:
                         raise osv.except_osv(('Error creating record!'), (
                             "Error message: %s\nRow Number: %s\n\nRecord: %s"
                             % (e, row_number, record)))
                     new_rec = target_model_pool.browse(cr, uid, new_rec_id)
                     if getattr(new_rec, target_model_pool._rec_name):
                         log_row_name = getattr(new_rec,
                                                target_model_pool._rec_name)
                     else:
                         log_row_name = ''
                     log_notes = "creating ", target_model_pool._name, "- name = ", new_rec._rec_name, "- data = ", record
                     context['import_log'].append(log_notes)
                     result.append(new_rec_id)
                     return result
             if template.update and upd_key:
                 if template.update_current:
                     upd_key.append(
                         ('create_date', '>', context['time_of_start']))
                 updating_record_id = self.low_level_search(cr,
                                                            uid,
                                                            ids,
                                                            upd_key,
                                                            context=context)
                 if updating_record_id:
                     existing_rec = target_model_pool.browse(
                         cr, uid, updating_record_id)[0]
                     if existing_rec.name:
                         log_row_name = existing_rec.name
                     else:
                         log_row_name = ''
                     if self.need_to_update(cr,
                                            uid,
                                            target_model_pool,
                                            updating_record_id,
                                            record,
                                            context=context):
                         target_model_pool.write(cr,
                                                 uid,
                                                 updating_record_id,
                                                 record,
                                                 context=context)
                         result.append(updating_record_id[0])
                         log_notes = "update ", target_model_pool._name, "- record id = ", updating_record_id, "- name = ", log_row_name, "- data = ", record
                         context['import_log'].append(log_notes)
                     else:
                         log_notes = "no update ", target_model_pool._name, "- record id = ", updating_record_id, "- name = ", log_row_name, "- NO CHANGES REQUIRED - data = ", record
                         context['import_log'].append(log_notes)
                     updated = True
             if not updated and template.create_new and ready_to_create_new:
                 try:
                     new_rec_id = target_model_pool.create(cr,
                                                           uid,
                                                           record,
                                                           context=context)
                 except Exception, e:
                     raise osv.except_osv(('Error creating record!'), (
                         "Error message: %s\nRow Number: %s\n\nRecord: %s" %
                         (e, row_number, record)))
                 new_rec = target_model_pool.browse(cr, uid, new_rec_id)
                 if new_rec._rec_name:
                     log_row_name = new_rec._rec_name
                 else:
                     log_row_name = ''
                 log_notes = "creating ", target_model_pool._name, "- name = ", new_rec._rec_name, "- data = ", record
                 context['import_log'].append(log_notes)
                 result.append(new_rec_id)
Exemplo n.º 51
0
    def create_move_from_st_line(self,
                                 cr,
                                 uid,
                                 st_line_id,
                                 company_currency_id,
                                 next_number,
                                 context=None):
        res = super(account_bank_statement,
                    self).create_move_from_st_line(cr, uid, st_line_id,
                                                   company_currency_id,
                                                   next_number, context)

        res_currency_obj = self.pool.get('res.currency')
        account_move_obj = self.pool.get('account.move')
        account_journal_obj = self.pool.get('account.journal')
        account_move_line_obj = self.pool.get('account.move.line')
        account_bank_statement_line_obj = self.pool.get(
            'account.bank.statement.line')
        st_line = account_bank_statement_line_obj.browse(cr,
                                                         uid,
                                                         st_line_id,
                                                         context=context)
        st = st_line.statement_id

        amount_move = st_line.amount
        amount_tax = 0.0
        if st_line.tax_id:
            precision = self.pool.get('decimal.precision').precision_get(
                cr, uid, 'Account')
            if st_line.amount != round(st_line.amount_net + st_line.amount_tax,
                                       precision):
                raise osv.except_osv(
                    _('Error !'),
                    _('VAT and Amount Net do not match Amount in line "%s"') %
                    st_line.name)
            if st_line.partner_id:
                raise osv.except_osv(
                    _('Error !'),
                    _('Lines "%s" with VAT must not have partner account ') %
                    st_line.name)
            amount_net = res_currency_obj.compute(cr,
                                                  uid,
                                                  company_currency_id,
                                                  st.currency.id,
                                                  st_line.amount_net,
                                                  context=context)

            amount_tax = amount_move - amount_net

            # update amount to amount_net
            bank_debit_account_id = st_line.statement_id.journal_id.default_debit_account_id.id
            bank_credit_account_id = st_line.statement_id.journal_id.default_credit_account_id.id
            move_ids = account_move_line_obj.search(
                cr, uid, [('move_id', '=', res),
                          ('account_id', 'not in',
                           [bank_debit_account_id, bank_debit_account_id])])
            entry_posted = st_line.statement_id.journal_id.entry_posted
            entry_posted_reset = False
            if not entry_posted:
                # to disable the update check
                account_journal_obj.write(cr, uid,
                                          st_line.statement_id.journal_id.id,
                                          {'entry_posted': True})
                entry_posted_reset = True
            if not len(move_ids) == 1:
                raise osv.except_osv(
                    _('Error !'),
                    _('must only find one move line %s"') % st_line.name)
            if amount_tax > 0:
                account_move_line_obj.write(cr, uid, move_ids,
                                            {'credit': amount_net})
            else:
                account_move_line_obj.write(cr, uid, move_ids,
                                            {'debit': -amount_net})
            if entry_posted_reset:
                account_journal_obj.write(cr, uid,
                                          st_line.statement_id.journal_id.id,
                                          {'entry_posted': False})

            # create tax line
            account_move_line_obj.create(
                cr,
                uid, {
                    'name':
                    st_line.name,
                    'date':
                    st_line.date,
                    'ref':
                    st_line.ref,
                    'move_id':
                    res,
                    'partner_id':
                    ((st_line.partner_id) and st_line.partner_id.id) or False,
                    'account_id':
                    st_line.tax_id.account_collected_id.id,
                    'credit': ((amount_tax > 0) and amount_tax) or 0.0,
                    'debit': ((amount_tax < 0) and -amount_tax) or 0.0,
                    'statement_id':
                    st.id,
                    'journal_id':
                    st.journal_id.id,
                    'period_id':
                    st.period_id.id,
                    'currency_id':
                    st.currency.id,
                    'tax_amount':
                    amount_tax,
                    'tax_code_id':
                    st_line.tax_id.tax_code_id.id,
                },
                context=context)

        return res
Exemplo n.º 52
0
 def close_serial_number_wizard(self, cr, uid, ids, context=None):
     psn_obj = self.pool.get('product.serial.number')
     move_obj = self.pool.get('stock.move')
     for move in move_obj.browse(cr, uid, [context['active_id']]):
         if move.product_id.psn == False:
             raise osv.except_osv(
                 _('Error!'),
                 _('Este producto ( %s ) no usa numero de serie!!!') %
                 (move.product_id.default_code))
             return False
         for psnw in self.browse(cr, uid, ids):
             lines = [c for c in psnw.line_ids if c]
             lines.sort()
             ltemp = []
             name_list = []
             for line1 in lines:
                 if line1.name != False and line1.name != "":
                     name_list.append(line1.name)
             for line in lines:
                 if line.name != False and line.name != "":
                     psn_exist = False
                     psn_exist = psn_obj.search(
                         cr, uid, [('name', '=', line.name),
                                   ('product_id', '=', move.product_id.id),
                                   ('active', '=', True)])
                     if psn_exist:
                         psn_reads = False
                         psn_reads = psn_obj.read(cr, uid, psn_exist)
                         psn_read = psn_reads[0]
                         sn_product_tuple_list = []
                         product_ids_reads = []
                         for psnr in psn_reads:
                             temp_list = [psnr['id'], psnr['product_id'][0]]
                             sn_product_tuple_list.append(tuple(temp_list))
                             product_ids_reads.append(psnr['product_id'][0])
                         if move.product_id.id in product_ids_reads \
                         and (move.picking_id.type == 'in') and move.product_id.psn_unique_ftp:
                             raise osv.except_osv(
                                 _('Error!'),
                                 _('El numero de serie (%s) existe para este producto ( %s ) y debe ser unico para el SKU'
                                   ) %
                                 (line.name, move.product_id.default_code))
                             return False
                         elif move.product_id.id in product_ids_reads \
                         and (move.picking_id.type == 'in') and move.product_id.psn_unique:
                             raise osv.except_osv(
                                 _('Error!'),
                                 _('El numero de serie (%s) existe para este producto ( %s ) y debe ser unico.'
                                   ) %
                                 (line.name, move.product_id.default_code))
                             return False
                         elif move.product_id.id not in product_ids_reads and (
                                 move.picking_id.type
                                 in ['internal', 'out']):
                             raise osv.except_osv(
                                 _('Error!'),
                                 _('El numero de serie (%s) no existe para este producto ( %s )'
                                   ) %
                                 (line.name, move.product_id.default_code))
                             return False
                         elif move.picking_id.type in ['internal','out'] and move.product_id.id in product_ids_reads \
                         and not move.product_id.psn_unique and not move.product_id.psn_unique_ftp:
                             veces = name_list.count(line.name)
                             multi_list = []
                             for i in range(veces):
                                 for psn in psn_reads:
                                     if (len(multi_list) < veces) and (
                                             psn['id'] not in ltemp):
                                         ltemp.append(psn['id'])
                                         multi_list.append(psn['id'])
                         else:
                             ltemp.append(int(psn_read['id']))
                     else:
                         if move.picking_id.type == 'in':
                             vals = {
                                 'name': line.name,
                                 'product_id': move.product_id.id,
                                 'expiration_date': psnw.expiration_date,
                             }
                             serialnumber_id = psn_obj.create(
                                 cr, uid, vals, context=context)
                             serialnumber_id = int(serialnumber_id)
                             if serialnumber_id:
                                 ltemp.append(serialnumber_id)
                             else:
                                 raise osv.except_osv(
                                     _('Error!'),
                                     _('El numero de serie %s no puede ser creado'
                                       ) % (vals['name']))
                                 return False
                         else:
                             raise osv.except_osv(
                                 _('Error!'),
                                 _('La serie %s no existe o esta inactiva para este producto (%s), solo se pueden crear series desde una guia de entrada o puede editarlas desde el menu para numeros de serie.'
                                   ) %
                                 (line.name, move.product_id.default_code))
                             return False
             self._check_location(cr, uid, ids, move, ltemp)
             picking_id = move.picking_id.id
             self._check_duplication_in_stock_picking(cr,
                                                      uid,
                                                      ids,
                                                      picking_id,
                                                      ltemp,
                                                      context=context)
         slist = []
         for serialnumber in move.product_serial_number_ids:
             slist.append(serialnumber.id)
         ltemp = ltemp + slist
         ltemp.sort()
         move_obj.write(
             cr, uid, [move.id], {
                 'product_serial_number_ids': [(6, move.id, ltemp)],
                 'product_qty': len(ltemp),
                 'product_uos_qty': len(ltemp)
             })
         psn_obj.write(cr, uid, ltemp, {'state': move.state})
     return {'type': 'ir.actions.act_window_close'}
Exemplo n.º 53
0
 def action_ship_create(self, cr, uid, ids, *args):
     """
    Modified to avoid confirm a sell order that not have lots related
     and generate stock picking and move lines in the company that generate the purchase order
     """
     result = super(sale_order, self).action_ship_create(cr, uid, ids, *args)
     sm_obj = self.pool.get('stock.move')
     picking_obj = self.pool.get('stock.picking')
     company_obj = self.pool.get('res.company')
     lot_obj = self.pool.get('stock.production.lot')
     sale_brw = self.browse(cr, uid, ids, context={})
     company_obj = self.pool.get('res.company')
     company_id = company_obj._company_default_get(cr, uid, 'sale.order')
     company_brws = company_obj.browse(cr,uid,company_id,context={})
     if not sale_brw[0].partner_id.seniat_updated and [i .id for i in sale_brw[0].partner_id.address if i.country_id.code == 'VE']:
         raise osv.except_osv(_('Processing Error'), _('The partner is not updated with seniat'))
     for order in sale_brw:
         if company_brws.company_out_ids:
             for company in company_brws.company_out_ids:
                 if company.id == order.partner_id.id:
                     dest = company.location_stock_id and company.location_stock_id.id
                     orig = company_brws.location_stock_internal_id and company_brws.location_stock_internal_id.id
                     break
                 else:
                     dest = order.shop_id.warehouse_id.lot_output_id and order.shop_id.warehouse_id.lot_output_id.id
                     orig = order.shop_id.warehouse_id.lot_stock_id and order.shop_id.warehouse_id.lot_stock_id.id
         else:
             dest = order.shop_id.warehouse_id.lot_output_id and order.shop_id.warehouse_id.lot_output_id.id
             orig = order.shop_id.warehouse_id.lot_stock_id and order.shop_id.warehouse_id.lot_stock_id.id
         
             
         for ol in order.order_line:
             
             if ol.prod_lot_id.id == False and ol.product_id.stock_driver is ('slab','normal','block','tile'):
                 raise osv.except_osv(_('Processing Error'), _('The line is not lot'))
             
             #~ elif ol.prod_lot_id.stock_move_id:
                 #~ self.create_internal_sale(cr,uid,ids,order,ol,context={})
           #~ 
             for sm in ol.move_ids:
                 sm_obj.write(cr, uid, [sm.id], 
                     {
                     'prodlot_id':ol.prod_lot_id and ol.prod_lot_id.id,
                     'pieces_qty':ol.pieces,
                     'location_id':orig,
                     'location_dest_id':dest,
                     'state':'draft',
                     })
         if order.purchase_order_ids:
             vals = []
             picking_in_ids = picking_obj.search(cr,uid,[('origin','=',order.purchase_order_ids[0].name)],context={})
             picking_out_ids = picking_obj.search(cr,uid,[('origin','=',order.name)],context={})
             picking_in_brw = picking_obj.browse(cr,uid,picking_in_ids[0],context={})
             picking_out_brw = picking_obj.browse(cr,uid,picking_out_ids[0],context={})
            
             for pickin_in in picking_in_brw.move_lines:
                 sm_obj.write(cr,uid,[pickin_in.id],{'state':'draft'},context={})
                 sm_obj.unlink(cr,uid,[pickin_in.id],context=None)
                 
             for picking_out in picking_out_brw.move_lines:
                 print "picking_in_brw.company_id.name",picking_in_brw.company_id.name
                 lot = {
                 'name':picking_out.prodlot_id.name,
                 'product_id':picking_out.prodlot_id.product_id and picking_out.prodlot_id.product_id.id,
                 'length':picking_out.prodlot_id.length,
                 'heigth':picking_out.prodlot_id.heigth,
                 'width':picking_out.prodlot_id.width,
                 'stock_move_id':picking_out.id,
                 'stock_move_in_id':[],
                 'company_id':order.partner_id.id,
                 }
                 lot_new = lot_obj.create(cr, uid, lot, context={})
                 mov_id = sm_obj.create(cr,uid,{'name':picking_in_brw.origin,
                 'product_id':picking_out.product_id and picking_out.product_id.id,
                 'product_qty':picking_out.product_qty,
                 'pieces_qty':picking_out.pieces_qty,
                 'product_uom': picking_out.product_uom.id,
                 'date':picking_out.date,
                 'date_expected':picking_out.date_expected,
                 'state':'draft',
                 'location_id':picking_in_brw.company_id.location_stock_id and picking_in_brw.company_id.location_stock_id.id,
                 'location_dest_id':picking_in_brw.company_id.location_stock_internal_id and picking_in_brw.company_id.location_stock_internal_id.id ,
                 'prodlot_id':lot_new,
                 'company_id':order.partner_id and order.partner_id.id,
                 'picking_id': picking_in_brw and picking_in_brw.id,
                 
                 })
                 lot_obj.write(cr,uid,[lot_new],{'stock_move_in_id':mov_id},context={})
             
     return result
Exemplo n.º 54
0
    def fill_inventory(self, cr, uid, ids, context=None):
        """ To Import stock inventory according to products available in the selected locations.
        @param self: The object pointer.
        @param cr: A database cursor
        @param uid: ID of the user currently logged in
        @param ids: the ID or list of IDs if we want more than one
        @param context: A standard dictionary
        @return:
        """
        if context is None:
            context = {}

        inventory_line_obj = self.pool.get('stock.inventory.line')
        location_obj = self.pool.get('stock.location')
        product_obj = self.pool.get('product.product')
        stock_location_obj = self.pool.get('stock.location')
        move_obj = self.pool.get('stock.move')
        uom_obj = self.pool.get('product.uom')
        if ids and len(ids):
            ids = ids[0]
        else:
             return {'type': 'ir.actions.act_window_close'}
        fill_inventory = self.browse(cr, uid, ids, context=context)
        res = {}
        res_location = {}

        if fill_inventory.recursive:
            location_ids = location_obj.search(cr, uid, [('location_id',
                             'child_of', [fill_inventory.location_id.id])], order="id",
                             context=context)
        else:
            location_ids = [fill_inventory.location_id.id]

        res = {}
        flag = False

        for location in location_ids:
            datas = {}
            res[location] = {}
            inventory_date = fill_inventory.date or context.get('date')
            move_ids = move_obj.search(cr, uid, ['|', ('location_dest_id', '=', location), ('location_id', '=', location),('state','=','done'), ('date', '<=', inventory_date)], context=context)

            for move in move_obj.browse(cr, uid, move_ids, context=context):
                lot_id = move.prodlot_id.id
                prod_id = move.product_id.id
                if move.location_dest_id.id == location:
                    qty = uom_obj._compute_qty(cr, uid, move.product_uom.id,move.product_qty, move.product_id.uom_id.id)
                else:
                    qty = -uom_obj._compute_qty(cr, uid, move.product_uom.id,move.product_qty, move.product_id.uom_id.id)


                if datas.get((prod_id, lot_id)):
                    qty += datas[(prod_id, lot_id)]['product_qty']

                datas[(prod_id, lot_id)] = {'product_id': prod_id, 'location_id': location, 'product_qty': qty, 'product_uom': move.product_id.uom_id.id, 'prod_lot_id': lot_id}

            if datas:
                flag = True
                res[location] = datas

        if not flag:
            raise osv.except_osv(_('Warning !'), _('No product in this location.'))

        for stock_move in res.values():
            for stock_move_details in stock_move.values():
                stock_move_details.update({'inventory_id': context['active_ids'][0]})
                domain = []

                if fill_inventory.set_stock_zero:
                    stock_move_details.update({'product_qty': 0})

                for field, value in stock_move_details.items():
                    domain.append((field, '=', value))

                line_ids = inventory_line_obj.search(cr, uid, domain, context=context)

                if not line_ids:
                    inventory_line_obj.create(cr, uid, stock_move_details, context=context)

        return {'type': 'ir.actions.act_window_close'}
Exemplo n.º 55
0
    def purchase_order(self,cr,uid,ids,context=None):  
        if context is None:
            context = {}
        so_brw = self.browse(cr,uid,ids[0],context=context)
        po_obj = self.pool.get("purchase.order")
        rpa_obj = self.pool.get("res.partner.address")
        partner_id = so_brw.company_id.partner_id.id
        company = self.pool.get('res.users').browse(cr, uid, uid).company_id
        rpa_inv = rpa_obj.search(cr,uid,[('type','=','invoice'),('partner_id','=',partner_id)])
        rpa_ctc = rpa_obj.search(cr,uid,[('type','=','contact'),('partner_id','=',partner_id)])
        rpa_dft = rpa_obj.search(cr,uid,[('type','=','default'),('partner_id','=',partner_id)])
        rpa_shp = rpa_obj.search(cr,uid,[('type','=','delivery'),('partner_id','=',partner_id)])

        partner_invoice_id = rpa_inv and rpa_inv[0]
        ordering_invoice_id = rpa_ctc and rpa_ctc[0] or rpa_ctc and rpa_ctc[0] or rpa_inv and rpa_inv[0]  
        shipping_invoice_id = rpa_shp and rpa_shp[0] or rpa_inv and rpa_inv[0]  
        company_id = self.get_company(cr,uid,ids,context)
        so_line = []
        po_line = []
        for i in so_brw.order_line:
            if i.purchase_order_line_id:
                pass
                #~ pruebas con break
            else:
                date_planned = datetime.now() + relativedelta(days=i.delay or 0.0)
                date_planned = (date_planned - timedelta(days=company.security_lead)).strftime('%Y-%m-%d %H:%M:%S')
                po_line.append((0,0,{'product_id':i.product_id and i.product_id.id,
                                     #~ 'concept_id':i.concept_id and i.concept_id.id,
                                     'product_qty':i.product_uom_qty,
                                     'product_uom':i.product_uom and i.product_uom.id,
                                     'date_planned':date_planned,
                                     'price_unit':i.price_unit,
                                     'pieces':i.pieces,
                                     'prod_lot_id':[],
                                     'company_id':company_id and company_id[0],
                                     'name':i.name,
                                     'sale_order_line_ids':[(4,i.id)],
                                     }))
        so_line.append((4,so_brw.id))

        name = self.pool.get('ir.sequence').get(cr, uid,'purchase.order')
        company_obj = self.pool.get('res.company')
        company_brw = company_obj.browse(cr,uid,company_id[0],context=context)
        if not company_brw.user_in_id:
            raise osv.except_osv(_('Processing Error'), _('The partner need a in user'))
        user = company_brw.user_in_id.id
        values = {
                'partner_id':partner_id,
                'pricelist_id':so_brw.pricelist_id.id,
                'partner_address_id':partner_invoice_id,
                'partner_order_id':ordering_invoice_id,
                'partner_shipping_id':shipping_invoice_id,
                'company_id':company_id and company_id[0],
                'name': name,
                'location_id': company_brw.location_stock_id and company_brw.location_stock_id.id,
                'location_dest_id': company_brw.location_stock_internal_id and company_brw.location_stock_internal_id.id,
                'order_line':po_line,
                'validator':user,
                'user_id':user,
                'sale_order_ids':so_line,
                }
        if po_line:
            po_id = po_obj.create(cr,user,values,context=context)
            po_obj.wkf_confirm_order(cr, user, [po_id], context)
            po_obj.wkf_approve_order(cr, user, [po_id], context)
            po_obj.action_picking_create(cr, user, [po_id], ())
            self.action_ship_create(cr, uid, ids,())
            return po_id
        else:
            return po_line
Exemplo n.º 56
0
    def create_move_from_st_line_v6(self,
                                    cr,
                                    uid,
                                    st_line_id,
                                    company_currency_id,
                                    st_line_number,
                                    context=None):
        if context is None:
            context = {}
        res_currency_obj = self.pool.get('res.currency')
        account_move_obj = self.pool.get('account.move')
        account_move_line_obj = self.pool.get('account.move.line')
        account_bank_statement_line_obj = self.pool.get(
            'account.bank.statement.line')
        st_line = account_bank_statement_line_obj.browse(cr,
                                                         uid,
                                                         st_line_id,
                                                         context=context)
        st = st_line.statement_id

        context.update({'date': st_line.date})

        move_id = account_move_obj.create(cr,
                                          uid, {
                                              'journal_id': st.journal_id.id,
                                              'period_id': st.period_id.id,
                                              'date': st_line.date,
                                              'name': st_line_number,
                                          },
                                          context=context)
        account_bank_statement_line_obj.write(
            cr, uid, [st_line.id], {'move_ids': [(4, move_id, False)]})

        torec = []
        if st_line.amount >= 0:
            account_id = st.journal_id.default_credit_account_id.id
        else:
            account_id = st.journal_id.default_debit_account_id.id

        acc_cur = (
            (st_line.amount <= 0)
            and st.journal_id.default_debit_account_id) or st_line.account_id
        context.update({
            'res.currency.compute.account': acc_cur,
        })
        amount = res_currency_obj.compute(cr,
                                          uid,
                                          st.currency.id,
                                          company_currency_id,
                                          st_line.amount,
                                          context=context)

        # need amount later for bank move line, prepare tax
        amount_move = amount
        amount_tax = 0.0
        move = st_line  # shorter
        if move.tax_id:
            precision = self.pool.get('decimal.precision').precision_get(
                cr, uid, 'Account')
            if move.amount != round(move.amount_net + move.amount_tax,
                                    precision):
                raise osv.except_osv(
                    _('Error !'),
                    _('VAT and Amount Net do not match Amount in line "%s"') %
                    move.name)
            if move.partner_id:
                raise osv.except_osv(
                    _('Error !'),
                    _('Lines "%s" with VAT must not have partner account ') %
                    move.name)
            amount_net = res_currency_obj.compute(cr,
                                                  uid,
                                                  company_currency_id,
                                                  st.currency.id,
                                                  move.amount_net,
                                                  context=context)

            amount_tax = amount - amount_net
            amount = amount_net

        #
        # move line
        #

        val = {
            'name':
            st_line.name,
            'date':
            st_line.date,
            'ref':
            st_line.ref,
            'move_id':
            move_id,
            'partner_id': ((st_line.partner_id) and st_line.partner_id.id)
            or False,
            'account_id': (st_line.account_id) and st_line.account_id.id,
            'credit': ((amount > 0) and amount) or 0.0,
            'debit': ((amount < 0) and -amount) or 0.0,
            'statement_id':
            st.id,
            'journal_id':
            st.journal_id.id,
            'period_id':
            st.period_id.id,
            'currency_id':
            st.currency.id,
            'analytic_account_id':
            st_line.analytic_account_id and st_line.analytic_account_id.id
            or False
        }

        if st.currency.id != company_currency_id:
            amount_cur = res_currency_obj.compute(cr,
                                                  uid,
                                                  company_currency_id,
                                                  st.currency.id,
                                                  amount,
                                                  context=context)
            val['amount_currency'] = -amount_cur

        if st_line.account_id and st_line.account_id.currency_id and st_line.account_id.currency_id.id != company_currency_id:
            val['currency_id'] = st_line.account_id.currency_id.id
            amount_cur = res_currency_obj.compute(
                cr,
                uid,
                company_currency_id,
                st_line.account_id.currency_id.id,
                amount,
                context=context)
            val['amount_currency'] = -amount_cur

        if amount_tax != 0.0 and move.tax_id:
            val['tax_amount'] = amount_net
            val['tax_code_id'] = move.tax_id.base_code_id.id

        move_line_id = account_move_line_obj.create(cr,
                                                    uid,
                                                    val,
                                                    context=context)
        torec.append(move_line_id)

        # VAT Move line
        if amount_tax != 0.0 and move.tax_id:
            account_move_line_obj.create(
                cr,
                uid, {
                    'name': move.name,
                    'date': move.date,
                    'ref': move.ref,
                    'move_id': move_id,
                    'partner_id':
                    ((move.partner_id) and move.partner_id.id) or False,
                    'account_id': move.tax_id.account_collected_id.id,
                    'credit': ((amount_tax > 0) and amount_tax) or 0.0,
                    'debit': ((amount_tax < 0) and -amount_tax) or 0.0,
                    'statement_id': st.id,
                    'journal_id': st.journal_id.id,
                    'period_id': st.period_id.id,
                    'currency_id': st.currency.id,
                    'tax_amount': amount_tax,
                    'tax_code_id': move.tax_id.tax_code_id.id,
                },
                context=context)

        # Fill the secondary amount/currency
        # if currency is not the same than the company
        # Bank Move Line
        # reset amount to what is was before VAT calculation
        amount = amount_move

        amount_currency = False
        currency_id = False
        if st.currency.id != company_currency_id:
            amount_currency = st_line.amount
            currency_id = st.currency.id
        account_move_line_obj.create(
            cr,
            uid, {
                'name': st_line.name,
                'date': st_line.date,
                'ref': st_line.ref,
                'move_id': move_id,
                'partner_id':
                ((st_line.partner_id) and st_line.partner_id.id) or False,
                'account_id': account_id,
                'credit': ((amount < 0) and -amount) or 0.0,
                'debit': ((amount > 0) and amount) or 0.0,
                'statement_id': st.id,
                'journal_id': st.journal_id.id,
                'period_id': st.period_id.id,
                'amount_currency': amount_currency,
                'currency_id': currency_id,
            },
            context=context)

        for line in account_move_line_obj.browse(
                cr,
                uid, [
                    x.id for x in account_move_obj.browse(
                        cr, uid, move_id, context=context).line_id
                ],
                context=context):
            if line.state != 'valid':
                raise osv.except_osv(
                    _('Error !'),
                    _('Journal Item "%s" is not valid') % line.name)

        # Bank statements will not consider boolean on journal entry_posted
        account_move_obj.post(cr, uid, [move_id], context=context)
        return move_id
Exemplo n.º 57
0
    def fill_table(self, cr, uid, ids, context=None):
        loc_obj = self.pool.get('stock.location')
        wizard = self.browse(cr, uid, ids[0], context=context)

        sql = "delete from makloon_card where user_id = %s" % (uid)

        cr.execute(sql)

        makloon_card_id = self.pool.get('makloon.card').create(
            cr, uid, {
                'partner_id': wizard.partner_id.id,
                'date_start': wizard.date_start,
                'date_end': wizard.date_end,
                'user_id': uid
            })

        makloon_obj = self.pool.get('vit.makloon.order')
        #search_makloon = makloon_obj.search(cr,uid,['|',('date_end_completion','>=',wizard.date_start),('date_end_completion','>=',wizard.date_end)])

        cr.execute(
            'SELECT id AS id FROM vit_makloon_order WHERE partner_id = %s AND (date_taking >= %s AND date_taking <= %s) order by date_taking ASC',
            (wizard.partner_id.id, wizard.date_start, wizard.date_end))
        search_makloon = cr.fetchall()
        if not search_makloon:
            raise osv.except_osv(_('Error!'), _('Data not found !'))
        move_obj = self.pool.get('stock.move')
        qty_order_total = 0
        qty_finish_total = 0
        qty_hold_total = 0
        qty_balance_total = 0
        price_balance_total = 0
        date_mk = False
        spk_mk = False
        type_product = False
        for mkl in search_makloon:
            mk = mkl[0]

            makloon = makloon_obj.browse(cr, uid, mk, context=context)
            makloon_model_name = makloon.type_product_id.model_product
            makloon_model_id = makloon.type_product_id.id
            date = makloon.date_end_completion

            s_order = int(makloon.s_order)
            m_order = int(makloon.m_order)
            l_order = int(makloon.l_order)
            xl_order = int(makloon.xl_order)
            xxl_order = int(makloon.xxl_order)
            xxxl_order = int(makloon.xxxl_order)
            #import pdb;pdb.set_trace()
            mv_ids = move_obj.search(cr,
                                     uid, [('origin', '=', makloon.name),
                                           ('type', 'in', ('in', 'internal')),
                                           ('location_dest_id', '=', 29)],
                                     context=context)
            mv_return_ids = move_obj.search(cr,
                                            uid,
                                            [('origin', '=', makloon.name),
                                             ('type', '=', 'out'),
                                             ('location_id', '=', 29),
                                             ('location_dest_id', '=', 7)],
                                            context=context)
            move_reject_ids = move_obj.search(cr,
                                              uid,
                                              [('origin', '=', makloon.name),
                                               ('type', 'in',
                                                ('in', 'internal')),
                                               ('state', '=', 'done'),
                                               ('location_dest_id', '=', 30)],
                                              context=context)
            scrap_location = loc_obj.search(cr, uid,
                                            [('scrap_location', '=', True)])
            scrap = False
            if scrap_location:
                scrap = scrap_location[0]
            move_ids = set(mv_ids + mv_return_ids + move_reject_ids)
            if move_ids:
                s_price_balance = 0
                m_price_balance = 0
                l_price_balance = 0
                xl_price_balance = 0
                xxl_price_balance = 0
                xxxl_price_balance = 0

                s_finish = 0
                s_hold = 0

                m_finish = 0
                m_hold = 0

                l_finish = 0
                l_hold = 0

                xl_finish = 0
                xl_hold = 0

                xxl_finish = 0
                xxl_hold = 0

                xxxl_finish = 0
                xxxl_hold = 0
                move_ids_sorted = sorted(move_ids)
                for move in move_ids_sorted:
                    move = move_obj.browse(cr, uid, move, context=context)
                    product_name = move.product_id.name
                    backorder = move.picking_id.backorder_id
                    state = move.state
                    #import pdb;pdb.set_trace()
                    # jika finish good
                    if state == 'done' and move.location_dest_id.id == 29:
                        if move.location_id.id != scrap:
                            if product_name == makloon_model_name + ' S' or product_name == makloon_model_name + ' S - B' or product_name == makloon_model_name + ' S - C' or product_name == makloon_model_name + ' 2':
                                product_qty = move.product_qty
                                s_finish += product_qty
                            if product_name == makloon_model_name + ' M' or product_name == makloon_model_name + ' M - B' or product_name == makloon_model_name + ' M - C' or product_name == makloon_model_name + ' 4':
                                product_qty = move.product_qty
                                m_finish += product_qty
                            if product_name == makloon_model_name + ' L' or product_name == makloon_model_name + ' L - B' or product_name == makloon_model_name + ' L - C' or product_name == makloon_model_name + ' 6':
                                product_qty = move.product_qty
                                l_finish += product_qty
                            if product_name == makloon_model_name + ' XL' or product_name == makloon_model_name + ' XL - B' or product_name == makloon_model_name + ' XL - C' or product_name == makloon_model_name + ' 8':
                                product_qty = move.product_qty
                                xl_finish += product_qty
                            if product_name == makloon_model_name + ' XXL' or product_name == makloon_model_name + ' XXL - B' or product_name == makloon_model_name + ' XXL - C' or product_name == makloon_model_name + ' 10':
                                product_qty = move.product_qty
                                xxl_finish += product_qty
                            if product_name == makloon_model_name + ' XXXL' or product_name == makloon_model_name + ' XXXL - B' or product_name == makloon_model_name + ' XXXL - C' or product_name == makloon_model_name + ' 12':
                                product_qty = move.product_qty
                                xxxl_finish += product_qty
                    # jika retur
                    if state == 'done' and move.location_id.id == 29 and move.location_dest_id.id == 7:
                        if move.location_id.id != scrap:
                            if product_name == makloon_model_name + ' S' or product_name == makloon_model_name + ' S - B' or product_name == makloon_model_name + ' S - C' or product_name == makloon_model_name + ' 2':
                                product_qty = move.product_qty
                                s_finish -= product_qty
                            if product_name == makloon_model_name + ' M' or product_name == makloon_model_name + ' M - B' or product_name == makloon_model_name + ' M - C' or product_name == makloon_model_name + ' 4':
                                product_qty = move.product_qty
                                m_finish -= product_qty
                            if product_name == makloon_model_name + ' L' or product_name == makloon_model_name + ' L - B' or product_name == makloon_model_name + ' L - C' or product_name == makloon_model_name + ' 6':
                                product_qty = move.product_qty
                                l_finish -= product_qty
                            if product_name == makloon_model_name + ' XL' or product_name == makloon_model_name + ' XL - B' or product_name == makloon_model_name + ' XL - C' or product_name == makloon_model_name + ' 8':
                                product_qty = move.product_qty
                                xl_finish -= product_qty
                            if product_name == makloon_model_name + ' XXL' or product_name == makloon_model_name + ' XXL - B' or product_name == makloon_model_name + ' XXL - C' or product_name == makloon_model_name + ' 10':
                                product_qty = move.product_qty
                                xxl_finish -= product_qty
                            if product_name == makloon_model_name + ' XXXL' or product_name == makloon_model_name + ' XXXL - B' or product_name == makloon_model_name + ' XXXL - C' or product_name == makloon_model_name + ' 12':
                                product_qty = move.product_qty
                                xxxl_finish -= product_qty

                    # jika incoming hold
                    elif move.location_dest_id.id == 30:
                        if product_name == makloon_model_name + ' S' or product_name == makloon_model_name + ' S - B' or product_name == makloon_model_name + ' S - C' or product_name == makloon_model_name + ' 2':
                            product_qty = move.product_qty
                            s_hold += product_qty
                        if product_name == makloon_model_name + ' M' or product_name == makloon_model_name + ' M - B' or product_name == makloon_model_name + ' M - C' or product_name == makloon_model_name + ' 4':
                            product_qty = move.product_qty
                            m_hold += product_qty
                        if product_name == makloon_model_name + ' L' or product_name == makloon_model_name + ' L - B' or product_name == makloon_model_name + ' L - C' or product_name == makloon_model_name + ' 6':
                            product_qty = move.product_qty
                            l_hold += product_qty
                        if product_name == makloon_model_name + ' XL' or product_name == makloon_model_name + ' XL - B' or product_name == makloon_model_name + ' XL - C' or product_name == makloon_model_name + ' 8':
                            product_qty = move.product_qty
                            xl_hold += product_qty
                        if product_name == makloon_model_name + ' XXL' or product_name == makloon_model_name + ' XXL - B' or product_name == makloon_model_name + ' XXL - C' or product_name == makloon_model_name + ' 10':
                            product_qty = move.product_qty
                            xxl_hold += product_qty
                        if product_name == makloon_model_name + ' XXXL' or product_name == makloon_model_name + ' XXXL - B' or product_name == makloon_model_name + ' XXXL - C' or product_name == makloon_model_name + ' 12':
                            product_qty = move.product_qty
                            xxxl_hold += product_qty

                s_qty_balance = 0
                s_price_balance = 0
                if s_order != 0:

                    s_qty_balance = s_order - (s_finish + s_hold)
                    s_price_balance = (makloon.avg_qty_total_wip_spk_cut +
                                       makloon.avg_qty_acc_total) * (
                                           s_order - (s_finish + s_hold))
                    self.create_makloon_card_detail(cr, uid, makloon_card_id,
                                                    date, mk, makloon_model_id,
                                                    'S', s_order, s_finish,
                                                    s_hold, s_qty_balance,
                                                    s_price_balance, context)
                    qty_order_total += s_order
                    qty_finish_total += s_finish
                    qty_hold_total += s_hold
                    qty_balance_total += s_qty_balance
                    price_balance_total += s_price_balance
                    date = False
                    mk = False
                    makloon_model_id = False

                m_qty_balance = 0
                m_price_balance = 0
                if m_order != 0:
                    m_qty_balance = m_order - (m_finish + m_hold)
                    m_price_balance = (makloon.avg_qty_total_wip_spk_cut +
                                       makloon.avg_qty_acc_total) * (
                                           m_order - (m_finish + m_hold))
                    self.create_makloon_card_detail(cr, uid, makloon_card_id,
                                                    date, mk, makloon_model_id,
                                                    'M', m_order, m_finish,
                                                    m_hold, m_qty_balance,
                                                    m_price_balance, context)
                    qty_order_total += m_order
                    qty_finish_total += m_finish
                    qty_hold_total += m_hold
                    qty_balance_total += m_qty_balance
                    price_balance_total += m_price_balance
                    date = False
                    mk = False
                    makloon_model_id = False

                l_qty_balance = 0
                l_price_balance = 0
                if l_order != 0:
                    l_qty_balance = l_order - (l_finish + l_hold)
                    l_price_balance = (makloon.avg_qty_total_wip_spk_cut +
                                       makloon.avg_qty_acc_total) * (
                                           l_order - (l_finish + l_hold))
                    self.create_makloon_card_detail(cr, uid, makloon_card_id,
                                                    date, mk, makloon_model_id,
                                                    'L', l_order, l_finish,
                                                    l_hold, l_qty_balance,
                                                    l_price_balance, context)
                    qty_order_total += l_order
                    qty_finish_total += l_finish
                    qty_hold_total += l_hold
                    qty_balance_total += l_qty_balance
                    price_balance_total += l_price_balance
                    date = False
                    mk = False
                    makloon_model_id = False

                xl_qty_balance = 0
                xl_price_balance = 0
                if xl_order != 0:
                    xl_qty_balance = xl_order - (xl_finish + xl_hold)
                    xl_price_balance = (makloon.avg_qty_total_wip_spk_cut +
                                        makloon.avg_qty_acc_total) * (
                                            xl_order - (xl_finish + xl_hold))
                    self.create_makloon_card_detail(cr, uid, makloon_card_id,
                                                    date, mk, makloon_model_id,
                                                    'XL', xl_order, xl_finish,
                                                    xl_hold, xl_qty_balance,
                                                    xl_price_balance, context)
                    qty_order_total += xl_order
                    qty_finish_total += xl_finish
                    qty_hold_total += xl_hold
                    qty_balance_total += xl_qty_balance
                    price_balance_total += xl_price_balance
                    date = False
                    mk = False
                    makloon_model_id = False

                xxl_qty_balance = 0
                xxl_price_balance = 0
                if xxl_order != 0:
                    xxl_qty_balance = xxl_order - (xxl_finish + xxl_hold)
                    xxl_price_balance = (makloon.avg_qty_total_wip_spk_cut +
                                         makloon.avg_qty_acc_total) * (
                                             xxl_order -
                                             (xxl_finish + xxl_hold))
                    self.create_makloon_card_detail(cr, uid, makloon_card_id,
                                                    date, mk, makloon_model_id,
                                                    'XXL', xxl_order,
                                                    xxl_finish, xxl_hold,
                                                    xxl_qty_balance,
                                                    xxl_price_balance, context)
                    qty_order_total += xxl_order
                    qty_finish_total += xxl_finish
                    qty_hold_total += xxl_hold
                    qty_balance_total += xxl_qty_balance
                    price_balance_total += xxl_price_balance
                    date = False
                    mk = False
                    makloon_model_id = False

                xxxl_qty_balance = 0
                xxxl_price_balance = 0
                if xxxl_order != 0:
                    xxxl_qty_balance = xxxl_order - (xxxl_finish + xxxl_hold)
                    xxxl_price_balance = (makloon.avg_qty_total_wip_spk_cut +
                                          makloon.avg_qty_acc_total) * (
                                              xxxl_order -
                                              (xxxl_finish + xxxl_hold))
                    self.create_makloon_card_detail(
                        cr, uid, makloon_card_id, date, mk, makloon_model_id,
                        'XXXL', xxxl_order, xxxl_finish, xxxl_hold,
                        xxxl_qty_balance, xxxl_price_balance, context)
                    qty_order_total += xxxl_order
                    qty_finish_total += xxxl_finish
                    qty_hold_total += xxxl_hold
                    qty_balance_total += xxxl_qty_balance
                    price_balance_total += xxxl_price_balance
                    date = False
                    mk = False
                    makloon_model_id = False

                self.pool.get('makloon.card.detail').create(
                    cr,
                    uid, {
                        'makloon_card_id':
                        makloon_card_id,
                        'size':
                        'SUB TOTAL',
                        'total_mkl':
                        s_order + m_order + l_order + xl_order + xxl_order +
                        xxxl_order,
                        'total_finish':
                        s_finish + m_finish + l_finish + xl_finish +
                        xxl_finish + xxxl_finish,
                        'total_hold':
                        s_hold + m_hold + l_hold + xl_hold + xxl_hold +
                        xxxl_hold,
                        'qty_balance':
                        s_qty_balance + m_qty_balance + l_qty_balance +
                        xl_qty_balance + xxl_qty_balance + xxxl_qty_balance,
                        'price_balance':
                        s_price_balance + m_price_balance + l_price_balance +
                        xl_price_balance + xxl_price_balance +
                        xxxl_price_balance
                    },
                    context=context)
                self.pool.get('makloon.card.detail').create(
                    cr,
                    uid, {
                        'makloon_card_id': makloon_card_id,
                        'size': '---',
                        'total_mkl': False,
                        'total_finish': False,
                        'total_hold': False,
                        'qty_balance': False,
                        'price_balance': False,
                    },
                    context=context)
        self.pool.get('makloon.card').write(
            cr, uid, makloon_card_id, {
                'total_order': qty_order_total,
                'total_finish': qty_finish_total,
                'total_hold': qty_hold_total,
                'total_qty': qty_balance_total,
                'total_balance': price_balance_total
            })
        view_ref = self.pool.get('ir.model.data').get_object_reference(
            cr, uid, 'vit_makloon_card', 'vit_makloon_card_form')
        view_id = view_ref and view_ref[1] or False,

        desc = 'Makloon Card'
        domain = []
        context = {}

        return self.hasil(cr, uid, desc, makloon_card_id, view_id, domain,
                          context)
Exemplo n.º 58
0
    def create_internal_sale(self,cr,uid,ids,order_id,line_id,context=None):
        """
        Create a new picking for lots assigned for CONSIGNMENT and that is in a sale order
        @param order_id browse of sale order
        @param line_id browse of sale order line
        """
        if context == None: context = {}
        sm_obj = self.pool.get('stock.move')
        picking_obj = self.pool.get('stock.picking')
        company_obj = self.pool.get('res.company')
        res_address_obj = self.pool.get('res.partner.address')
        company_id = company_obj._company_default_get(cr, uid, 'sale.order', context=context),
        company_brw = company_obj.browse(cr,uid,company_id[0],context=context)
        picking_origin = picking_sale = []
        sm_in_brw = sm_obj.browse(cr,uid,line_id.prod_lot_id.stock_move_in_id.id,context=context)
        if sm_in_brw.state == 'draft':

            if line_id.quantity <= sm_in_brw.product_qty:
                vals = {
                'product_qty': sm_in_brw.product_qty - line_id.quantity,
                'pieces_qty': sm_in_brw.pieces_qty - line_id.pieces,}
                
                sm_obj.write(cr,uid,[line_id.prod_lot_id.stock_move_id.id],vals,context=context)
                sm_obj.write(cr,uid,[line_id.prod_lot_id.stock_move_in_id.id],vals,context=context)

            if line_id.quantity > sm_in_brw.product_qty:
                raise osv.except_osv(_('Invalid action !'), _('The quantity is greater than available!'))
            picking_ids_out = picking_obj.search(cr,uid,[('state_rw','=',1),('company_id','=',company_id[0])],context=context)
            picking_ids = picking_obj.search(cr,uid,[('state_rw','=',1),('company_id','=',line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.id)],context=context)
            address_in = res_address_obj.search(cr,uid,[('partner_id','=',line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.partner_id.id)],context=context)
            address_out = res_address_obj.search(cr,uid,[('partner_id','=',company_brw.id)],context=context)
            if picking_ids_out and picking_ids:
#-----------------------------Acropolis Picking -------------------------------------------------------------  
                picking_in_id = picking_ids_out[0]
                picking_in_brw = picking_obj.browse(cr,uid,picking_in_id,context=context)
                picking_obj.write(cr,uid,[picking_in_id],{'state_rw':0},context=context)
                pick_out = { 'product_qty':line_id.quantity,'pieces_qty':line_id.pieces,'picking_id':picking_in_id,
                    'state':'done',
                    'location_dest_id':line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.location_stock_internal_id and line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.location_stock_internal_id.id,
                    'location_id':company_brw.location_stock_internal_id and company_brw.location_stock_internal_id.id,
                    'note':
u"""
%s
\n Recibido el producto %s desde %s el dia %s
""" %(picking_in_brw.note,line_id.product_id.name,line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.name,time.strftime('%d/%m/%Y')),
                    }
#~----------------------------Tecvemar Picking-------------------------------------------------------- 
                picking_id = picking_ids[0]
                picking_ids_brw = picking_obj.browse(cr,uid,picking_id,context=context)
                picking_obj.write(cr,uid,[picking_id],{'state_rw':0},context=context)
                pick_in = {'product_qty':line_id.quantity,'pieces_qty':line_id.pieces,'picking_id':picking_id,
                'state':'done',
                'location_dest_id':company_brw.location_stock_internal_id and company_brw.location_stock_internal_id.id,
                'location_id':line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.location_stock_internal_id and line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.location_stock_internal_id.id,
                'note':
u"""
%s
\n Enviado el producto %s hacia el acropolis %s el dia %s
""" %(picking_ids_brw.note,line_id.product_id.name,line_id.prod_lot_id.company_id.name,time.strftime('%d/%m/%Y'))
                }
            else:
#~ ----------------------------Picking Acropolis----------------------------------------------------------------
              
                pick_name_in = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.in')
                picking_in_id = picking_obj.create(cr, uid, {
                    'name': pick_name_in,
                    'origin': order_id.name+((order_id.origin and (':'+order_id.origin)) or ''),
                    'type': 'in','address_id': address_in[0],'invoice_state': '2binvoiced','state_rw': 0,
                    'purchase_id': [],
                    'note':
u"""
Picking generados por consignación el dia %s
Transacción generada entre %s ------> %s
""" %(time.strftime('%d/%m/%Y'),line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.name,line_id.prod_lot_id.company_id.name),
                    'company_id': company_id[0],
                    'move_lines' : [], })
               
                pick_out = {
                'product_qty':line_id.quantity,'pieces_qty':line_id.pieces,'picking_id':picking_in_id,
                'state':'done',
                'location_dest_id':company_brw.location_stock_internal_id and company_brw.location_stock_internal_id.id,
                'location_id':line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.location_stock_internal_id and line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.location_stock_internal_id.id,
                }
                
#~-------------------------Tecvemar Picking-------------------------------------------------------------------
              
                pick_name = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out')
                picking_id = picking_obj.create(cr, uid, {
                    'name': pick_name,
                    'origin': order_id.name+((order_id.origin and (':'+order_id.origin)) or ''),
                    'type': 'out', 'address_id': address_out[0],'invoice_state': '2binvoiced','state_rw': 0,
                    'sale_id': [],
                    'note':
u"""
Picking generados por consignación el dia %s
Transacción generada entre %s ------> %s
""" %(time.strftime('%d/%m/%Y'),line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.name,line_id.prod_lot_id.company_id.name),
                    'company_id': line_id.prod_lot_id.stock_move_id.prodlot_id.company_id and line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.id,
                    'move_lines' : [],})
              
                pick_in = {'product_qty':line_id.quantity,'pieces_qty':line_id.pieces,'picking_id':picking_id,
                'state':'draft',
                'location_dest_id':company_brw.location_stock_internal_id and company_brw.location_stock_internal_id.id,
                'location_id':line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.location_stock_internal_id and line_id.prod_lot_id.stock_move_id.prodlot_id.company_id.location_stock_internal_id.id,
                }
            sm_obj.copy(cr,uid,line_id.prod_lot_id.stock_move_id.id,pick_in,context=context)
            sm_obj.copy(cr,uid,line_id.prod_lot_id.stock_move_in_id.id,pick_out,context=context)
            picking_origin.append((4,picking_id))
            picking_sale.append((4,picking_in_id))
            picking_obj.write(cr,uid,[picking_in_id],{'picking_origin_ids':picking_origin,'state_rw':1},context=context)
            picking_obj.write(cr,uid,[picking_id],{'picking_sale_ids':picking_sale,'state_rw':1},context=context)

        return True
Exemplo n.º 59
0
    def compute_refund(self, cr, uid, ids, mode='refund', context=None):
        """
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param ids: the account invoice refund’s ID or list of IDs

        """
        inv_obj = self.pool.get('account.invoice')
        reconcile_obj = self.pool.get('account.move.reconcile')
        account_m_line_obj = self.pool.get('account.move.line')
        mod_obj = self.pool.get('ir.model.data')
        act_obj = self.pool.get('ir.actions.act_window')
        wf_service = netsvc.LocalService('workflow')
        inv_tax_obj = self.pool.get('account.invoice.tax')
        inv_line_obj = self.pool.get('account.invoice.line')
        res_users_obj = self.pool.get('res.users')
        if context is None:
            context = {}

        for form in self.browse(cr, uid, ids, context=context):
            created_inv = []
            date = False
            period = False
            description = False
            company = res_users_obj.browse(cr, uid, uid,
                                           context=context).company_id
            journal_id = form.journal_id.id
            for inv in inv_obj.browse(cr,
                                      uid,
                                      context.get('active_ids'),
                                      context=context):
                if inv.state in ['draft', 'proforma2', 'cancel']:
                    raise osv.except_osv(
                        _('Error !'),
                        _('Can not %s draft/proforma/cancel invoice.') %
                        (mode))
                if inv.reconciled and mode in ('cancel', 'modify'):
                    raise osv.except_osv(
                        _('Error !'),
                        _('Can not %s invoice which is already reconciled, invoice should be unreconciled first. You can only Refund this invoice'
                          ) % (mode))
                if form.period.id:
                    period = form.period.id
                else:
                    period = inv.period_id and inv.period_id.id or False

                if not journal_id:
                    journal_id = inv.journal_id.id

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

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

                refund_id = inv_obj.refund(cr, uid, [inv.id], date, period,
                                           description, journal_id)
                refund = inv_obj.browse(cr, uid, refund_id[0], context=context)
                inv_obj.write(cr, uid, [refund.id], {
                    'date_due': date,
                    'check_total': inv.check_total
                })
                inv_obj.button_compute(cr, uid, refund_id)

                created_inv.append(refund_id[0])
                if mode in ('cancel', 'modify'):
                    movelines = inv.move_id.line_id
                    to_reconcile_ids = {}
                    for line in movelines:
                        if line.account_id.id == inv.account_id.id:
                            to_reconcile_ids[line.account_id.id] = [line.id]
                        if type(line.reconcile_id) != osv.orm.browse_null:
                            reconcile_obj.unlink(cr, uid, line.reconcile_id.id)
                    wf_service.trg_validate(uid, 'account.invoice', \
                                        refund.id, 'invoice_open', cr)
                    refund = inv_obj.browse(cr,
                                            uid,
                                            refund_id[0],
                                            context=context)
                    for tmpline in refund.move_id.line_id:
                        if tmpline.account_id.id == inv.account_id.id:
                            to_reconcile_ids[tmpline.account_id.id].append(
                                tmpline.id)
                    for account in to_reconcile_ids:
                        account_m_line_obj.reconcile(
                            cr,
                            uid,
                            to_reconcile_ids[account],
                            writeoff_period_id=period,
                            writeoff_journal_id=inv.journal_id.id,
                            writeoff_acc_id=inv.account_id.id)
                    if mode == 'modify':
                        invoice = inv_obj.read(
                            cr,
                            uid, [inv.id], [
                                'name', 'type', 'number', 'reference',
                                'comment', 'date_due', 'partner_id',
                                'address_contact_id', 'address_invoice_id',
                                'partner_insite', 'partner_contact',
                                'partner_ref', 'payment_term', 'account_id',
                                'currency_id', 'invoice_line', 'tax_line',
                                'journal_id', 'period_id'
                            ],
                            context=context)
                        invoice = invoice[0]
                        del invoice['id']
                        invoice_lines = inv_line_obj.read(
                            cr, uid, invoice['invoice_line'], context=context)
                        invoice_lines = inv_obj._refund_cleanup_lines(
                            cr, uid, invoice_lines)
                        tax_lines = inv_tax_obj.read(cr,
                                                     uid,
                                                     invoice['tax_line'],
                                                     context=context)
                        tax_lines = inv_obj._refund_cleanup_lines(
                            cr, uid, tax_lines)
                        invoice.update({
                            'type': inv.type,
                            'date_invoice': date,
                            'state': 'draft',
                            'number': False,
                            'invoice_line': invoice_lines,
                            'tax_line': tax_lines,
                            'period_id': period,
                            'name': description
                        })
                        for field in ('address_contact_id',
                                      'address_invoice_id', 'partner_id',
                                      'account_id', 'currency_id',
                                      'payment_term', 'journal_id'):
                            invoice[
                                field] = invoice[field] and invoice[field][0]
                        inv_id = inv_obj.create(cr, uid, invoice, {})
                        if inv.payment_term.id:
                            data = inv_obj.onchange_payment_term_date_invoice(
                                cr, uid, [inv_id], inv.payment_term.id, date)
                            if 'value' in data and data['value']:
                                inv_obj.write(cr, uid, [inv_id], data['value'])
                        created_inv.append(inv_id)
            xml_id = (inv.type == 'out_refund') and 'action_invoice_tree1' or \
                     (inv.type == 'in_refund') and 'action_invoice_tree2' or \
                     (inv.type == 'out_invoice') and 'action_invoice_tree3' or \
                     (inv.type == 'in_invoice') and 'action_invoice_tree4'
            result = mod_obj.get_object_reference(cr, uid, 'account', xml_id)
            id = result and result[1] or False
            result = act_obj.read(cr, uid, id, context=context)
            invoice_domain = eval(result['domain'])
            invoice_domain.append(('id', 'in', created_inv))
            result['domain'] = invoice_domain
            return result
Exemplo n.º 60
0
 def _validate_split(self, cr, uid, ids, context):
     for item in self.browse(cr, uid, ids, context={}):
         if not item.debit:
             raise osv.except_osv(
                 _('Error!'),
                 _('Please select some debits'))
         if not item.credit:
             raise osv.except_osv(
                 _('Error!'),
                 _('Please select some credits'))
         sel_count, split_count, not_sel = 0, 0, 0
         for line in item.line_ids:
             if line.select:
                 sel_count += 1
             else:
                 not_sel += 1
             if line.split:
                 split_count += 1
                 if line.move_line_id.invoice:
                     raise osv.except_osv(
                         _('Error!'),
                         _('Can\'t split a line related to invoice'))
                 if line.move_line_id.period_id.state != 'draft':
                     raise osv.except_osv(
                         _('Error!'),
                         _('Can\'t split lines while accounting period ' +
                           'is closed (%s)') %
                           line.move_line_id.period_id.name)
                 if not line.select:
                     raise osv.except_osv(
                         _('Error!'),
                         _('Must select line to be splited'))
                 if (item.balance > 0 and line.debit < item.balance) or \
                         (item.balance < 0 and line.credit > item.balance):
                     raise osv.except_osv(
                         _('Error!'),
                         _('Invalid line to split'))
         if not not_sel:
             raise osv.except_osv(
                 _('Error!'),
                 _('Can\'t select all lines'))
         if sel_count < 1:
             raise osv.except_osv(
                 _('Error!'),
                 _('Must select at least 2 lines'))
         if split_count > 1:
             raise osv.except_osv(
                 _('Error!'),
                 _('Can\'t split more than 1 line'))
         if split_count == 1 and not item.balance:
             raise osv.except_osv(
                 _('Error!'),
                 _('No amount to split'))
         if split_count == 0 and item.balance:
             raise osv.except_osv(
                 _('Error!'),
                 _('Must select one line to split'))
     return True