def _open_window_selected_partners(self, cr, uid, data, context):
        mod_obj = pooler.get_pool(cr.dbname).get('ir.model.data')
        act_obj = pooler.get_pool(cr.dbname).get('ir.actions.act_window')

        result = mod_obj._get_id(cr, uid, 'base', 'action_partner_form')
        list_ids = []

        if data['form']['select'] == 'lines':
            if not data['form']['amount']:
                raise wizard.except_wizard('Warning','Amount should be greater than zero')
            cr.execute("select distinct(partner_id) from account_move_line where credit>=%f and (date between to_date(%s,'yyyy-mm-dd') and to_date(%s,'yyyy-mm-dd')) and (partner_id is not null)", (data['form']['amount'], data['form']['date_from'], data['form']['date_to']))
            entry_lines = cr.fetchall()

            entry_ids = [x[0] for x in  entry_lines]
            a_id = pooler.get_pool(cr.dbname).get('res.partner').read(cr, uid, entry_ids, ['membership_state'])

            for i in range(0, len(a_id)):
                if a_id[i]['membership_state'] == data['form']['member_state']:
                    list_ids.append(a_id[i]['id'])
        else:
            cr.execute("select distinct(partner_id),section_id,state from crm_case where section_id=%d and state=%s and (partner_id is not null)", (data['form']['section'], data['form']['state']))
            p_ids = cr.fetchall()
            list_ids = [x[0] for x in p_ids]


        id = mod_obj.read(cr, uid, [result], ['res_id'])[0]['res_id']
        result = act_obj.read(cr, uid, [id])[0]

        if data['form']['removing_from_list']:
            result['domain'] = [('id', 'in', list_ids)]
        else:
            result['domain'] = [('id', 'not in', list_ids)]
#       result['context'] = ({'id': entry_ids})
        return result
def _delivery_set(self, cr, uid, data, context):
    order_obj = pooler.get_pool(cr.dbname).get('purchase.order')
    line_obj = pooler.get_pool(cr.dbname).get('purchase.order.line')
    order_objs = order_obj.browse(cr, uid, data['ids'], context)

    for order in order_objs:
#        if not order.dest_address_id:
#            raise wizard.except_wizard('Destination Address is not selected', 'Please select Destination Address for the purchase order')
        grid_id = pooler.get_pool(cr.dbname).get('delivery.carrier').grid_get(cr, uid, [data['form']['carrier_id']],order.partner_address_id.id)
        if not grid_id:
            raise wizard.except_wizard('No grid avaible !', 'No grid matching for this carrier !')
        grid_obj = pooler.get_pool(cr.dbname).get('delivery.grid')
        grid = grid_obj.browse(cr, uid, [grid_id])[0]

        line_obj.create(cr, uid, {
            'order_id': order.id,
            'name': grid.carrier_id.name,
            'product_qty': 1,
            'product_uom': grid.carrier_id.product_id.uom_id.id,
            'product_id': grid.carrier_id.product_id.id,
            'price_unit': grid_obj.get_price(cr, uid, grid.id, order, time.strftime('%Y-%m-%d'), context={'object':'purchase'}),
            'taxes_id': [(6,0,[ x.id for x in grid.carrier_id.product_id.taxes_id])],
            'date_planned':(date.today() + timedelta(days=1)).strftime('%Y-%m-%d'),

            })

    return {}
    def _get_text(self, partner, followup_id, context=None):
        fp_obj = pooler.get_pool(self.cr.dbname).get('account_followup.followup')
        fp_line = fp_obj.browse(self.cr, self.uid, followup_id).followup_line
        li_delay = []
        for line in fp_line:
            li_delay.append(line.delay)
        li_delay.sort(reverse=True)
        text = ""
        a = {}
        partner_line = pooler.get_pool(self.cr.dbname).get('account.move.line').search(self.cr, self.uid, [('partner_id','=',partner.id),('reconcile_id','=',False)])
        partner_delay = []
        context={}
        context.update({'lang': partner.lang})
        for i in pooler.get_pool(self.cr.dbname).get('account.move.line').browse(self.cr, self.uid, partner_line, context):
            for delay in li_delay:
                if  i.followup_line_id and str(i.followup_line_id.delay)==str(delay):
                    text = i.followup_line_id.description
                    a[delay] = text
                    partner_delay.append(delay)
        text = partner_delay and a[max(partner_delay)] or ''
        if text:
            text = text % {
                'partner_name': partner.name,
                'date': time.strftime('%Y-%m-%d'),
                'company_name': fp_obj.browse(self.cr, self.uid, followup_id).company_id.name,
                'user_signature': pooler.get_pool(self.cr.dbname).get('res.users').browse(self.cr, self.uid, self.uid, context).signature,
            }

        return text
	def _get_default_values(self, cr, uid, data, context):
		fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear')
		data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid)
		period_obj = pooler.get_pool(cr.dbname).get('account.period')
		data['form']['period_id'] = period_obj.find(cr, uid, dt=time.strftime('%Y-%m-%d'))[0]
		data['form']['date_move'] = time.strftime('%Y-%m-%d')
		return data['form']
 def get_currency_rate(self, cr, uid, ids=[], context={}):
     cur_obj = pooler.get_pool(cr.dbname).get('res.currency')
     cur_rate_obj = pooler.get_pool(cr.dbname).get('res.currency.rate')
     com_obj = pooler.get_pool(cr.dbname).get('res.company')
     
     companies = com_obj.search(cr, uid, [])
     for company in companies:
         code = com_obj.browse(cr, uid, company).currency_id.code
         
         cur_ids = cur_obj.search(cr, uid, [('company_id','=',company)])
         for cur in cur_obj.browse(cr, uid, cur_ids):
             if code==cur.code:
                 continue
             urldata = {'FromCurrency':code, 'ToCurrency':cur.code ,'method':'GET'}
             data = urllib.urlencode(urldata)
             req = urllib2.Request('http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate',data)
             
             try:
                 response = urllib2.urlopen(req)
             except Exception, e:
                 logger.notifyChannel('Error : ', e)
             
             data = response.read()
             xmldoc = minidom.parseString(data)
             rate = xmldoc.documentElement.firstChild.nodeValue
     
             if rate:
                 date = time.strftime('%Y-%m-%d')
                 if cur.base==False:
                     cur_rate_obj.create(cr, uid, {'name': date , 'rate':rate, 'currency_id': cur.id})
示例#6
0
def _create_duplicate(self, cr, uid, data, context):
    event_obj=pooler.get_pool(cr.dbname).get('event.event')
    project_obj = pooler.get_pool(cr.dbname).get('project.project')
    duplicate_project_id= project_obj.copy(cr, uid,data['form']['project_id'], {'active': True})
    project_obj.write(cr, uid, [duplicate_project_id], {'name': "copy of " + project_obj.browse(cr, uid, duplicate_project_id, context).name , 'date_start':time.strftime('%Y-%m-%d'),'date_end': event_obj.browse(cr, uid, [data['id']])[0].date_begin[0:10] })
    event_obj.write(cr, uid, [data['id']], {'project_id': duplicate_project_id })
    return {}
 def print_action(self, cr, uid, data, context):
     """
     Sets the printing template (as selected by the user) before printing.
     """
     pool_ba_report = pooler.get_pool(cr.dbname).get('account.balance.reporting')
     rpt_facade = pooler.get_pool(cr.dbname).get('ir.actions.report.xml')
     vals={}
     if context.get('report_xml_id'):
         report_xml_id = context['report_xml_id']
         report_xml_ids = rpt_facade.search(cr, uid, [('id', '=', report_xml_id)])
         report_xml_id = report_xml_ids and report_xml_ids[0] or None
         if report_xml_id:
             report_xml = rpt_facade.browse(cr, uid, [report_xml_id])[0]
             datas={
                 'ids': [context['report_id']],
                 'model': 'account.balance.reporting'
             }
         reports_ids = pool_ba_report.search(cr, uid, [('id', '=', context['report_id'])])
         if reports_ids:
             print reports_ids
             report_instance = pool_ba_report.browse(cr, uid, reports_ids[0])
             if report_instance.calc_date:
                 print report_instance.calc_date
                 vals = {'type': 'ir.actions.report.xml','report_name': report_xml.report_name, 'datas':datas,}
     return vals
 def _get_defaults(self, cr, uid, data, context):
     fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear')
     period_obj = pooler.get_pool(cr.dbname).get('account.period')
     journal_obj = pooler.get_pool(cr.dbname).get('account.journal')
     data['form']['period_ids'] = period_obj.search(cr, uid, [('fiscalyear_id','=',fiscalyear_obj.find(cr, uid))])
     data['form']['journal_ids'] = journal_obj.search(cr, uid, [])
     return data['form']
def _numerotate_cont(self,cr,uid,data,context={}):
    nbr_s = int(data['form']['start_number'])
    nbr_l = int(data['form']['last_number'])
    refs_ls = pooler.get_pool(cr.dbname).get('labo.sample')
    ref_hist = pooler.get_pool(cr.dbname).get('setup.history')
    refs_as = pooler.get_pool(cr.dbname).get('analysis.setup')
    rec_ids = refs_ls.browse(cr,uid,data['ids'])
    nbr=nbr_s
    for r in rec_ids:
        if  nbr<=nbr_l:
            refs_ls.write(cr,uid,[r.id],{'file_setup':data['form']['setup_id1']})
            nbr+=1    
 #      s_id=refs_as.create(cr,uid, {
 #                          'set_up':data['form']['setup_id'],
 #                          'well': nbr,
 #                          'run_setup':'004'
 #                          })
 #          #                'sample_id1':r.id,
         #   b=refs_ls.write(cr,uid,[r.id],{'file_setup':s_id})
      #  if r.file_setup.set_up:
          #  ids_r=refs_as.search(cr,uid,[('set_up','=',data['form']['setup_id1'])])
          #  ids_a=refs_as.browse(cr,uid,ids_r)
           # id_a=ids_a and ids_a[0]
            t=r.file_setup and r.file_setup.set_up or '' 
            if t:
                a=ref_hist.create(cr,uid,{'sample_id':r.id,
                               'setup_id':data['form']['setup_id1'],
                               'setup_id2':t.id or ''
                })
    return {}
 def _create_invoice(obj, cr, uid, data, context):
     if data['form'].get('new_picking',False):
         data['id'] = data['form']['new_picking']
         data['ids'] = [data['form']['new_picking']]
     pool = pooler.get_pool(cr.dbname)
     picking_obj = pooler.get_pool(cr.dbname).get('stock.picking')
     mod_obj = pool.get('ir.model.data')
     act_obj = pool.get('ir.actions.act_window')
 
     type = data['form']['type']
 
     res = picking_obj.action_invoice_create(cr, uid, data['ids'],
             journal_id=data['form']['journal_id'],group=data['form']['group'],
             type=type, context= context)
 
     invoice_ids = res.values()    
     if not invoice_ids:
         raise  wizard.except_wizard(_('Error'),_('Invoice is not created'))
 
     if type == 'out_invoice':
         xml_id = 'action_invoice_tree5'
     elif type == 'in_invoice':
         xml_id = 'action_invoice_tree8'
     elif type == 'out_refund':
         xml_id = 'action_invoice_tree10'
     else:
         xml_id = 'action_invoice_tree12'
 
     result = mod_obj._get_id(cr, uid, 'account', xml_id)
     id = mod_obj.read(cr, uid, result, ['res_id'])    
     result = act_obj.read(cr, uid, id['res_id'])
     result['res_id'] = invoice_ids    
     return result
    def _get_email_defaults(self, cr, uid, data, context):
        p = pooler.get_pool(cr.dbname)
        user = p.get('res.users').browse(cr, uid, uid, context)
        
        if user.company_id:
           company_id = user.company_id.id
        else:
           company_id = pooler.get_pool(cr.dbname).get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
        
        period_ids = p.get('account.period').browse(cr, uid, uid, context)

        res_ids = p.get('ir.model').search(cr, uid, [('model', '=', 'account.journal.period')], context=None)
        report_name = "account.print.ad.journal.entries"
        file_name = user.company_id.name.replace(' ','_')+'_'+_('journal_entries_report')
        report = create_report(cr, uid, res_ids, data, report_name, file_name)[1] or 'attachement'

        to = ""
        subject = "JOURNAL by ENTRIES REPORT, %s,  %s" % \
            (period_ids.name or period_ids.code, data['form']['journal_ids'])
        text = 'Dear ...........,\n\n' + \
                'Herewith I enclose the ' + subject + \
                '\n' + \
                '---------\n' + \
                user.signature

        return {'attachment_file': report, 'to': to, 'subject': subject, 'text': text}
示例#12
0
    def init(self, cr, uid=1):
        """ This view will be used in dashboard
        The reason writing this code here is, we need to check date range from today to first date of fiscal year.
        """
        pool_obj_fy = pooler.get_pool(cr.dbname).get('account.fiscalyear')
        today = time.strftime('%Y-%m-%d')
        fy_id = pool_obj_fy.find(cr, uid, exception=False)
        LIST_RANGES = []
        if fy_id:
            fy_start_date = pool_obj_fy.read(cr, uid, fy_id, ['date_start'])['date_start']
            fy_start_date = datetime.strptime(fy_start_date, '%Y-%m-%d')
            last_month_date = datetime.strptime(today, '%Y-%m-%d') - relativedelta(months=1)

            while (last_month_date > fy_start_date):
                LIST_RANGES.append(today + " to " + last_month_date.strftime('%Y-%m-%d'))
                today = (last_month_date- relativedelta(days=1)).strftime('%Y-%m-%d')
                last_month_date = datetime.strptime(today, '%Y-%m-%d') - relativedelta(months=1)

            LIST_RANGES.append(today +" to " + fy_start_date.strftime('%Y-%m-%d'))
            cr.execute('delete from temp_range')

            for range in LIST_RANGES:
                pooler.get_pool(cr.dbname).get('temp.range').create(cr, uid, {'name':range})

        cr.execute("""
            create or replace view report_aged_receivable as (
                select id,name from temp_range
            )""")
def _set_filter_value(self, cr, uid, data, context):
    form_data = data['form']
    value_data = form_data.get('value',False)
    value_field = set_value_fields.get('value')
    field_type = value_field.get('type',False)
    field_data = pooler.get_pool(cr.dbname).get('ir.model.fields').read(cr,uid,[form_data.get('field_id')],fields=['ttype','relation','model_id','name','field_description'])[0]
    model_name = pooler.get_pool(cr.dbname).get('ir.model').browse(cr, uid, field_data['model_id'][0]).model
    model_pool = pooler.get_pool(cr.dbname).get(model_name)
    table_name = model_pool._table
    model_name = model_pool._description

    if field_type:
        if field_type == 'boolean':
            if value_data == 1:
                value_data = 'true'
            else:
                value_data = 'false'

        if field_type in ['float','integer']:
            value_data =  value_data or 0

        if field_type == 'many2many' and value_data and len(value_data):
            fields_list = set_field_operator(self,table_name+"."+field_data['name'],field_data['ttype'],form_data['operator'],value_data[0][2])
        else:
            fields_list = set_field_operator(self,table_name+"."+field_data['name'],field_data['ttype'],form_data['operator'],value_data)
        if fields_list:
            create_dict = {
                           'name':model_name + "/" +field_data['field_description'] +" "+ mapping_fields[form_data['operator']] + " " + tools.ustr(fields_list[2]) + " ",
                           'expression':' '.join(map(tools.ustr,fields_list)),
                           'report_id':data['id'],
                           'condition' : form_data['condition']
                           }
            pooler.get_pool(cr.dbname).get('base_report_creator.report.filter').create(cr,uid,create_dict,context)
    return {'type': 'ir.actions.act_window_close'}
示例#14
0
	def _get_tax(self, order_obj):
		self.cr.execute("SELECT DISTINCT tax_id FROM purchase_order_taxe, purchase_order_line, purchase_order \
			WHERE (purchase_order_line.order_id=purchase_order.id) AND (purchase_order.id=%s)", (order_obj.id))
		res = self.cr.fetchall() or None
		if not res:
			return []
		if isinstance(res, list):
			tax_ids = [t[0] for t in res]
		else:
			tax_ids = res[0]
		tax_obj = pooler.get_pool(self.cr.dbname).get('account.tax')
		res = []
		for tax in tax_obj.browse(self.cr, self.uid, tax_ids):
			self.cr.execute("SELECT DISTINCT order_line_id FROM purchase_order_line, purchase_order_taxe \
				WHERE (purchase_order_taxe.tax_id=%s) AND (purchase_order_line.order_id=%s)", (tax.id, order_obj.id))
			lines = self.cr.fetchall() or None
			if lines:
				if isinstance(lines, list):
					line_ids = [l[0] for l in lines]
				else:
					line_ids = lines[0]
				base = 0
				for line in pooler.get_pool(self.cr.dbname).get('purchase.order.line').browse(self.cr, self.uid, line_ids):
					base += line.price_subtotal
				res.append({'code':tax.name,
					'base':base,
					'amount':base*tax.amount})
		return res
    def _get_email_defaults(self, cr, uid, data, context):
        p = pooler.get_pool(cr.dbname)
        user = p.get('res.users').browse(cr, uid, uid, context)
        
        if user.company_id:
           company_id = user.company_id.id
        else:
           company_id = pooler.get_pool(cr.dbname).get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
        
        fiscalyear = p.get('account.fiscalyear').browse(cr, uid, uid, context)

        res_ids = p.get('ir.model').search(cr, uid, [('model', '=', 'account.account')], context=None)
        report_name = "account.balance.full"
        file_name = user.company_id.name.replace(' ','_')+'_'+_('account_balance_report')
        report = create_report(cr, uid, res_ids, data, report_name, file_name)[1] or 'attachement'

        to = ""
        subject = "ACCOUNT BALANCE REPORT, %s, Date from: %s to %s" % \
            (fiscalyear.name or fiscalyear.code, data['form']['date_from'], data['form']['date_to'])
        text = 'Dear ...........,\n\n' + \
                'Herewith I enclose the ' + subject + \
                '\n' + \
                '---------\n' + \
                user.signature

        return {'attachment_file': report, 'to': to, 'subject': subject, 'text': text}
示例#16
0
def _open_history_event(self, cr, uid, data, context=None):
    pool = pooler.get_pool(cr.dbname)
    data_obj = pool.get("ir.model.data")
    result = data_obj._get_id(cr, uid, "crm", "view_crm_case_filter")
    id = data_obj.read(cr, uid, result, ["res_id"])
    id2 = data_obj._get_id(cr, uid, "crm", "crm_case_calendar_section-view")
    if id2:
        id2 = data_obj.browse(cr, uid, id2, context=context).res_id
    res = ""
    if data.get("model", False) and data.get("ids", False):
        model_obj = pooler.get_pool(cr.dbname).get(data["model"])
        res = model_obj.browse(cr, uid, data["ids"], context=context)
        if len(res):
            res = res[0].name
    return {
        "name": "History : " + res,
        "view_type": "form",
        "view_mode": "calendar, tree, form",
        "view_id": False,
        "views": [(id2, "calendar"), (False, "form"), (False, "tree"), (False, "graph")],
        "res_model": "crm.case",
        "type": "ir.actions.act_window",
        "domain": data.get("id", False) and "[('case_id','=',%d)]" % (data["id"]) or "[]",
        "search_view_id": id["res_id"],
    }
示例#17
0
    def _init_fields(self, cr, uid, data, context):
        """ init the form's fields """

        budget_obj = pooler.get_pool(cr.dbname).get('c2c_budget')
        
        res = {}

        #we come from budget
        if data['model'] == 'c2c_budget':
            budget_obj = pooler.get_pool(cr.dbname).get('c2c_budget')
            
            #init version and version 2 with the 2 first versions
            if len(data['ids']) >= 1:
                budget = budget_obj.browse(cr, uid, data['ids'][0])
                if len(budget.budget_version_ids) >= 1:
                    res['version_1'] = budget.budget_version_ids[0].id
                    res['currency'] = budget.budget_version_ids[0].currency_id.id
                if len(budget.budget_version_ids) >= 2:
                    res['version_2'] = budget.budget_version_ids[1].id
                

        #we come from versions
        elif data['model'] == 'c2c_budget.version':
            version_obj = pooler.get_pool(cr.dbname).get('c2c_budget.version')            

            #init version and version 2 with the 2 first versions
            if len(data['ids']) >= 1:
                res['version_1'] = data['ids'][0]
                res['currency'] = version_obj.browse(cr, uid, data['ids'][0], context=context).currency_id.id
            if len(data['ids']) >= 2:
                res['version_2'] = data['ids'][1]
            
            
        return res   
 def _lang_install(self, cr, uid, data, context):
     password =data['form']['password']
     lang =data['form']['lang']
     user = pooler.get_pool(cr.dbname).get('res.users').read(cr,uid,uid,['login'])['login']
     if not s.verify_user(user,password,lang):
         raise wizard.except_wizard('Error !!', 'Bad User name or Passsword or you are not authorised for this language')
     version = data['form']['version']
     profile = data['form']['profile']         
     ir_translation_contrib = pooler.get_pool(cr.dbname).get('ir.translation.contribution')        
     ids = ir_translation_contrib.search(cr,uid,[('lang','=',lang),('state','=','accept')])
     if not ids:
         raise wizard.except_wizard('Error !!', 'No contributions are find to upload in main revision')
     contrib = ir_translation_contrib.read(cr,uid,ids,['type','name','res_id','src','value'])
     new_contrib =map(lambda x:{'type':x['type'],'name':x['name'],'res_id':x['res_id'],'src':x['src'],'value':x['value']},contrib)
             
     try :
         result = s.publish_release(user,password,lang,version,profile,new_contrib)
  #still working to show correct error message when server is not responding properly
         
     except Exception,e:
         if e.__dict__.has_key('name'):
             raise wizard.except_wizard('Error !',e.value)
         else:
             raise wizard.except_wizard('Error !',"server is not properly configuraed")
         ir_translation_contrib.write(cr,uid,ids,{'state':'done'})
 def _save(self, cr, uid, data, context):
     debug(data)
     debug(context)
     id=data['id']
     table_name=data['model']
     ss=pooler.get_pool(cr.dbname).get(table_name).browse(cr,uid,id)
     data['form']['make']=ss.make
     data['form']['model']=ss.model
     data['form']['state']='in_stock'
     data['form']['manufacture_date']=datetime.datetime.now().strftime("%Y-%m-%d")
     data['form']['order_no']=ss.order_no
     data['form']['price']=ss.price
     data['form']['owner']=ss.owner.id
     data['form']['current_user_id']=ss.owner.id
     data['form']['size']=ss.size
     data['form']['color']=ss.color
     
     equipment_id=pooler.get_pool(cr.dbname).get('cmc.equipment').create(cr, uid, data['form'])
     debug(equipment_id)
     if equipment_id:
         query="insert into equipment_equipment_rel values("+str(ss.equipment_supply_process_id.id)+','+str(equipment_id)+")"
         debug(query)
         cr.execute(query)
         update_query="update cmc_equipment set state='booked' where id="+str(equipment_id)
         cr.execute(update_query)
         pooler.get_pool(cr.dbname).get(table_name).write(cr,uid,[id],{'color':data['form']['color'],'serial_no':data['form']['serial_no'],'state':'Recieved'})
         debug(equipment_id)
     debug(ss)
     return data['form']
    def _send_reminder(self, cr, uid, data, context):

        partner = data['form']['partner_id'][0][2]
        if partner:
            res = pooler.get_pool(cr.dbname).get('ecommerce.partner').browse(cr, uid, partner)
            for partner in res:
                if partner.address_ids and not partner.address_ids[0].email:
                    not_sent.append(partner.name)
                for adr in partner.address_ids:
                    if adr.email:
                        sent_dict[partner.name] = adr.email
                        name = adr.username or partner.name
                        to = '%s <%s>' % (name, adr.email)
                        mail_from = '*****@*****.**'
                       
                        attach_ids = pooler.get_pool(cr.dbname).get('ir.attachment').search(cr, uid, 
                                                                                            [('res_model', '=', 'ecommerce.shop'),
                                                                                            ('res_id', '=', data['ids'][0])])
                        res_atc = pooler.get_pool(cr.dbname).get('ir.attachment').read(cr, uid,
                                                                                       attach_ids, ['datas_fname', 'datas'])
                        res_atc = map(lambda x: (x['datas_fname'],
                                                 base64.decodestring(x['datas'])), res_atc)
                        tools.email_send(mail_from, [to], data['form']['subject'], data['form']['message'], attach=res_atc)

        return 'finished'
 def _save(self, cr, uid, data, context):
     id = int(data['id'])
     if context.get('from',False) == 'call history':
        call_browse=pooler.get_pool(cr.dbname).get('cmc.call.hisoty').browse(cr, uid, id)
        person_id=call_browse.person_id.id
     else: 
         person_id=id
     if data['form']['user_id'] == uid and not data['form']['call_summary']:
         raise except_orm('Incomplete','Please Provide Call Summary')
     if data['form']['allocated_user_group_id'] and data['form']['allocated_user_id']:
             raise except_orm('Call Error!', 'Both UserGroup And User Cannot Be Selected')
     if data['form']['user_id'] != uid :
         if data['form']['allocated_user_group_id'] :
             raise except_orm('Warning','You Cannot Select the Group')
         data['form']['allocated_user_id']=data['form']['user_id']
     else:
         if not data['form']['allocated_user_group_id'] and not data['form']['allocated_user_id']:
             raise except_orm('Call Error!', 'Only one can be selected')
     debug("At Time of saving")
     debug(data)
     if data['form']['allocated_user_group_id'] and data['form']['allocated_user_id']:
         raise except_orm('Enquiry Error!', 'Both UserGroup And User Cannot Be Selected')
     person = pooler.get_pool(cr.dbname).get('cmc.person').browse(cr, uid, person_id)
     user = pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, uid)
     data['form']['call_date_time'] = datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S')
     data['form']['call_person_type'] = 'client'
     data['form']['state'] = 'allocated'
     data['form']['agent_id'] = None
     data['form']['calling_about']='Self'
     call_id = pooler.get_pool(cr.dbname).get('cmc.call.history').create(cr, uid, data['form'],
                 {'wizard':True, 'person': person, 'user':user})
     return {}
示例#22
0
def _valider(self, cr, uid, data, context):
    pool = pooler.get_pool(cr.dbname)
    immo = pooler.get_pool(cr.dbname).get('asset.simulation')
    context.update({'fy_id':data['form']['fy_id'] })

    immo.valider(cr,uid,data['ids'],context)
    return{}
示例#23
0
    def _do_create_invoice(self, cr, uid, data, context):
        logger = netsvc.Logger()
        journal = pooler.get_pool(cr.dbname).get('ica.mrpjournal')
        order_cr = pooler.get_pool(cr.dbname).get('sale.order')
        invoice_cr = pooler.get_pool(cr.dbname).get('account.invoice')

        # One invoice per supplier
        #order_cr.action_invoice_create(cr, uid, order_cr.search(cr, uid, [("ica_mrpjournal","=",data['id']),('EANSUPPLIER','LIKE','7350031550009')]), True)
        #order_cr.action_invoice_create(cr, uid, order_cr.search(cr, uid, [("ica_mrpjournal","=",data['id']),('EANSUPPLIER','LIKE','7300009025411')]), True)

        #3days = datetime.timedelta(days=3)

        today = datetime.datetime.today()
        threedays = today - datetime.timedelta(days=3)

        # Journals three days old not invoiced
        journals = journal.search(cr,uid,[("saleorder_invoice","=",False),("datum","<=",threedays.strftime("%Y-%m-%d"))])
        logger.notifyChannel("Info", netsvc.LOG_INFO,"Journals to invoice '%s' %s ." % (journals,threedays.strftime("%Y-%m-%d")))
        
        for journal_id in journals:
            logger.notifyChannel("warning", netsvc.LOG_WARNING,"Invoice journal_id '%s'  ." % journal_id)    
            inv_id = order_cr.action_invoice_create(cr, uid, order_cr.search(cr, uid, [("ica_mrpjournal","=",journal_id),('eansupplier','=','7350031550009')]), True)
            invoice_cr.write(cr,uid, inv_id, {'ica_mrpjournal': journal_id}) # Mark invoice with journal
            inv_id = order_cr.action_invoice_create(cr, uid, order_cr.search(cr, uid, [("ica_mrpjournal","=",journal_id),('eansupplier','=','7300009025411')]), True)
            invoice_cr.write(cr,uid, inv_id, {'ica_mrpjournal': journal_id}) # Mark invoice with journal

        return {}
示例#24
0
def create(self, cr, uid, ids, datas, context):
    xml = self.create_xml(cr, uid, ids, datas, context)
    xml = tools.ustr(xml).encode('utf8')
    report_type = datas.get('report_type', 'pdf')
    if report_type == 'raw':
        return xml, report_type
    rml = self.create_rml(cr, xml, uid, context)
    pool = pooler.get_pool(cr.dbname)
    ir_actions_report_xml_obj = pool.get('ir.actions.report.xml')
    report_xml_ids = ir_actions_report_xml_obj.search(cr, uid, [('report_name', '=', self.name[7:])], context=context)
    self.title = report_xml_ids and ir_actions_report_xml_obj.browse(cr,uid,report_xml_ids)[0].name or 'OpenERP Report'
    create_doc = self.generators[report_type]
    # change the fontname
    install_ids = pool.get('ir.module.module').search(cr, uid, [('name','=','oecn_base_fonts'),('state','=','installed')])
    originCustomTTFonts = deepcopy(cfonts.CustomTTFonts)
    if install_ids:
        p1 = re.compile('<setFont name=".*?" ')
        p2 = re.compile('fontName=".*?" ')        
        config_parameter_obj = pooler.get_pool(cr.dbname).get("ir.config_parameter")
        base_font = config_parameter_obj.get_param(cr, uid, "font_url")
        cjk_wrap = config_parameter_obj.get_param(cr, uid, "cjk_wrap")
        fonts_map = []
        if base_font:
            for font in OE_FONTS:
                fonts_map += [(font, 'myFont', base_font, 'all')]
        cfonts.CustomTTFonts = fonts_map          
        ParagraphStyle.defaults['wordWrap'] = cjk_wrap and 'CJK' or ''
        rml = p1.sub('<setFont name="' + 'myFont' + '" ', rml)
        rml = p2.sub('fontName="' + 'myFont' + '" ', rml)
    # change the fontname
    pdf = create_doc(rml, title=self.title)
    cfonts.CustomTTFonts = originCustomTTFonts
    return pdf, report_type
示例#25
0
    def get_action(self, cursor, user_id):

        """
        Pull action's information from the DB. Return False if this menu
        has not any action associated to it.
        """

        pool_values = get_pool(cursor.dbname).get('ir.values')
        pool_action = get_pool(cursor.dbname).get('ir.actions.act_window')

        value_id = pool_values.search(cursor, user_id, [
            ('res_id', '=', self.id),
        ])

        if not value_id:
            return False

        value_id = value_id[0]
        value_data = pool_values.read(cursor, user_id, value_id)

        action_id = int(value_data['value'].split(',')[1])
        action_data = pool_action.read(cursor, user_id, action_id)

        self.value_id = value_id
        self.action_id = action_data['id']
        self.action_model = action_data['res_model']
        self.action_view_type = action_data['view_type']
        self.action_view_mode = action_data['view_mode']

        return True
def check(self, cr, uid, data, context):
    test_obj=pooler.get_pool(cr.dbname).get('testing.result')
    test_config=pooler.get_pool(cr.dbname).get('quality.test.config')
    mrp=pooler.get_pool(cr.dbname).get('mrp.production')
    mrp_obj=mrp.browse(cr,uid,data['id'])
    prod_obj=pooler.get_pool(cr.dbname).get('product.product').browse(cr,uid,mrp_obj.product_id.id)

    if prod_obj.finished_test:
        flag=False
        res={}
        res={'type':'finish_prod','product':data['form']['product'],'tester':data['form']['tester'],'test_date':data['form']['test_date']}
        test_id=test_obj.create(cr,uid,res)

        for case in prod_obj.finished_test:

            actual=data['form']['actual%s'%(case.name.id,)]
            min=data['form']['min%s'%(case.name.id,)]
            max=data['form']['max%s'%(case.name.id,)]

            if data['form']['active%s'%(case.name.id,)]:
                if actual> 0.00:
                    val={}
                    if (actual >=min and actual <= max):
                       state='accepted'
                    else:
                       state='rejected'
                       flag=True
                    val={'name':case.name.id,'min_limit':case.min_limit,'max_limit':case.max_limit,'uom':case.uom.id,
                             'actual_val':actual,'state':state,'test_id':test_id}
                    test_config.create(cr,uid,val)

        if not flag:
            mrp.write(cr,uid,data['id'],{'state':'done'})

    return {}
示例#27
0
def do_merge(self, cr, uid, data, context):
    invent_obj = pooler.get_pool(cr.dbname).get('stock.inventory')
    invent_line_obj = pooler.get_pool(cr.dbname).get('stock.inventory.line')
    prod_obj =  pooler.get_pool(cr.dbname).get('product.product')

    if len(data['ids']) <> 1:
        raise wizard.except_wizard(_('Warning'),
                                   _('Please select one and only one inventory !'))

    loc = data['form']['location_id']

    cr.execute('select distinct location_id,product_id from stock_inventory_line where inventory_id=%s', (data['ids'][0],))
    inv = cr.fetchall()
    cr.execute('select distinct product_id from stock_move where (location_dest_id=%(location_id)s) or (location_id=%(location_id)s)', data['form'])
    stock = cr.fetchall()
    for s in stock:
        if (loc,s[0]) not in inv:
            p = prod_obj.browse(cr, uid, s[0])
            invent_line_obj.create(cr, uid, {
                'inventory_id': data['ids'][0],
                'location_id': loc,
                'product_id': s[0],
                'product_uom': p.uom_id.id,
                'product_qty': 0.0,
                })
    return {}
 def _get_defaults(self, cr, uid, data, context):
     fiscalyear_obj = pooler.get_pool(cr.dbname).get("account.fiscalyear")
     period_obj = pooler.get_pool(cr.dbname).get("account.period")
     journal_obj = pooler.get_pool(cr.dbname).get("account.journal")
     data["form"]["period_ids"] = period_obj.search(cr, uid, [("fiscalyear_id", "=", fiscalyear_obj.find(cr, uid))])
     data["form"]["journal_ids"] = journal_obj.search(cr, uid, [])
     return data["form"]
def _mass_mail_send(self, cr, uid, data, context):
	nbr = 0
	partners = pooler.get_pool(cr.dbname).get('labo.analysis.request').browse(cr, uid, data['ids'], context)
	for p in partners:
		partner=p.ref_client
		for adr in partner.address:
			if adr.email:
				name = adr.name or partner.name
				to = '%s <%s>' % (name, adr.email)
#TODO: add some tests to check for invalid email addresses
#CHECKME: maybe we should use res.partner/email_send
				attach_ids = pooler.get_pool(cr.dbname).get('ir.attachment').search(cr, uid,
							[('res_model', '=', 'labo.analysis.request'),
								('res_id', '=', p.id)])
				res = pooler.get_pool(cr.dbname).get('ir.attachment').read(cr, uid,
							attach_ids, ['datas_fname','datas'])
				res = map(lambda x: (x['datas_fname'],
						base64.decodestring(x['datas'])), res)
				tools.email_send_attach(data['form']['from'], [to], data['form']['subject'], data['form']['text'],attach=res)
				nbr += 1
	#	pooler.get_pool(cr.dbname).get('res.partner.event').create(cr, uid,
	#			{'name': 'Email sent through mass mailing',
	#			 'partner_id': partner,
	#			 'description': data['form']['text'], })
#TODO: log number of message sent
	return {'email_sent': nbr}
def crear_header(self, cr, uid, data, context):
    form = data['form']
    anio = form['trans_anio']
    res = pooler.get_pool(cr.dbname).get('hr.employee').search(cr, uid, [])
    #iter in employees
    for emp in res:
        obj = pooler.get_pool(cr.dbname).get('hr.employee').browse(cr, uid, emp)
        tipoid = obj.tipoid
        cedula = obj.cedula
        address = obj.address
        fono = obj.work_phone
        sis_sal = 2
        res1 = pooler.get_pool(cr.dbname).get('hr.contract').search(cr, uid, [('employee_id','=',emp)])[0]
        ct = pooler.get_pool(cr.dbname).get('hr.contract').browse(cr, uid, res1)
        salario = ct.wage
        sobresueldo = 0
        res2 = pooler.get_pool(cr.dbname).get('hr.provision').search(cr, uid, ['employee_id',])
    res = cr.fetchall()
    if res:
        ruc = res[0][0]   
        rdep = etree.Element('rdep')
        etree.SubElement(rdep, 'numRuc').text = ruc
        etree.SubElement(rdep, 'anio').text = str(anio)
        file = etree.tostring(rdep, pretty_print=True, encoding='iso-8859-1')
        buf=StringIO.StringIO()
        buf.write(file)
        out=base64.encodestring(buf.getvalue())
        buf.close()
        name = "%s%s.XML" % ("RDEP", strftime("%Y"))
    return {'data': out, 'name': name}
 def generate_parameters(self, cr, uid, ids, data, context):
     vals = {}
     pool = pooler.get_pool(cr.dbname)
     user_pool = pool.get('res.users')
     ana_pool = pool.get('account.analytic.account')
     fin_pool = pool.get('account.financial.report')
     user_obj = user_pool.browse(cr, uid, uid, context=context)
     comp_obj = user_obj.company_id
     date_from = data['form'].get('date_from', False)
     date_to = data['form'].get('date_to', False)
     cost_center_ids = data['form']['cost_center_ids']
     report_id = data['form']['account_report_id'][0]
     report_obj = fin_pool.browse(cr, uid, report_id, context=context)
     cc_names = 'ALL'
     total_label = "TOTAL"
     if report_obj.total_label:
         total_label = report_obj.total_label or ''
     if cost_center_ids:
         cost_center_objs = ana_pool.browse(cr,
                                            uid,
                                            cost_center_ids,
                                            context=context)
         cc_list = [x.name for x in cost_center_objs]
         cc_names = ', '.join(cc_list)
     start_date = datetime.strptime(date_from,
                                    "%Y-%m-%d").strftime("%d/%m/%Y")
     end_date = datetime.strptime(date_to, "%Y-%m-%d").strftime("%d/%m/%Y")
     year = datetime.strptime(date_to, "%Y-%m-%d").strftime("%Y")
     account_report_name = data['form']['account_report_id'][1]
     grand_balance = 0.0
     total_profit = 0.0
     total_loss = 0.0
     child_accounts = self.cr.execute("""
                                             SELECT 
                                                 id
                                             FROM
                                                 account_account
                                             where 
                                                 code ilike '4%'
                                             """)
     child_ids = map(lambda x: x[0], self.cr.fetchall())
     if child_ids:
         balance_list = self._get_balance(data, child_ids)
         balance = balance_list and balance_list[0] or 0.0
         total_profit = abs(balance)
     child_accounts = self.cr.execute("""
                                         SELECT 
                                             id
                                         FROM
                                             account_account
                                         where 
                                             code ilike '5%' 
                                                 or 
                                             code ilike '6%'
                                         """)
     child_ids = map(lambda x: x[0], self.cr.fetchall())
     if child_ids:
         balance_list = self._get_balance(data, child_ids)
         balance = balance_list and balance_list[0] or 0.0
         total_loss = abs(balance)
     if account_report_name and account_report_name == 'PROFIT & LOSS':
         label = 'yes'
     else:
         label = 'no'
     if total_profit > total_loss:
         grand_balance = total_profit - total_loss
         grand_balance = -1 * grand_balance
     else:
         grand_balance = total_loss - total_profit
         grand_balance = 1 * grand_balance
     vals = {
         'company_name':
         comp_obj.name or '',
         'run_time':
         fields.datetime.context_timestamp(cr,
                                           uid,
                                           datetime.now(),
                                           context=context),
         'curr':
         comp_obj.currency_id.name or '',
         'report_name':
         "%s AS ON %s" % (account_report_name, str(end_date)),
         'year':
         str(year),
         'cc_names':
         cc_names,
         'total_label':
         total_label,
         'grand_total':
         grand_balance,
         'label':
         label
     }
     return vals
    def create_with_attachment(self,
                               cr,
                               uid,
                               ids,
                               data,
                               original_doc,
                               context=None):
        import base64
        from report.pyPdf import PdfFileReader, PdfFileWriter
        o = PdfFileWriter()

        pool = pooler.get_pool(cr.dbname)
        quizz_id = ids[0]

        if data.get('model', '') == 'training.participation':
            participation = pool.get('training.participation').browse(
                cr, uid, data['id'])
            quizz_id = participation.questionnaire_id.id

        quizz_proxy = pool.get('training.exam.questionnaire')
        quizz = quizz_proxy.browse(cr, uid, quizz_id)

        def write_orig_document():
            r = PdfFileReader(StringIO.StringIO(original_doc[0]))
            for p in range(r.getNumPages()):
                o.addPage(r.getPage(p))

        def generate_watermark_pdf(docid, basenum, npages):
            watermark_report = netsvc.LocalService(
                'report.training.participation.watermark.qrcode')
            report_ids = [
                '%s-%s%03d' % (docid, basenum, n + 1) for n in range(npages)
            ]
            (result, format) = watermark_report.create(cr,
                                                       uid,
                                                       report_ids, {},
                                                       context=context)
            return PdfFileReader(StringIO.StringIO(result))

        attach_count = 0
        orig_doc_written = False
        for attach in quizz.attachment_ids:
            if attach.position == 'after' and not orig_doc_written:
                write_orig_document()
                orig_doc_written = True

            # 1 = annex and store
            # 2 = detect qrcode but don't store in the DMS
            basenum = '%1s%02d' % (attach.store_in_dms and 1
                                   or 2, attach_count)

            attach_pdf_data = base64.decodestring(attach.attachment_id.datas)
            attach_pdf = PdfFileReader(StringIO.StringIO(attach_pdf_data))
            waterm_pdf = generate_watermark_pdf(ids[0], basenum,
                                                attach_pdf.getNumPages())

            for attach_page in range(attach_pdf.getNumPages()):
                docp = attach_pdf.getPage(attach_page)
                docp_wm = waterm_pdf.getPage(attach_page)
                docp.mergePage(docp_wm)
                o.addPage(docp)

            attach_count += 1
        if not orig_doc_written:
            write_orig_document()

        s = StringIO.StringIO()
        o.write(s)
        return (s.getvalue(), original_doc[1])
 def _selectPartner(self, cr, uid, data, context):
     case_obj = pooler.get_pool(cr.dbname).get('crm.case')
     case = case_obj.browse(cr, uid, data['id'])
     return {'date': case.date, 'duration': case.duration or 2.0}
示例#34
0
def _get_out(self, cr, uid, data, context):
    args = {}
    pool = pooler.get_pool(cr.dbname)
    statement_obj = pool.get('account.bank.statement')
    product_obj = pool.get('product.template')
    productp_obj = pool.get('product.product')
    res_obj = pool.get('res.users')
    curr_company = res_obj.browse(cr, uid, uid).company_id.id
    statement_id = statement_obj.search(
        cr, uid, [('journal_id', '=', data['form']['journal_id']),
                  ('company_id', '=', curr_company), ('user_id', '=', uid),
                  ('state', '=', 'open')])
    monday = (DateTime.now() +
              DateTime.RelativeDateTime(weekday=(DateTime.Monday,
                                                 0))).strftime('%Y-%m-%d')
    sunday = (DateTime.now() +
              DateTime.RelativeDateTime(weekday=(DateTime.Sunday,
                                                 0))).strftime('%Y-%m-%d')
    done_statmt = statement_obj.search(
        cr, uid, [('date', '>=', monday + ' 00:00:00'),
                  ('date', '<=', sunday + ' 23:59:59'),
                  ('journal_id', '=', data['form']['journal_id']),
                  ('company_id', '=', curr_company), ('user_id', '=', uid)])
    stat_done = statement_obj.browse(cr, uid, done_statmt)
    address_u = pool.get('res.users').browse(cr, uid, uid).address_id
    am = 0.0
    amount_check = productp_obj.browse(
        cr, uid, data['form']['product_id']).am_out or False
    for st in stat_done:
        for s in st.line_ids:
            if address_u and s.partner_id == address_u.partner_id and s.am_out:
                am += s.amount
    if (-data['form']['amount'] or 0.0) + am < -(res_obj.browse(
            cr, uid, uid).company_id.max_diff or 0.0) and amount_check:
        val = (res_obj.browse(cr, uid, uid).company_id.max_diff or 0.0) + am
        raise wizard.except_wizard(
            _('Error !'),
            _('The maximum value you can still withdraw is exceeded. \n Remaining value is equal to %d '
              ) % (val))

    acc_id = product_obj.browse(
        cr, uid, data['form']['product_id']).property_account_income
    if not acc_id:
        raise wizard.except_wizard(
            _('Error !'),
            _('please check that account is set to %s') %
            (product_obj.browse(cr, uid, data['form']['product_id']).name))
    if not statement_id:
        raise wizard.except_wizard(_('Error !'),
                                   _('You have to open at least one cashbox'))
    if statement_id:
        statement_id = statement_id[0]
    if not statement_id:
        statement_id = statement_obj.create(
            cr, uid, {
                'date': time.strftime('%Y-%m-%d 00:00:00'),
                'journal_id': data['form']['journal_id'],
                'company_id': curr_company,
                'user_id': uid,
            })
    args['statement_id'] = statement_id
    args['journal_id'] = data['form']['journal_id']
    if acc_id:
        args['account_id'] = acc_id.id
    amount = data['form']['amount'] or 0.0
    if data['form']['amount'] > 0:
        amount = -data['form']['amount']
    args['amount'] = amount
    if productp_obj.browse(cr, uid, data['form']['product_id']).am_out:
        args['am_out'] = True
    args['ref'] = data['form']['ref'] or ''
    args['name'] = "%s: %s " % (product_obj.browse(
        cr, uid,
        data['form']['product_id']).name, data['form']['name'].decode('utf8'))
    address_u = pool.get('res.users').browse(cr, uid, uid).address_id
    if address_u:
        partner_id = address_u.partner_id and address_u.partner_id.id or None
        args['partner_id'] = partner_id
    statement_line_id = pool.get('account.bank.statement.line').create(
        cr, uid, args)
    return {}
示例#35
0
 def get_cat(self, data):
     result = []
     cat_id = data['form']['cat_id']
     emp = pooler.get_pool(self.cr.dbname).get('hr.employee.category')
     result = emp.browse(self.cr, self.uid, cat_id)
     return result
示例#36
0
    def update_translations(self,
                            cr,
                            uid,
                            ids,
                            filter_lang=None,
                            context=None):
        if context is None:
            context = {}
        if not filter_lang:
            pool = pooler.get_pool(cr.dbname)
            lang_obj = pool.get('res.lang')
            lang_ids = lang_obj.search(cr, uid, [('translatable', '=', True)])
            filter_lang = [
                lang.code for lang in lang_obj.browse(cr, uid, lang_ids)
            ]
        elif not isinstance(filter_lang, (list, tuple)):
            filter_lang = [filter_lang]

        for mod in self.browse(cr, uid, ids):
            if mod.state != 'installed':
                continue
            modpath = addons.get_module_path(mod.name)
            if not modpath:
                # unable to find the module. we skip
                continue
            for lang in filter_lang:
                iso_lang = tools.get_iso_codes(lang)
                f = addons.get_module_resource(mod.name, 'i18n',
                                               iso_lang + '.po')
                context2 = context and context.copy() or {}
                if f and '_' in iso_lang:
                    iso_lang2 = iso_lang.split('_')[0]
                    f2 = addons.get_module_resource(mod.name, 'i18n',
                                                    iso_lang2 + '.po')
                    if f2:
                        _logger.info(
                            'module %s: loading base translation file %s for language %s',
                            mod.name, iso_lang2, lang)
                        tools.trans_load(cr,
                                         f2,
                                         lang,
                                         verbose=False,
                                         context=context)
                        context2['overwrite'] = True
                # Implementation notice: we must first search for the full name of
                # the language derivative, like "en_UK", and then the generic,
                # like "en".
                if (not f) and '_' in iso_lang:
                    iso_lang = iso_lang.split('_')[0]
                    f = addons.get_module_resource(mod.name, 'i18n',
                                                   iso_lang + '.po')
                if f:
                    _logger.info(
                        'module %s: loading translation file (%s) for language %s',
                        mod.name, iso_lang, lang)
                    tools.trans_load(cr,
                                     f,
                                     lang,
                                     verbose=False,
                                     context=context2)
                elif iso_lang != 'en':
                    _logger.warning(
                        'module %s: no translation for language %s', mod.name,
                        iso_lang)
示例#37
0
    def _open_partner(self, cr, uid, data, context):
        pool_obj = pooler.get_pool(cr.dbname)
        model_data_ids = pool_obj.get('ir.model.data').search(
            cr, uid, [('model', '=', 'ir.ui.view'),
                      ('name', '=', 'view_partner_form')])
        resource_id = pool_obj.get('ir.model.data').read(
            cr, uid, model_data_ids, fields=['res_id'])[0]['res_id']

        # extract the caller phone number from the list of active channels of Escaux Serveur
        # 1/ extract the Escaux server where the current user is connected to
        user = pool_obj.get('res.users').browse(cr, uid, uid, context=context)
        if not user.escaux_server_id.id:
            raise osv.except_osv(
                _('Error :'),
                _('No Escaux server configured for the current user.'))
        else:
            escaux_server = user.escaux_server_id

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

        # 3/ We extract the list of active channels from the Escaux SOP server
        res = urllib.urlopen('http://' + escaux_server.ip_address +
                             '/xml/ccGetChannels.php')
        stringXML = ''
        for line in res:
            stringXML += line
        root = etree.fromstring(stringXML)
        foundUser = False
        phone_nr = ''
        user_phone_name = 'SIP/' + user.sip_name
        for channel in list(root):
            lastCallerID = ''
            for element in list(channel):
                if element.tag == 'CallerId':
                    lastCallerID = element.text
                elif element.tag == "ID" and element.text[
                        0:len(user_phone_name)] == user_phone_name:
                    foundUser = True
            if foundUser:
                phone_nr = lastCallerID[len(escaux_server.prefix_incoming):]
                break

        # Check if the number to dial is not empty
        #print "extracted: *" + phone_nr + "*"
        if not phone_nr:
            raise osv.except_osv(
                _('Error :'),
                _('There is no phone number to retrieve for this user !'))
        # Note : if I write 'Error' without ' :', it won't get translated...
        # Alexis de Lattre doesn't understand why ! I agree ...

        # search for this phonenumber in the fields res.partner.job.phone then res.partner.contact.mobile and, if not yet found, res.partner.address.phone
        partner_id = 0
        job_ids = pool_obj.get('res.partner.job').search(
            cr, uid, [('phone', '=', phone_nr)])
        foundRecord = False
        if job_ids:
            jobs = pool_obj.get('res.partner.job').browse(cr, uid, job_ids)
            for job in jobs:
                if job.address_id and job.address_id.partner_id:
                    # we found a job with an address linked to a partner, we can stop the search here
                    partner_id = job.address_id.partner_id.id
                    foundRecord = True
                    break
        if not foundRecord:
            # we don't found someone in jobs from the phonenumber so we try from contacts
            contact_ids = pool_obj.get('res.partner.contact').search(
                cr, uid, [('mobile', '=', phone_nr)])
            if contact_ids:
                contacts = pool_obj.get('res.partner.contact').browse(
                    cr, uid, contact_ids)
                print contacts
                for contact in contacts:
                    print contact
                    if contact.job_id and contact.job_id.address_id and contact.job_id.address_id.partner_id:
                        # we found a contact linked to a partner, we can stop the search here
                        partner_id = contact.job_id.address_id.partner_id.id
                        foundRecord = True
                        break
        if not foundRecord:
            # we don't found someone in jobs, nor in contacts, so we try in addresses
            address_ids = pool_obj.get('res.partner.address').search(
                cr, uid, [('phone', '=', phone_nr)])
            if address_ids:
                addresses = pool_obj.get('res.partner.address').browse(
                    cr, uid, address_ids)
                for address in addresses:
                    if address.partner_id:
                        # we found a address linked to a partner, we can stop the search here
                        partner_id = address.partner_id.id
                        foundRecord = True
                        break
        if not foundRecord:
            raise osv.except_osv(
                _('Error :'),
                _('This phone number is not found in our database !'))
            return {'type': 'state', 'state': 'end'}
        else:
            return {
                'domain': "[('id','='," + str(partner_id) + ")]",
                'name': 'Calling Partner',
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'res.partner',
                'views': [(False, 'tree'), (resource_id, 'form')],
                'type': 'ir.actions.act_window'
            }
示例#38
0
    def generate_records(self, cr, uid, ids, data, context):
        print data, 'afdssgsggsgfs'
        pool = pooler.get_pool(cr.dbname)

        return {}
示例#39
0
 def _get_vouchers(self, move):
     vouchers = pooler.get_pool(self.cr.dbname).get('account.voucher').search(self.cr, self.uid, [('move_id', '=', move.id)])
     return pooler.get_pool(self.cr.dbname).get('account.voucher').browse(self.cr, self.uid, vouchers)
示例#40
0
    def tire_retread(self, cr, uid, data, context):

        pool = pooler.get_pool(cr.dbname)
        tire_obj = pool.get('stock.production.lot')
        move_obj = pool.get('stock.move')
        vehic_obj = pool.get('fleet.vehicles')
        loc_obj = pool.get('stock.location')
        company_obj = pool.get('res.company')
        tire_data_obj = pool.get('tire.stock.lot')
        tire = tire_obj.browse(cr, uid, data['form']['tire'])
        company = tire.company_id
        move_list = move_obj.search(cr, uid, [('prodlot_id', '=', tire.id)])
        destination = loc_obj.browse(cr, uid, data['form']['destination'])
        destination_name = destination.name
        origin = loc_obj.browse(cr, uid, data['form']['origin'])
        origin_name = origin.name

        #Comprobar si el origen es un vehiculo
        if origin.location_id:
            loc_parent_ori = origin.location_id.id
            if loc_parent_ori:
                vehic_list = vehic_obj.search(
                    cr, uid, [('buslocat', '=', loc_parent_ori)])
            else:
                vehic_list = []
            if vehic_list == []:
                ori_vehicle = False
                res = 'error'
            else:
                vehicle = vehic_obj.browse(cr, uid, vehic_list[0])
                ori_vehicle = True
                res = 'moved'
        else:
            ori_vehicle = False
            res = 'moved'
        # Termina comprobación origen

        if ori_vehicle:  # Origin = Vehicle
            if origin_name.endswith("-1"):
                update = {'f_l_tire': False}
            elif origin_name.endswith("-2"):
                update = {'f_r_tire': False}
            if vehicle.tires == 6:
                if origin_name.endswith("-3"):
                    update = {'r_l_tire1': False}
                elif origin_name.endswith("-4"):
                    update = {'r_l_tire2': False}
                elif origin_name.endswith("-5"):
                    update = {'r_r_tire2': False}
                elif origin_name.endswith("-6"):
                    update = {'r_r_tire1': False}
            elif vehicle.tires > 6:
                if origin_name.endswith("-3"):
                    update = {'m_l_tire1': False}
                elif origin_name.endswith("-4"):
                    update = {'m_l_tire2': False}
                elif origin_name.endswith("-5"):
                    update = {'m_r_tire2': False}
                elif origin_name.endswith("-6"):
                    update = {'m_r_tire1': False}
                elif origin_name.endswith("-7"):
                    update = {'r_l_tire1': False}
                elif origin_name.endswith("-8"):
                    update = {'r_r_tire1': False}
            vehic_obj.write(cr, uid, vehicle.id, update)
        product_id = tire.product_id

        # actualizar odometro rueda
        odometer = data['form']['odometer']
        if move_list == []:
            odometer_text = str(data['form']['odometer'])
            tire_odometer = 1
            if odometer_text == '0':
                odometer = 1
            tire_val = {'tire_km': tire_odometer, 'odometers': odometer_text}
        else:
            if ori_vehicle:
                loc_id = max(move_list)
                move = move_obj.browse(cr, uid, loc_id)
                result = int(odometer) - move.odometer
                tire_odometer = tire.tire_km + result
                if tire.odometers:
                    odometer_text = tire.odometers + "\n" + str(
                        data['form']['odometer'])
                else:
                    odometer_text = str(data['form']['odometer'])
                tire_val = {
                    'tire_km': tire_odometer,
                    'odometers': odometer_text
                }
            else:
                if tire.odometers:
                    odometer_text = tire.odometers + "\n" + str(
                        data['form']['odometer'])
                else:
                    odometer_text = str(data['form']['odometer'])
                tire_val = {'odometers': odometer_text}
        tire_obj.write(cr, uid, tire.id, tire_val)
        # Termina actualización odometro rueda

        #Datos rueda
        tire_data_list = tire_data_obj.search(cr, uid,
                                              [('lot_id', '=', tire.id)])
        if tire_data_list == []:
            tire_data_val = {
                'name':
                origin.name + ' | ' + tire.name + ' => ' + destination.name,
                'lot_id': tire.id,
                'origin': origin.id,
                'destination': destination.id,
                # 'data':time.strftime('%Y-%m-%d %H:%M:%S'),
                'odomold': 0,
                'odomnew': 0,
                'tire_km': 0,
                'tire_km_total': tire.tire_km
            }
        else:
            tire_data_id = max(tire_data_list)
            tire_data = tire_data_obj.browse(cr, uid, tire_data_id)
            tire_data_val = {
                'name':
                origin.name + ' | ' + tire.name + ' => ' + destination.name,
                'lot_id': tire.id,
                'origin': origin.id,
                'destination': destination.id,
                # 'data':time.strftime('%Y-%m-%d %H:%M:%S'),
            }
            if ori_vehicle:  # Update odometer from vehicle
                tire_data_val['odomold'] = tire_data.odomnew
                tire_data_val['odomnew'] = odometer
                tire_data_val['tire_km'] = odometer - tire_data.odomnew
                tire_data_val[
                    'tire_km_total'] = tire_data.tire_km_total + odometer - tire_data.odomnew
            else:
                tire_data_val['odomold'] = tire_data.odomnew
                tire_data_val['odomnew'] = odometer
                tire_data_val['tire_km'] = 0
                tire_data_val['tire_km_total'] = tire.tire_km
        #Fin datos rueda

        #Datos movimiento
        move_data = {
            'product_id': tire.product_id.id,
            'name':
            origin.name + ' | ' + tire.name + ' => ' + destination.name,
            'location_id': origin.id,
            'product_uom': tire.product_id.product_tmpl_id.uom_id.id,
            'prodlot_id': tire.id,
            'location_dest_id': destination.id,
            'odometer': odometer
        }
        #actualiza movimiento
        move_id = move_obj.create(cr, uid, move_data)
        #Fin datos movimiento

        #Actualiza rueda
        tire_obj.write(cr, uid, tire.id, {
            'tire_km': tire_data_val['tire_km_total'],
            'odometers': odometer_text
        })

        #crear datos neumático
        move_data_reg = move_obj.browse(cr, uid, move_id)
        tire_data_val['data'] = move_data_reg.date
        data_id = tire_data_obj.create(cr, uid, tire_data_val)
        #Fin datos rueda
        res = 'moved'

        return res
示例#41
0
 def get_partner(self, partner_id):
     partner_obj = pooler.get_pool(self.cr.dbname).get('res.partner')
     return partner_obj.read(self.cr, self.uid, [partner_id], ['name'])[0]['name']
示例#42
0
def parse_sequence(bank_statement,bank, cr, uid,):
	pool = pooler.get_pool(cr.dbname)
	st_line = {}
	bank_statement_output=[]
	current=0
	while current < len(bank_statement):
		#if ':61:' in bank_statement[current]:
		if bank_statement[current].has_key(':61:'):
			# Pfff.. a line we can use. Gives us the date, debit/credit, and amount
			st_line['date']=conversion.str2date(bank_statement[current][':61:'][0:6])
			entry_date = time.strftime('%Y-%m-%d',time.strptime(conversion.str2date(bank_statement[current][':61:'][0:6]),"%d/%m/%y")),
			st_line['val_date']   = time.strftime('%Y-%m-%d',time.strptime(conversion.str2date(bank_statement[current][':61:'][0:6]),"%d/%m/%y")),
			st_line['entry_date']=entry_date
			# Pfff...get amount
			amount =round(float(get_number(bank_statement[current][':61:'])),2)
			st_line['amount']=amount
			# Getting rich or poor
			if bank_statement[current][':61:'][6] == "D":
				st_line['account_id'] = bank['def_pay_acc']
				st_line['amount'] = - st_line['amount']
				# chek_ids did not work correctly because the amount could also be negativ
				amount = - amount
			else:
				st_line['account_id'] = bank['def_rec_acc']
			# Well, that was the transaction, now the details, directly next line..
			current += 1
			if bank_statement[current].has_key(':68:'):
				st_line['free_comm'] = " "
				st_line['partner_id'] = 0
				st_line['type'] = 'general'
				st_line['free_comm'] = " "
				st_line['partner_acc_number'] = get_acc_number(bank_statement[current][':68:'])
				st_line['cntry_number'] = get_acc_number(bank_statement[current][':68:'])
				st_line['contry_name'] =bank_statement[current][':68:'][len(st_line['cntry_number']):]
				st_line['name'] = bank_statement[current][':68:'][len(st_line['cntry_number']):]
				st_line['ref'] =" " # Sometimes .. there is no ref. Still, it is being used by other scripts.
				# Houston, we have a problem.. ING uses nicely a second :86: code, Postbank does not ... (back to the filling of the list,.done)
				# See if we have a next rule, only description!! 
				current += 1
				if bank_statement[current].has_key(':68:'):
					st_line['ref'] =bank_statement[current][':68:'][0:]
					# extra comment.. filling the free_comm
					current += 1
					if bank_statement[current].has_key(':68:'):
						st_line['free_comm'] = bank_statement[current][':68:'][0:]
					else:
						current -= 1
			# check if there is already a statement like this...
			check_ids = pool.get('account.bank.statement.line').search(cr,uid,[('amount','=',amount), ('date','=',entry_date),('name','=',st_line['name'])])
			# check if there already is a relation ..., and use the ID
			bank_ids = pool.get('res.partner.bank').search(cr,uid,[('acc_number','=',st_line['partner_acc_number'])])
			if bank_ids:
				bank = pool.get('res.partner.bank').browse(cr,uid,bank_ids[0],context={})
				if bank.partner_id:
					st_line['partner_id'] = bank.partner_id.id
					partner = pool.get('res.partner').browse(cr,uid,bank.partner_id,context={})
					if bank.partner_id.supplier == True and bank.partner_id.customer == False:
						st_line['account_id'] = bank.partner_id.property_account_receivable.id
						st_line['type'] ='supplier'
					elif bank.partner_id.customer == True and bank.partner_id.supplier == False :
						st_line['account_id'] = bank.partner_id.property_account_payable.id
						st_line['type'] ='customer'
			# ..Let see if we can make that just one line of imput
			if not check_ids:
				bank_statement_output.append(st_line.copy())
							
				
			
		current += 1
	return bank_statement_output
示例#43
0
def _populate_statement(obj, cr, uid, data, context):
    line_ids = data['form']['lines'][0][2]
    if not line_ids:
        return {}

    pool = pooler.get_pool(cr.dbname)
    line_obj = pool.get('payment.line')
    statement_obj = pool.get('account.bank.statement')
    statement_line_obj = pool.get('account.bank.statement.line')
    currency_obj = pool.get('res.currency')
    move_line_obj = pool.get('account.move.line')
    voucher_obj = pool.get('account.voucher')
    voucher_line_obj = pool.get('account.voucher.line')

    statement = statement_obj.browse(cr, uid, data['id'], context=context)

    for line in line_obj.browse(cr, uid, line_ids, context=context):
        ctx = context.copy()
        ctx['date'] = line.ml_maturity_date
        amount_currency = line.type == 'receivable' and line.amount_currency or -line.amount_currency
        amount = currency_obj.compute(cr, uid, line.currency.id,
                statement.currency.id, amount_currency, context=ctx)

        voucher_id = False
        if line.move_line_id:
            #We have to create a voucher and link it to the bank statement line
            context.update({'move_line_ids': [line.move_line_id.id]})
            result = voucher_obj.onchange_partner_id(cr, uid, [], partner_id=line.move_line_id.partner_id.id,
                journal_id=statement.journal_id.id, price=abs(amount), currency_id= statement.currency.id,
                ttype=(amount < 0 and 'payment' or 'receipt'), date=line.date or line.move_line_id.date, context=context)

            voucher_res = { 'type':(amount < 0 and 'payment' or 'receipt'),
                            'name': line.move_line_id.name,
                            'reference': (line.order_id.reference or '?') +'. '+ line.name,
                            'partner_id': line.move_line_id.partner_id.id,
                            'journal_id': statement.journal_id.id,
                            'account_id': result.get('account_id', statement.journal_id.default_credit_account_id.id), # improve me: statement.journal_id.default_credit_account_id.id
                            'company_id': statement.company_id.id,
                            'currency_id': statement.currency.id,
                            'date': line.date or line.move_line_id.date,
                            'amount': abs(amount),
                            'period_id': statement.period_id.id}
            voucher_id = voucher_obj.create(cr, uid, voucher_res, context=context)

            voucher_line_dict =  {}
            if result['value']['line_ids']:
                for line_dict in result['value']['line_ids']:
                    move_line = move_line_obj.browse(cr, uid, line_dict['move_line_id'], context)
                    if line.move_line_id.move_id.id == move_line.move_id.id:
                        voucher_line_dict = line_dict
            if voucher_line_dict:
                voucher_line_dict.update({'voucher_id': voucher_id, 'amount': abs(amount)})
                voucher_line_obj.create(cr, uid, voucher_line_dict, context=context)

        statement_line_obj.create(cr, uid, {
            'name': (line.order_id.reference or '?') +'. '+ line.name,
            'amount': amount, 
            'type': line.order_id.type=='payable' and 'supplier' or 'customer',
            'partner_id': line.partner_id.id,
            'account_id': line.move_line_id.account_id.id,
            'statement_id': statement.id,
            'ref': line.communication,
            'voucher_id': voucher_id,
            }, context=context)
    return {}
    def _get_detalle(self, order):
        if not order:
            return []

        resp = []
        #Inicializacion Variables Globales----------------------------------------------------
        if self.currentOrderId == 0 or self.currentOrderId != order:
            self.currentOrderId = order
            self.totalgral = 0
            self.subtotal = 0
            self.totaldcto = 0
            self.totalcajas = 0
            self.pay = 0
            product_fact = []

        sql = """	
		SELECT  p.default_code,t.name,p.variants,s.price_unit,s.product_uom_qty,s.id   
		FROM	 sale_order_line		AS s
		LEFT     JOIN product_product	AS p  ON s.product_id=p.id
		INNER  JOIN product_template	AS t  ON p.product_tmpl_id=t.id  
		WHERE order_id=%d 
		ORDER BY p.default_code;""" % order
        self.cr.execute(sql)
        resultSQL = self.cr.fetchall()
        if not resultSQL:
            product_fact = [{
                "cod": '',
                "nomb": '',
                "ref": '',
                "cant": 0,
                "precio": 0,
                "total": 0,
                "alic": 0,
                "imp": ''
            }]

        for inf in resultSQL:
            total = 0
            iva = 0
            alic = 0
            impt = 0
            sqlt = """
			select t.amount 
			from sale_order_tax as s
			inner join account_tax as t on s.tax_id=t.id  
			where order_line_id=%d and t.tax_group='vat'
			""" % inf[5]
            self.cr.execute(sqlt)
            for tx in self.cr.fetchall():
                if tx:
                    alic = 100 * tx[0]
            tax_line = pooler.get_pool(
                self.cr.dbname).get('sale.order.line').read(
                    self.cr, self.uid, [inf[5]], ['tax_id'])
            if tax_line and tax_line[0] and tax_line[0].has_key('tax_id'):
                impt = len(tax_line[0]['tax_id'])
            if (inf[3] > 0) and (inf[4] > 0):
                total = inf[3] * inf[4]
                self.totalcajas += inf[4]
                self.subtotal += total
            product_fact.append({
                "cod": inf[0],
                "nomb": inf[1],
                "ref": inf[2],
                "cant": inf[4],
                "precio": inf[3],
                "total": total,
                "alic": alic,
                "imp": impt
            })
        return product_fact
def _make_excel_file(self, cr, uid, data, context):
    pool = pooler.get_pool(cr.dbname)
    workBookDocument = xl.Workbook()
    docSheet1 = workBookDocument.add_sheet("Disparus")
    docSheet2 = workBookDocument.add_sheet("Nouveaux")
    docSheet3 = workBookDocument.add_sheet("Chg de noms")
    docSheet4 = workBookDocument.add_sheet("Chg d Etats")
    docSheet5 = workBookDocument.add_sheet("Chg d'Adresses")
    part_photo_obj = pool.get('res.partner.photo')
    partner_obj = pool.get('res.partner')
    cr.execute("select id from res_partner_photo order by date desc")
    photo_id = cr.fetchone()
    photo_id = photo_id and photo_id[0] or False
    photo_rec = part_photo_obj.browse(cr, uid, photo_id)

    list_losts = [u"Clé", "Nom - Forme", "Adresse", "Etat"]
    for header_num, header_item in enumerate(list_losts):
        docSheet1.write(0, header_num, header_item)
    """
        Data of lost partners
    """
    row_count = 0
    for rec in photo_rec.partner_lost_ids:
        row_count += 1
        docSheet1.write(row_count, 0, (rec.partner_id.ref or ''))
        docSheet1.write(row_count, 1, rec.partner_id.name)
        address_def = [((x.street or '') + '- ' + (x.zip_id and x.city or ''))
                       for x in rec.partner_id.address if x.type == 'default']
        if len(address_def):
            docSheet1.write(row_count, 2, address_def[0])
        docSheet1.write(
            row_count, 3,
            (rec.partner_id.state_id and rec.partner_id.state_id.name or ''))
    """
        Data of New partners
    """
    list_new = [u"Clé", "Nom - Forme", "Adresse", "Etat"]
    for header_num, header_item in enumerate(list_new):
        docSheet2.write(0, header_num, header_item)
    row_count = 0
    for rec in photo_rec.partner_new_ids:
        row_count += 1
        docSheet2.write(
            row_count, 0,
            (rec.address_id.partner_id and rec.address_id.partner_id.ref
             or ''))
        docSheet2.write(
            row_count, 1,
            rec.address_id.partner_id and rec.address_id.partner_id.name or '')
        docSheet2.write(row_count, 2, rec.address or '')
        docSheet2.write(
            row_count, 3,
            (rec.address_id.partner_id and rec.address_id.partner_id.state_id
             and rec.address_id.partner_id.state_id.name or ''))
    """
        Data of Changed partners
    """
    list_chg = [u"Clé", "Ancien Nom", "Nouveau nom", "Adresse"]
    for header_num, header_item in enumerate(list_chg):
        docSheet3.write(0, header_num, header_item)
    row_count = 0
    for rec in photo_rec.partner_chg_ids:
        row_count += 1
        docSheet3.write(row_count, 0, (rec.address_id.partner_id.ref or ''))
        docSheet3.write(row_count, 1, rec.address_id.partner_id.name)
        docSheet3.write(row_count, 2, (rec.name or ''))
        address = (rec.address_id.street or '') + ' ' + (
            rec.address_id.zip or '') + '  ' + (rec.address_id.city or '')
        docSheet3.write(row_count, 3, address)
    """
        Data of Changed states
    """
    list_chg_adr = [
        u"Clé", "Nom - Forme", "Ancien Etat", "Nouvel Etat", "Adresse"
    ]
    for header_num, header_item in enumerate(list_chg_adr):
        docSheet4.write(0, header_num, header_item)
    row_count = 0
    for rec in photo_rec.partner_state_ids:
        row_count += 1
        docSheet4.write(row_count, 0, (rec.address_id.partner_id.ref or ''))
        docSheet4.write(row_count, 1, (rec.address_id.partner_id.name or ''))
        docSheet4.write(row_count, 2,
                        (rec.new_state and rec.new_state.name or ''))
        docSheet4.write(row_count, 3,
                        (rec.partner_id and rec.partner_id.state_id
                         and rec.partner_id.state_id.name or ''))
        address = (rec.address_id.street or '') + ' ' + (
            rec.address_id.zip or '') + '  ' + (rec.address_id.city or '')
        docSheet4.write(row_count, 4, address)
    """
        Data of Changed Adresses
    """
    list_chg_adr = [
        u"Clé", "Nom - Forme", "Ancienne Adresse", "Nouvelle Adresse"
    ]
    for header_num, header_item in enumerate(list_chg_adr):
        docSheet5.write(0, header_num, header_item)
    row_count = 0
    for rec in photo_rec.address_chg_ids:
        row_count += 1
        docSheet5.write(row_count, 0, (rec.address_id.partner_id.ref or ''))
        address_def = [
            x.name for x in rec.address_id.partner_id.address
            if x.type == 'default'
        ]
        address_def = address_def and address_def[0] or ''
        docSheet5.write(
            row_count, 1, rec.address_id
            and (rec.address_id.partner_id.name + ' ' + address_def))
        docSheet5.write(row_count, 2, rec.old_address or '')
        docSheet5.write(row_count, 3, rec.new_address or '')
    file = StringIO.StringIO()
    out = workBookDocument.save(file)
    out = base64.encodestring(file.getvalue())
    return {
        'data': out,
        'file_name': 'export_sumo_file%s.xsl' % time.strftime('%Y-%m-%d')
    }
示例#46
0
 def get_fiscalyear(self, fiscalyear_id):
     fiscalyear_obj = pooler.get_pool(self.cr.dbname).get('account.fiscalyear')
     return fiscalyear_obj.read(self.cr, self.uid, [fiscalyear_id], ['name'])[0]['name']
示例#47
0
    def login(self, db, login, password):

        if not password:
            # empty passwords are disallowed for obvious security reasons
            return False

        ret = super(users, self).login(db, login, password)
        if ret:
            return ret
        logger = logging.getLogger('orm.ldap')
        pool = pooler.get_pool(db)
        cr = pooler.get_db(db).cursor()
        action_obj = pool.get('ir.actions.actions')
        cr.execute("""
            SELECT id, company, ldap_server, ldap_server_port, ldap_binddn, ldap_password,
                   ldap_filter, ldap_base, "user", create_user
            FROM res_company_ldap
            WHERE ldap_server != '' and ldap_binddn != '' ORDER BY sequence""")
        for res_company_ldap in cr.dictfetchall():
            logger.debug(res_company_ldap)
            try:
                l = ldap.open(res_company_ldap['ldap_server'],
                              res_company_ldap['ldap_server_port'])
                if l.simple_bind_s(res_company_ldap['ldap_binddn'],
                                   res_company_ldap['ldap_password']):
                    base = res_company_ldap['ldap_base']
                    scope = ldap.SCOPE_SUBTREE
                    filter = filter_format(res_company_ldap['ldap_filter'],
                                           (login, ))
                    retrieve_attributes = None
                    result_id = l.search(base, scope, filter,
                                         retrieve_attributes)
                    timeout = 60
                    result_type, result_data = l.result(result_id, timeout)
                    if not result_data:
                        continue
                    if result_type == ldap.RES_SEARCH_RESULT and len(
                            result_data) == 1:
                        dn = result_data[0][0]
                        logger.debug(dn)
                        name = result_data[0][1]['cn'][0]
                        if l.bind_s(dn, password):
                            l.unbind()
                            cr.execute(
                                "SELECT id FROM res_users WHERE login=%s",
                                (tools.ustr(login), ))
                            res = cr.fetchone()
                            logger.debug(res)
                            if res:
                                cr.close()
                                return res[0]
                            if not res_company_ldap['create_user']:
                                continue
                            action_id = action_obj.search(
                                cr, 1, [('usage', '=', 'menu')])[0]
                            if res_company_ldap['user']:
                                res = self.copy(cr,
                                                1,
                                                res_company_ldap['user'],
                                                default={'active': True})
                                self.write(
                                    cr, 1, res, {
                                        'name': name,
                                        'login': login.encode('utf-8'),
                                        'company_id':
                                        res_company_ldap['company'],
                                    })
                            else:
                                res = self.create(
                                    cr, 1, {
                                        'name': name,
                                        'login': login.encode('utf-8'),
                                        'company_id':
                                        res_company_ldap['company'],
                                        'action_id': action_id,
                                        'menu_id': action_id,
                                    })
                            cr.commit()
                            cr.close()
                            return res
                    l.unbind()
            except Exception:
                logger.warning("Cannot auth", exc_info=True)
                continue
        cr.close()
        return False
def _make_calculation(self, cr, uid, data, context):
    form = data['form']
    pool = pooler.get_pool(cr.dbname)
    partner_obj = pool.get('res.partner')
    partner_ids = partner_obj.search(cr, uid, [('membership_state', 'in',
                                                ('free', 'paid', 'invoiced'))])
    part_address_chg_obj = pool.get('res.partner.address.change')
    part_chg_obj = pool.get('res.partner.change')
    part_photo_obj = pool.get('res.partner.photo')
    cr.execute('select id from res_partner_photo order by date desc limit 1')
    last_photo_id = cr.fetchone()
    last_photo_id = last_photo_id and last_photo_id[0] or False
    part_address_obj = pool.get('res.partner.address')
    part_lost_obj = pool.get('res.partner.address.lost')
    part_address_new_obj = pool.get('res.partner.address.new')
    part_state_obj = pool.get('res.partner.state.register')
    postal_addr = []
    address_l = []
    address_def = []
    list_lost_out = []
    photo_id = part_photo_obj.create(cr, uid, {})
    for partner in partner_obj.browse(cr, uid, partner_ids):
        postal_addr = [
            x.id for x in partner.address
            if x.magazine_subscription in ('postal', 'personal')
        ]
        if not len(postal_addr):
            for address in partner.address:
                never_addr = [
                    x.id for x in partner.address if x.state in ('never')
                ]
                if not never_addr and address.type == 'default':
                    part_address_new_obj.create(
                        cr, uid, {
                            'code':
                            partner.ref,
                            'name':
                            partner.id,
                            'address': (address.street or '') + ' ' +
                            (address.zip or '') + '  ' + (address.city or ''),
                            'address_id':
                            address.id,
                            'photo_id':
                            photo_id,
                            'state_activity':
                            partner.state_id and partner.state_id.id or False
                        })
                    part_address_obj.write(cr, uid, [address.id],
                                           {'magazine_subscription': 'postal'})
    if last_photo_id:
        """
        Create entries for losts partners
        """
        cr.execute(
            "select id from res_partner where (state_id is null or state_id not in (1)) and id not in (select partner_id from res_partner_address_lost)"
        )
        for part_id in cr.dictfetchall():
            partner_id = partner_obj.browse(cr, uid, part_id['id'])
            if len(partner_id.address):
                address_def = [
                    x.id for x in partner_id.address if x.type == 'default'
                ]
                part_lost_obj.create(
                    cr, uid, {
                        'name':
                        partner_id.ref,
                        'address_id':
                        address_def and address_def[0] or False,
                        'partner_id':
                        partner_id.id,
                        'state_activity':
                        partner_id.state_id and partner_id.state_id.id
                        or False,
                        'photo_id':
                        photo_id
                    })
        """
        Create entries for partners changes states
        """
        for state_item in part_photo_obj.browse(
                cr, uid, last_photo_id).partner_state_ids:
            if state_item.new_state.id != state_item.partner_id.state_id.id:
                address_l = [
                    x.id for x in state_item.partner_id.address
                    if x.type == 'default'
                ]
                part_state_obj.create(
                    cr, uid, {
                        'old_state':
                        state_item.new_state and state_item.new_state.id,
                        'new_state':
                        state_item.partner_id.state_id.id,
                        'name':
                        state_item.partner_id.ref,
                        'partner_id':
                        state_item.partner_id.id,
                        'address_id': (address_l and address_l[0]) or
                        (state_item.address_id and state_item.address_id.id)
                        or False,
                        'photo_id':
                        photo_id
                    })
                list_lost_out.append(state_item.partner_id.id)
        """
        Create entries for changed adresses
        """
        for adr_item in part_photo_obj.browse(cr, uid,
                                              last_photo_id).address_chg_ids:
            address_zip = adr_item.address_id.zip_id and adr_item.address_id.zip_id.city or ''
            if adr_item.new_address != (
                (adr_item.address_id.street or '') + '- ' + address_zip):
                part_address_chg_obj.create(
                    cr, uid, {
                        'old_address':
                        adr_item.new_address,
                        'new_address': (adr_item.address_id.street or '') +
                        '- ' + address_zip,
                        'code':
                        adr_item.address_id and adr_item.address_id.partner_id
                        and adr_item.address_id.partner_id.ref or '',
                        'name':
                        adr_item.address_id
                        and adr_item.address_id.partner_id.id or False,
                        'address_id':
                        adr_item and adr_item.address_id.id or False,
                        'photo_id':
                        photo_id
                    })
        """
        Create entries for new adresses
        """
        cr.execute(
            "select id from res_partner_address where magazine_subscription = 'postal' and id not in (select address_id from res_partner_address_new where address_id is not null)"
        )
        for item in cr.dictfetchall():
            address_id = part_address_obj.browse(cr, uid, item['id'])
            if address_id.partner_id.state_id.id in (1):
                address_zip = address_id.zip_id and address_id.zip_id.city or ''
                part_address_new_obj.create(
                    cr, uid, {
                        'name':
                        address_id.partner_id.id,
                        'address_id':
                        address_id.id,
                        'code':
                        address_id.partner_id.ref,
                        'state_activity':
                        address_id.partner_id.state_id
                        and address_id.partner_id.state_id.id or False,
                        'address':
                        (address_id.street or '') + '- ' + address_zip,
                        'photo_id':
                        photo_id
                    })
        """
        Create entries for changed partner names
        """
        for adr_item in part_photo_obj.browse(cr, uid,
                                              last_photo_id).partner_chg_ids:
            if adr_item.address_id and adr_item.address_id.partner_id and (
                    adr_item.address_id.partner_id.id not in list_lost_out):
                partner_name = (adr_item.address_id
                                and adr_item.address_id.partner_id.name +
                                ' ') + (adr_item.address_id.name and
                                        (adr_item.address_id.name or '') or '')
                if (adr_item.name).strip() != partner_name.strip():
                    part_chg_obj.create(
                        cr, uid, {
                            'old_name':
                            adr_item.name,
                            'name':
                            partner_name,
                            'code':
                            adr_item.address_id
                            and adr_item.address_id.partner_id
                            and adr_item.address_id.partner_id.ref or '',
                            'address_id':
                            adr_item and adr_item.address_id.id or False,
                            'photo_id':
                            photo_id
                        })

    return {}
示例#49
0
def _import_account_move_file(self, cr, uid, data, context):
    cont = 0
    ruta = '/home/public/'
    ruta	= "/opt/openerp/reportes/personal/nomina/" # Ruta Server Produccion  
    file_data = data['form']['fdata']
    nf        = data['form']['fname']
    file_name = ruta + data['form']['fname']
    move_id = data['id']
    nomb= nf.split('.')
    if not move_id:
        raise wizard.except_wizard(_('Error !'), _('Debe pulsar el Boton Guardar, antes de procesar el archivo..!') )
    move_obj =  pooler.get_pool(cr.dbname).get('account.move')
    move_data = move_obj.browse(cr, uid, move_id)
    periodo   = move_data.period_id.id
    fecha     = move_data.date
    diario    = move_data.journal_id.id
    ref       = move_data.ref

    #Validaciones----------------------------------------------------------------------------------
    if nomb[1].lower() != 'csv':
        raise wizard.except_wizard(_('Error !'), _('El Archivo no es de tipo CSV, consulte al administrador ') )
    if os.path.exists(file_name):
        raise wizard.except_wizard(_('Error !'), _('El Archivo ya EXISTE por lo tanto no puede ser procesado') )


    #Procesando el Archivo-------------------------------------------------------------------------
    val =base64.decodestring(file_data)
    lines = val.split("\n")
    flines = map( lambda x: x.split(';'), lines )
    list_fail_acc = ''
    for l in flines:
        #print "LIN",l
        acc_id    = ''
        name_desc =''
        haber     = 0
        debe      = 0
        if not l[0]:
            continue
        cta_nro	=	l[0].strip()
        sql = "SELECT id,code,type FROM account_account WHERE code='%s' "%cta_nro
        #print "SQL",sql
        cr.execute (sql)
        result = cr.fetchall()
        #
        if l[1]:
            name_desc = l[1].strip()

        if not result:
            cod = cta_nro.split(".")
            if len(cod) == 6:
                list_fail_acc += cta_nro + ' \n' 
            continue
        if result and result[0]:
            cont += 1
            if result[0][2]=='view':
                list_fail_acc += cta_nro + ' (Vista) \n'
                continue
            acc_id = result[0][0]
        if l[2]:
            debit_debe   = l[2].strip()
            if debit_debe:
                debit_debe   = debit_debe.replace('.','')
                debit_debe   = debit_debe.replace(',','.')
                debe   = float(debit_debe)
        if l[3]:
            credit_haber = l[3].strip()
            if credit_haber:                
                credit_haber = credit_haber.replace('.','')
                credit_haber = credit_haber.replace(',','.')
                haber        = float(credit_haber)
        vals ={
        'move_id':move_id,
        'journal_id':diario,
        'period_id':periodo,
        'account_id':acc_id,
        'partner_id':1,
        'name': name_desc,
        'ref': ref,
        'date':fecha,
        'date_created':fecha,
        'credit':haber,
        'debit':debe,
        'state':'draft',
        'centralisation':'normal',
        'blocked':False
        }
        line_ids = pooler.get_pool(cr.dbname).get('account.move.line').create(cr, uid,vals)

    #Se guarda el Arvhivo procesado----------------------------------------------------------------
    output		= open(file_name,"w")
    output.write(val)
    output.close()
    move_obj.write(cr,uid, [move_id], {'file_name':nomb[0]},context)

    return {'lines_proc':str(cont),'fail_acc':list_fail_acc}
示例#50
0
def try_report_action(cr, uid, action_id, active_model=None, active_ids=None,
                wiz_data=None, wiz_buttons=None,
                context=None, our_module=None):
    """Take an ir.action.act_window and follow it until a report is produced

        :param action_id: the integer id of an action, or a reference to xml id
                of the act_window (can search [our_module.]+xml_id
        :param active_model, active_ids: call the action as if it had been launched
                from that model+ids (tree/form view action)
        :param wiz_data: a dictionary of values to use in the wizard, if needed.
                They will override (or complete) the default values of the
                wizard form.
        :param wiz_buttons: a list of button names, or button icon strings, which
                should be preferred to press during the wizard.
                Eg. 'OK' or 'gtk-print'
        :param our_module: the name of the calling module (string), like 'account'
    """

    if not our_module and isinstance(action_id, basestring):
        if '.' in action_id:
            our_module = action_id.split('.', 1)[0]

    if context is None:
        context = {}
    else:
        context = context.copy() # keep it local
    # TODO context fill-up

    pool = pooler.get_pool(cr.dbname)
    if our_module:
        log = logging.getLogger('tests.%s' % our_module)
    else:
        log = logging.getLogger('tools.test_reports')

    def log_test(msg, *args):
        log.log(netsvc.logging.TEST, "  - " + msg, *args)

    datas = {}
    if active_model:
        datas['model'] = active_model
    if active_ids:
        datas['ids'] = active_ids

    if not wiz_buttons:
        wiz_buttons = []

    if isinstance(action_id, basestring):
        if '.' in action_id:
            act_module, act_xmlid = action_id.split('.', 1)
        else:
            if not our_module:
                raise ValueError('You cannot only specify action_id "%s" without a module name' % action_id)
            act_module = our_module
            act_xmlid = action_id
        act_model, act_id = pool.get('ir.model.data').get_object_reference(cr, uid, act_module, act_xmlid)
    else:
        assert isinstance(action_id, (long, int))
        act_model = 'ir.action.act_window'     # assume that
        act_id = action_id
        act_xmlid = '<%s>' % act_id

    def _exec_action(action, datas, context):
        # taken from client/modules/action/main.py:84 _exec_action()
        if isinstance(action, bool) or 'type' not in action:
            return
        # Updating the context : Adding the context of action in order to use it on Views called from buttons
        if datas.get('id',False):
            context.update( {'active_id': datas.get('id',False), 'active_ids': datas.get('ids',[]), 'active_model': datas.get('model',False)})
        context.update(safe_eval(action.get('context','{}'), context.copy()))
        if action['type'] in ['ir.actions.act_window', 'ir.actions.submenu']:
            for key in ('res_id', 'res_model', 'view_type', 'view_mode',
                    'limit', 'auto_refresh', 'search_view', 'auto_search', 'search_view_id'):
                datas[key] = action.get(key, datas.get(key, None))

            view_id = False
            if action.get('views', []):
                if isinstance(action['views'],list):
                    view_id = action['views'][0][0]
                    datas['view_mode']= action['views'][0][1]
                else:
                    if action.get('view_id', False):
                        view_id = action['view_id'][0]
            elif action.get('view_id', False):
                view_id = action['view_id'][0]

            assert datas['res_model'], "Cannot use the view without a model"
            # Here, we have a view that we need to emulate
            log_test("will emulate a %s view: %s#%s",
                        action['view_type'], datas['res_model'], view_id or '?')

            view_res = pool.get(datas['res_model']).fields_view_get(cr, uid, view_id, action['view_type'], context)
            assert view_res and view_res.get('arch'), "Did not return any arch for the view"
            view_data = {}
            if view_res.get('fields',{}).keys():
                view_data = pool.get(datas['res_model']).default_get(cr, uid, view_res['fields'].keys(), context)
            if datas.get('form'):
                view_data.update(datas.get('form'))
            if wiz_data:
                view_data.update(wiz_data)
            log.debug("View data is: %r", view_data)

            for fk, field in view_res.get('fields',{}).items():
                # Default fields returns list of int, while at create()
                # we need to send a [(6,0,[int,..])]
                if field['type'] in ('one2many', 'many2many') \
                        and view_data.get(fk, False) \
                        and isinstance(view_data[fk], list) \
                        and not isinstance(view_data[fk][0], tuple) :
                    view_data[fk] = [(6, 0, view_data[fk])]

            action_name = action.get('name')
            try:
                from xml.dom import minidom
                cancel_found = False
                buttons = []
                dom_doc = minidom.parseString(view_res['arch'])
                if not action_name:
                    action_name = dom_doc.documentElement.getAttribute('name')

                for button in dom_doc.getElementsByTagName('button'):
                    button_weight = 0
                    if button.getAttribute('special') == 'cancel':
                        cancel_found = True
                        continue
                    if button.getAttribute('icon') == 'gtk-cancel':
                        cancel_found = True
                        continue
                    if button.getAttribute('default_focus') == '1':
                        button_weight += 20
                    if button.getAttribute('string') in wiz_buttons:
                        button_weight += 30
                    elif button.getAttribute('icon') in wiz_buttons:
                        button_weight += 10
                    string = button.getAttribute('string') or '?%s' % len(buttons)

                    buttons.append( { 'name': button.getAttribute('name'),
                                'string': string,
                                'type': button.getAttribute('type'),
                                'weight': button_weight,
                                })
            except Exception, e:
                log.warning("Cannot resolve the view arch and locate the buttons!", exc_info=True)
                raise AssertionError(e.args[0])

            if not datas['res_id']:
                # it is probably an orm_memory object, we need to create
                # an instance
                datas['res_id'] = pool.get(datas['res_model']).create(cr, uid, view_data, context)

            if not buttons:
                raise AssertionError("view form doesn't have any buttons to press!")

            buttons.sort(key=lambda b: b['weight'])
            log.debug('Buttons are: %s', ', '.join([ '%s: %d' % (b['string'], b['weight']) for b in buttons]))

            res = None
            while buttons and not res:
                b = buttons.pop()
                log_test("in the \"%s\" form, I will press the \"%s\" button.", action_name, b['string'])
                if not b['type']:
                    log_test("the \"%s\" button has no type, cannot use it", b['string'])
                    continue
                if b['type'] == 'object':
                    #there we are! press the button!
                    fn =  getattr(pool.get(datas['res_model']), b['name'])
                    if not fn:
                        log.error("The %s model doesn't have a %s attribute!", datas['res_model'], b['name'])
                        continue
                    res = fn(cr, uid, [datas['res_id'],], context)
                    break
                else:
                    log.warning("in the \"%s\" form, the \"%s\" button has unknown type %s",
                        action_name, b['string'], b['type'])
            return res

        elif action['type']=='ir.actions.report.xml':
            if 'window' in datas:
                del datas['window']
            if not datas:
                datas = action.get('datas',{})
            datas = datas.copy()
            ids = datas.get('ids')
            if 'ids' in datas:
                del datas['ids']
            res = try_report(cr, uid, 'report.'+action['report_name'], ids, datas, context, our_module=our_module)
            return res
    def _create_file(self, cr, uid, data, context):
        obj_sample = pooler.get_pool(cr.dbname).get('labo.sample')
        v_sample = obj_sample.browse(cr, uid, data['ids'])
        view_b = v_sample[0]
        view_type = view_b.sample_id.type_id.code
        header_1 = 'Container Name' + '\t' + 'Description' + '\t' + 'ContainerType' + '\t' + 'AppType' + '\t' + 'Owner' + '\t' + 'Operator' + '\n'
        header_2 = 'Well' + '\t' + 'Sample Name' + '\t' + 'Comment' + '\t' + 'Priority' + '\t' + 'Size Standard' + '\t' + 'Snp Set' + '\t' + 'User-Defined 3' + '\t' + 'User-Defined 2' + '\t' + 'User-Defined 1' + '\t' + 'Panel' + '\t' + 'Study' + '\t' + 'Sample Type' + '\t' + 'Analysis Method' + '\t' + 'Results Group 1' + '\t' + 'Instrument Protocol 1' + '\n'
        content = ""
        con = ""
        global_cont = ""
        l = []

        for sample in v_sample:
            v_setup = sample.file_setup and sample.file_setup.set_up and sample.file_setup.set_up.name or ""
            l.append(v_setup)
            l_st = dict([(i, 0) for i in l if i]).keys()
            res = ""
            i = 1
            for k in l_st:
                res += k + "+"
        res = res[0:len(res) - 1]
        file_name = str(res) + '.csv'
        gg = ""
        c = str(data['form']['container_a'] or "")
        k = (data['form']['container_a'] or "")
        fields3 = header_1 + str(res) + '\t' + "" + '\t' + str(
            data['form']['container_a'] or "") + '\t' + 'Regular' + '\t' + str(
                data['form']['owner_a'] or "") + '\t' + str(
                    data['form']['operator_a'] or "") + '\t' + '\n' + header_2
        v_req = sample.sample_id and sample.sample_id.type_id and sample.sample_id.type_id.code or ''
        content = ''
        t = []
        for sample in v_sample:
            #    data_sample= str(sample.num_alpha)+'\t'+str(sample.progenus_number)+'\t'+"comment"+'\t'+str(100)+'\t'+"Size standard"+'\t'+"snp set"+'\t'+"UD3"+'\t'+"UD2"+'\t'+"UD1"+'\t'+'Panel'+'\t'+'Study'+'\t'+'CHECK IR'+'\t'+"METOD"+'\t'+"RES GRP1"+'\t'+str(v_req)+'\n'
            if view_type != 'EMPDOG' and view_type != 'EMPDOG_2' and view_type != 'EMPCHE':
                data_sample = str(sample.num_alpha or "") + '\t' + str(
                    sample.progenus_number or ""
                ) + '\t' + "comment" + '\t' + str(
                    100
                ) + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + '' + '\t' + '' + '\t' + '' + '\t' + "" + '\t' + "" + '\t' + str(
                    v_req) + '\n'
                content += data_sample

            elif view_type == 'EMPDOG' or view_type == 'EMPCHE':
                if sample.dog_child and sample.dog_child.progenus_number and sample.dog_child.progenus_number not in t:
                    data_sample_child = str(
                        sample.dog_child and sample.dog_child.num_alpha or ""
                    ) + '\t' + str(
                        sample.dog_child and sample.dog_child.progenus_number
                        or ""
                    ) + '\t' + "comment" + '\t' + str(
                        100
                    ) + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + '' + '\t' + '' + '\t' + '' + '\t' + "" + '\t' + "" + '\t' + str(
                        v_req) + '\n'
                    content += data_sample_child
                    t.append(sample.dog_child.progenus_number)

                if sample.dog_mother and sample.dog_mother.progenus_number and sample.dog_mother.progenus_number not in t:
                    data_sample_mother = str(
                        sample.dog_mother and sample.dog_mother.num_alpha or ""
                    ) + '\t' + str(
                        sample.dog_mother and sample.dog_mother.progenus_number
                        or ""
                    ) + '\t' + "comment" + '\t' + str(
                        100
                    ) + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + '' + '\t' + '' + '\t' + '' + '\t' + "" + '\t' + "" + '\t' + str(
                        v_req) + '\n'
                    content += data_sample_mother
                    t.append(sample.dog_mother.progenus_number)

                if sample.dog_father and sample.dog_father.progenus_number and sample.dog_father.progenus_number not in t:
                    data_sample_father = str(
                        sample.dog_father and sample.dog_father.num_alpha or ""
                    ) + '\t' + str(
                        sample.dog_father and sample.dog_father.progenus_number
                        or ""
                    ) + '\t' + "comment" + '\t' + str(
                        100
                    ) + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + '' + '\t' + '' + '\t' + '' + '\t' + "" + '\t' + "" + '\t' + str(
                        v_req) + '\n'
                    content += data_sample_father
                    t.append(sample.dog_father.progenus_number)

            elif view_type == 'EMPDOG_2':

                if sample.dog_mother and sample.dog_mother.progenus_number and sample.dog_mother.progenus_number not in t:
                    data_sample_mother = str(
                        sample.dog_mother and sample.dog_mother.num_alpha or ""
                    ) + '\t' + str(
                        sample.dog_mother and sample.dog_mother.progenus_number
                        or ""
                    ) + '\t' + "comment" + '\t' + str(
                        100
                    ) + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + '' + '\t' + '' + '\t' + '' + '\t' + "" + '\t' + "" + '\t' + str(
                        v_req) + '\n'
                    content += data_sample_mother
                    t.append(sample.dog_mother.progenus_number)

                if sample.dog_father and sample.dog_father.progenus_number and sample.dog_father.progenus_number not in t:
                    data_sample_father = str(
                        sample.dog_father and sample.dog_father.num_alpha or ""
                    ) + '\t' + str(
                        sample.dog_father and sample.dog_father.progenus_number
                        or ""
                    ) + '\t' + "comment" + '\t' + str(
                        100
                    ) + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + "" + '\t' + '' + '\t' + '' + '\t' + '' + '\t' + "" + '\t' + "" + '\t' + str(
                        v_req) + '\n'
                    content += data_sample_father
                    t.append(sample.dog_father.progenus_number)

        out = base64.encodestring(fields3 + content)
        return {'data': out, 'file_name': file_name}
示例#52
0
    def generate_records(self, cr, uid, ids, data, context):
        result = []
        pool = pooler.get_pool(cr.dbname)
        move_pool = pool.get('account.move')
        currency_pool = pool.get('res.currency')
        user_pool = pool.get('res.users')
        user_obj = user_pool.browse(cr, uid, uid, context=context)
        company_currency_obj = user_obj.company_id.currency_id
        for move_obj in move_pool.browse(cr, uid, ids, context=context):
            journal = move_obj.journal_id or False
            #             journal_curr = journal.currency and journal.currency or company_currency_obj
            amount = 0.00
            tot_amount = 0.00
            lines = []
            reconsile_objs = []
            customer_list = []
            sett_lines = []
            curr_id = [
                x.currency_id for x in move_obj.line_id if x.currency_id
            ]
            journal_curr = curr_id and curr_id[0] or company_currency_obj
            for line in move_obj.line_id:
                if line.partner_id:
                    customer_list.append(line.partner_id)
                sub_ledger = line.job_id and line.job_id.name or ''
                partner_name = line.partner_id and line.partner_id.name or False
                partner_code = line.partner_id and line.partner_id.partner_ac_code or False
                if line.partner_id:
                    sub_ledger = partner_name
                    if partner_code:
                        sub_ledger = "[%s] %s" % (partner_code, partner_name)
                cheque_no = move_obj.cheque_no or ''
                if move_obj.journal_id.voucher_no_as_ref:
                    cheque_no = move_obj.name or ''
                if line.man_ref:
                    cheque_no = line.man_ref or ''
                amount_currency = line.amount_fc_temp and line.amount_fc_temp or 0.00
                if line.debit != 0.00:
                    tot_amount += abs(amount_currency or 0.00)
                line_vals = {
                    'account_code':
                    line.account_id.code or '',
                    'account_name':
                    line.account_id.name.upper() or '',
                    'partner_code':
                    line.partner_id and line.partner_id.partner_ac_code or '',
                    'partner_name':
                    line.partner_id and line.partner_id.name or '',
                    'sub_ledger':
                    sub_ledger,
                    'ref':
                    cheque_no,
                    'debit':
                    line.debit or 0.00,
                    'credit':
                    line.credit or 0.00,
                    'fc_amount':
                    amount_currency,
                    'remark':
                    line.name or '',
                    'cc':
                    line.analytic_account_id and line.analytic_account_id.code
                    or ''
                }
                lines.append(line_vals)
                if line.voucher_id:
                    line_cr = []
                    for vou_line in line.voucher_id.line_cr_ids:
                        if vou_line.move_line_id and vou_line.amount != 0.00 and vou_line.move_line_id.id != line.id:
                            rec_line = vou_line.move_line_id
                            invoice_date = False
                            if rec_line.invoice:
                                doc_no = rec_line.invoice and rec_line.invoice.number or ''
                            else:
                                doc_no = rec_line.doc_no
                            amount = vou_line.amount
                            print vou_line.type
                            if rec_line.invoice:
                                #                                 doc_no = ''
                                invoice_date = datetime.strptime(
                                    rec_line.invoice.date_invoice, '%Y-%m-%d')
                            rec_vals = {
                                'date':
                                rec_line.date and datetime.strptime(
                                    rec_line.date, '%Y-%m-%d'),
                                'doc_no':
                                doc_no,
                                'amount':
                                abs(amount),
                                'amount_real':
                                amount,
                                'c_r':
                                vou_line.type == 'cr' and 'C' or 'D',
                                'remark':
                                rec_line.name or '',
                                'inv_no':
                                rec_line.invoice and rec_line.invoice.number
                                or '',
                                'inv_date':
                                invoice_date or '',
                            }
                            line_cr.append(rec_vals)
                        if vou_line.move_line_id and vou_line.move_line_id.id == line.id:
                            line_cr = []
                            break
                    line_dr = []
                    for vou_line in line.voucher_id.line_dr_ids:
                        if vou_line.move_line_id and vou_line.amount != 0.00 and vou_line.move_line_id.id != line.id:
                            rec_line = vou_line.move_line_id
                            invoice_date = False
                            if rec_line.invoice:
                                doc_no = rec_line.invoice and rec_line.invoice.number or ''
                            else:
                                doc_no = rec_line.doc_no
                            amount = vou_line.amount
                            if rec_line.invoice:
                                #                                 doc_no = ''
                                invoice_date = datetime.strptime(
                                    rec_line.invoice.date_invoice, '%Y-%m-%d')
                            rec_vals = {
                                'date':
                                rec_line.date and datetime.strptime(
                                    rec_line.date, '%Y-%m-%d'),
                                'doc_no':
                                doc_no,
                                'amount':
                                abs(amount),
                                'amount_real':
                                amount,
                                'c_r':
                                vou_line.type == 'cr' and 'C' or 'D',
                                'remark':
                                rec_line.name or '',
                                'inv_no':
                                rec_line.invoice and rec_line.invoice.number
                                or '',
                                'inv_date':
                                invoice_date or '',
                            }
                            line_dr.append(rec_vals)
                        elif vou_line.move_line_id and vou_line.move_line_id.id == line.id:
                            line_dr = []
                            break
                    sett_lines.extend(line_cr)
                    sett_lines.extend(line_dr)
            sett_lines = [
                dict(t) for t in set([tuple(d.items()) for d in sett_lines])
            ]
            sett_lines = sorted(sett_lines, key=operator.itemgetter('date'))
            amount_curr = currency_pool.amount_word(cr,
                                                    uid,
                                                    journal_curr,
                                                    tot_amount or 0.00,
                                                    context=context)
            bank_name = move_obj.bank_details or ''
            vals = {
                'journal_label':
                journal and journal.voucher_label or '',
                'voucher_code':
                journal.code or '',
                'voucher_name':
                move_obj.name or '',
                'amount_total':
                tot_amount or "0.00",
                'date':
                move_obj.date and datetime.strptime(move_obj.date, '%Y-%m-%d'),
                'partner':
                move_obj.journal_partner_id
                and move_obj.journal_partner_id.name.upper() or '',
                'ref':
                move_obj.ref or '',
                'amount_in_words':
                amount_curr and amount_curr.upper() or '',
                'bank':
                bank_name,
                'check_no':
                move_obj.display_check_details and move_obj.cheque_no or '',
                'check_date':
                move_obj.display_check_details and move_obj.cheque_date
                and datetime.strptime(move_obj.cheque_date, '%Y-%m-%d'),
                'curr_name':
                journal_curr.name == 'AED' and "DIRHAMS" or journal_curr.name,
                'user_name':
                user_obj.name.upper() or '',
                'sett_lines':
                sett_lines
            }

            vals['move_lines'] = lines
            result.append(vals)
        return result
示例#53
0
	def generate_records(self, cr, uid, ids, data, context):		
		pool= pooler.get_pool(cr.dbname)
		return {}
示例#54
0
def _open_statement(self, cr, uid, data, context):
    pool = pooler.get_pool(cr.dbname)
    company_id = pool.get('res.users').browse(cr, uid, uid).company_id.id
    statement_obj = pool.get('account.bank.statement')
    singer_obj = pool.get('singer.statement')
    journal_obj = pool.get('account.journal')
    journal_lst = journal_obj.search(cr, uid, [('company_id', '=', company_id),
                                               ('auto_cash', '=', True)])
    journal_ids = journal_obj.browse(cr, uid, journal_lst)
    for journal in journal_ids:
        ids = statement_obj.search(cr, uid, [('state', '!=', 'confirm'),
                                             ('user_id', '=', uid),
                                             ('journal_id', '=', journal.id)])
        if len(ids):
            raise wizard.except_wizard(
                _('Message'),
                _('You can not open a Cashbox for "%s". \n Please close the cashbox related to. '
                  % (journal.name)))
        sql = """ Select id from account_bank_statement
                                where journal_id=%d
                                and company_id =%d
                                order by id desc limit 1""" % (journal.id,
                                                               company_id)
        singer_ids = None
        cr.execute(sql)
        st_id = cr.fetchone()
        number = ''
        if journal.statement_sequence_id:
            number = pool.get('ir.sequence').get_id(cr, uid, journal.id)
        else:
            number = pool.get('ir.sequence').get(cr, uid,
                                                 'account.bank.statement')


#        statement_id=statement_obj.create(cr,uid,{'journal_id':journal.id,
#                                                  'company_id':company_id,
#                                                  'user_id':uid,
#                                                  'state':'open',
#                                                  'name':number
#                                                  })
        period = statement_obj._get_period(cr, uid, context) or None
        cr.execute(
            "INSERT INTO account_bank_statement(journal_id,company_id,user_id,state,name, period_id,date) VALUES(%d,%d,%d,'open','%s',%d,'%s')"
            % (journal.id, company_id, uid, number, period,
               time.strftime('%Y-%m-%d %H:%M:%S')))
        cr.commit()
        cr.execute(
            "select id from account_bank_statement where journal_id=%d and company_id=%d and user_id=%d and state='open' and name='%s'"
            % (journal.id, company_id, uid, number))
        statement_id = cr.fetchone()[0]
        if st_id:
            statemt_id = statement_obj.browse(cr, uid, st_id[0])
            if statemt_id and statemt_id.ending_details_ids:
                statement_obj.write(cr, uid, [statement_id], {
                    'balance_start': statemt_id.balance_end,
                    'state': 'open'
                })
                if statemt_id.ending_details_ids:
                    for i in statemt_id.ending_details_ids:
                        c = singer_obj.create(
                            cr, uid, {
                                'pieces': i.pieces,
                                'number': i.number,
                                'starting_id': statement_id,
                            })
        cr.commit()
    return {}
 def _get_company(self, form):
     self.data = form
     return pooler.get_pool(self.cr.dbname).get('res.company').browse(
         self.cr, self.uid, form['company_id']).name
示例#56
0
    def create(self, cr, uid, ids, datas, context={}):
        pool = pooler.get_pool(cr.dbname)
        res = pool.get("res.lang").search(cr, uid, [("code", "=", "th_TH")])
        if not res:
            raise Exception("Thai language not installed")
        lang_id = res[0]
        lang = pool.get("res.lang").browse(cr, uid, lang_id)

        period_id = datas["form"]["period_id"]
        period = pool.get("account.period").browse(cr, uid, period_id)
        fy = period.fiscalyear_id
        user = pool.get("res.users").browse(cr, uid, uid)

        year = int(fy.date_stop[:4]) + 543
        month = int(period.date_stop[5:7])

        partner = user.company_id.partner_id
        vals = {
            "place_name": partner.name,
            "year": year,
            "branch_code": "00000",
            "cb_pnd_attach": "Yes",
            "cb_tredecim": "Yes",
            "cb_ordinary_filling": "Yes",
        }

        addr = partner.address[0]
        vals.update({
            "road": addr.street,
            "district": addr.city,
            "province": addr.state_id.name or "",
            "tel": addr.phone,
        })

        ids = pool.get("account.tax.code").search(cr, uid,
                                                  [("code", "like", "PP30_")])
        for tc in pool.get("account.tax.code").browse(
                cr, uid, ids, {"period_id": period_id}):
            vals[tc.code.replace("PP30_", "tax")] = tc.sum_period

        vals.update({
            "tax1": vals["tax4"],
            "tax2": 0.0,
            "tax3": 0.0,
        })
        vals.update({
            "tax8":
            vals["tax5"] > vals["tax7"] and vals["tax5"] - vals["tax7"] or 0.0,
            "tax9":
            vals["tax7"] > vals["tax5"] and vals["tax7"] - vals["tax5"] or 0.0,
            "tax10":
            0.0,
        })
        vals.update({
            "tax11": vals["tax8"],
            "tax12": vals["tax9"],
        })
        set_satang(vals)

        vals.update({
            "head_office": "Yes",
            "ordinary_filing": "Yes",
            "zipcode": addr.zip,
            "%d" % month: "Yes",
            "tin": partner.tin and fmt_tin(partner.tin) or "",
            "tax1": str(vals["tax1"]) + " " + "%.2d" % (vals["st1"]),
            "tax2": str(vals["tax2"]) + " " + "%.2d" % (vals["st2"]),
            "tax3": str(vals["tax3"]) + " " + "%.2d" % (vals["st3"]),
            "tax4": str(vals["tax4"]) + " " + "%.2d" % (vals["st4"]),
            "tax5": str(vals["tax5"]) + " " + "%.2d" % (vals["st5"]),
            "tax6": str(vals["tax6"]) + " " + "%.2d" % (vals["st6"]),
            "tax7": str(vals["tax7"]) + " " + "%.2d" % (vals["st7"]),
            "tax8": str(vals["tax8"]) + " " + "%.2d" % (vals["st8"]),
            "tax9": str(vals["tax9"]) + " " + "%.2d" % (vals["st9"]),
            "tax10": str(vals["tax10"]) + " " + "%.2d" % (vals["st10"]),
            "tax11": str(vals["tax11"]) + " " + "%.2d" % (vals["st11"]),
            "tax12": str(vals["tax12"]) + " " + "%.2d" % (vals["st12"]),
            "pay_more": vals["tax12"] and "Yes" or "No",
        })

        pdf = pdf_fill("addons/ac_account_thai/report/pdf/vat_pp30.pdf", vals)

        # attachments for output vat
        ids = pool.get("account.move.line").search(
            cr, uid, [("tax_code_id.code", "=", "PP30_5"),
                      ("period_id", "=", period_id)])
        item_no = 0
        PAGE_SIZE = 20
        for p in range(0, len(ids), PAGE_SIZE):
            ids2 = ids[p:p + PAGE_SIZE]
            if not ids2:
                break
            vals = {
                "year": year,
                "month": month,
                "name": partner.name,
                "tin": partner.tin and partner.tin or "",
                "page_no": p / PAGE_SIZE + 1,
                "page_total": (len(ids) + PAGE_SIZE - 1) / PAGE_SIZE,
                "date": time.strftime("%d-%m-%Y"),
                "repeatIn": repeatIn,
            }
            lines = []
            total_base = 0.0
            total_tax = 0.0
            for ml in pool.get("account.move.line").browse(cr, uid, ids2):
                cust = ml.partner_id
                addr = cust.address[0]
                res = pool.get("account.move.line").search(
                    cr, uid, [("tax_code_id.code", "=", "PP30_4"),
                              ("move_id", "=", ml.move_id.id)])
                ml2_id = res[0]
                ml2 = pool.get("account.move.line").browse(cr, uid, ml2_id)
                item_no += 1
                lines.append({
                    "item_no":
                    item_no,
                    "invoice":
                    ml.invoice and ml.invoice.number or "N/A",
                    "date":
                    ml.date,
                    "customer":
                    cust.name,
                    "base":
                    lang.format("%.2f", ml2.tax_amount, grouping=True),
                    "tax":
                    lang.format("%.2f", ml.tax_amount, grouping=True),
                })
                total_base += ml2.tax_amount
                total_tax += ml.tax_amount
            vals.update({
                "lines":
                lines,
                "total_base":
                lang.format("%.2f", total_base, grouping=True),
                "total_tax":
                lang.format("%.2f", total_tax, grouping=True),
            })
            pdf2 = rml2pdf("addons/ac_account_thai/report/rml/output_vat.rml",
                           vals)
            pdf = pdf_merge(pdf, pdf2)

        # attachments for input vat
        ids = pool.get("account.move.line").search(
            cr, uid, [("tax_code_id.code", "=", "PP30_7"),
                      ("period_id", "=", period_id)])
        item_no = 0
        PAGE_SIZE = 20
        for p in range(0, len(ids), PAGE_SIZE):
            ids2 = ids[p:p + PAGE_SIZE]
            if not ids2:
                break
            vals = {
                "year": year,
                "month": month,
                "name": partner.name,
                "tin": partner.tin,
                "page_no": p / PAGE_SIZE + 1,
                "page_total": (len(ids) + PAGE_SIZE - 1) / PAGE_SIZE,
                "date": time.strftime("%Y-%m-%d"),
                "repeatIn": repeatIn,
            }
            lines = []
            total_base = 0.0
            total_tax = 0.0
            for ml in pool.get("account.move.line").browse(cr, uid, ids2):
                supp = ml.partner_id
                addr = supp.address[0]
                res = pool.get("account.move.line").search(
                    cr, uid, [("tax_code_id.code", "=", "PP30_6"),
                              ("move_id", "=", ml.move_id.id)])
                ml2_id = res[0]
                ml2 = pool.get("account.move.line").browse(cr, uid, ml2_id)
                item_no += 1
                lines.append({
                    "item_no":
                    item_no,
                    "invoice":
                    ml.invoice and ml.invoice.number or "N/A",
                    "date":
                    ml.date,
                    "supplier":
                    supp.name,
                    "base":
                    lang.format("%.2f", ml2.tax_amount, grouping=True),
                    "tax":
                    lang.format("%.2f", ml.tax_amount, grouping=True),
                })
                total_base += ml2.tax_amount
                total_tax += ml.tax_amount
            vals.update({
                "lines":
                lines,
                "total_base":
                lang.format("%.2f", total_base, grouping=True),
                "total_tax":
                lang.format("%.2f", total_tax, grouping=True),
            })
            pdf2 = rml2pdf("addons/ac_account_thai/report/rml/input_vat.rml",
                           vals)
            pdf = pdf_merge(pdf, pdf2)

        return (pdf, "pdf")
示例#57
0
    def synchronize(self, cr, uid, server, object, context=None):
        pool = pooler.get_pool(cr.dbname)
        self.meta = {}
        ids = []
        pool1 = RPCProxy(server)
        pool2 = pool
        #try:
        if object.action in ('d', 'b'):
            ids = pool1.get('base.synchro.obj').get_ids(
                cr, uid, object.model_id.model, object.synchronize_date,
                eval(object.domain), {'action': 'd'})
        if object.action in ('u', 'b'):
            ids += pool2.get('base.synchro.obj').get_ids(
                cr, uid, object.model_id.model, object.synchronize_date,
                eval(object.domain), {'action': 'u'})
        ids.sort()
        iii = 0
        for dt, id, action in ids:
            print 'Process', dt, id, action
            iii += 1
            if action == 'u':
                pool_src = pool2
                pool_dest = pool1
            else:
                pool_src = pool1
                pool_dest = pool2
            print 'Read', object.model_id.model, id
            fields = False
            if object.model_id.model == 'crm.case.history':
                fields = ['email', 'description', 'log_id']
            value = pool_src.get(object.model_id.model).read(
                cr, uid, [id], fields)[0]
            value = self.data_transform(cr, uid, pool_src, pool_dest,
                                        object.model_id.model, value, action)
            id2 = self.get_id(cr, uid, object.id, id, action, context)
            #
            # Transform value
            #
            #tid=pool_dest.get(object.model_id.model).name_search(cr, uid, value['name'],[],'=',)
            if not (iii % 50):
                print 'Record', iii

            # Filter fields to not sync
            for field in object.avoid_ids:
                if field.name in value:
                    del value[field.name]

            if id2:
                #try:
                pool_dest.get(object.model_id.model).write(
                    cr, uid, [id2], value)
                #except Exception, e:
                #self.report.append('ERROR: Unable to update record ['+str(id2)+']:'+str(value.get('name', '?')))
                self.report_total += 1
                self.report_write += 1
            else:
                print value
                idnew = pool_dest.get(object.model_id.model).create(
                    cr, uid, value)
                synid = self.pool.get('base.synchro.obj.line').create(
                    cr, uid, {
                        'obj_id': object.id,
                        'local_id': (action == 'u') and id or idnew,
                        'remote_id': (action == 'd') and id or idnew
                    })
                self.report_total += 1
                self.report_create += 1
        self.meta = {}
        return True
 def _get_currency(self, form):
     return pooler.get_pool(self.cr.dbname).get('res.company').browse(
         self.cr, self.uid, form['company_id']).currency_id.name
 def change_digit(cr):
     res = pooler.get_pool(cr.dbname).get('decimal.precision').precision_get(cr, 1, application)
     return (16, res)
 def _get_defaults(self, cr, uid, data, context):
     fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear')
     data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid)
     data['form']['report_type'] = 'only_obj'
     return data['form']