Пример #1
0
def email_send(cr, uid, ids, to_adr, description, context={}):
    for task in pooler.get_pool(cr.dbname).get('project.task').browse(cr, uid, ids, context):
        project = task.project_id
        subject = "Task '%s' closed" % task.name
        if task.user_id and task.user_id.address_id and task.user_id.address_id.email:
            from_adr = task.user_id.address_id.email
            signature = task.user_id.signature
        else:
            raise wizard.except_wizard(_('Error'), _("Couldn't send mail because your email address is not configured!"))

        if to_adr:
            val = {
                'name': task.name,
                'user_id': task.user_id.name,
                'task_id': "%d/%d" % (project.id, task.id),
                'date_start': task.date_start,
                'date_close': task.date_close,
                'state': task.state
            }
            header = (project.warn_header or '') % val
            footer = (project.warn_footer or '') % val
            body = u'%s\n%s\n%s\n\n-- \n%s' % (header, description, footer, signature)
            email(from_adr, [to_adr], subject, body.encode('utf-8'), email_bcc=[from_adr])
        else:
            raise wizard.except_wizard(_('Error'), _("Couldn't send mail because the contact for this task (%s) has no email address!") % contact.name)
 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 _lang_install(self, cr, uid, data, context):
        fname = data['form']['contrib']
        ir_translation_contrib = pooler.get_pool(cr.dbname).get('ir.translation.contribution')        
        try :
            contrib = s.get_contrib(self.user,self.password,self.lang,self.version,self.profile,fname)
            if not contrib :
                raise wizard.except_wizard('Error !!', 'Bad User name or Passsword or you are not authorised for this language')
            
#It is assumed that res_id is properly set and we dnt need to apply any further calculation for it

            for c in contrib :
                vals = {}
                ids = ir_translation_contrib.search(cr,uid,[('type','=',c['type']),('name','=',c['name']),('src','=',c['src']),('lang','=',self.lang)])
                if ids:
                    ir_translation_contrib.write(cr,uid,ids,{'value':c['value'],'src':c['src']})
                if not ids:
                    vals['type']=c['type']
                    vals['name']=c['name']
                    vals['src']=c['src']
                    vals['value']=c['value']
                    vals['res_id']=c['res_id']
                    vals['lang'] = self.lang
                    id = ir_translation_contrib.create(cr,uid,vals)
                    wf_service = netsvc.LocalService("workflow")
                    wf_service.trg_validate(uid, 'ir.translation.contribution', id, 'button_propose', cr)
                    
         #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")
Пример #4
0
def _check(self, cursor, uid, data, context):
    """Check if the invoice is ready to be printed"""
    pool = pooler.get_pool(cursor.dbname)
    invoice_obj = pool.get("account.invoice")
    for invoice in invoice_obj.browse(cursor, uid, data["ids"], context):
        if not invoice.partner_bank:
            raise wizard.except_wizard(
                "UserError",
                "No bank specified on invoice:\n"
                + invoice_obj.name_get(cursor, uid, [invoice.id], context=context)[0][1],
            )
        if not re.compile("[0-9][0-9]-[0-9]{3,6}-[0-9]").match(invoice.partner_bank.bvr_number or ""):
            raise wizard.except_wizard(
                "UserError",
                "Your bank BVR number should be of the form 0X-XXX-X! "
                + "Please check your company "
                + "information for the invoice:\n"
                + invoice_obj.name_get(cursor, uid, [invoice.id], context=context)[0][1],
            )
        if invoice.partner_bank.bvr_adherent_num and not re.compile("[0-9]*$").match(
            invoice.partner_bank.bvr_adherent_num
        ):
            raise wizard.except_wizard(
                "UserError",
                "Your bank BVR adherent number must contain exactly seven"
                + "digits!\nPlease check your company "
                + "information for the invoice:\n"
                + +invoice_obj.name_get(cursor, uid, [invoice.id], context=context)[0][1],
            )
    return {}
Пример #5
0
 def _confirm(self,cr,uid,data,context):
     print "_confirm"
     pool=pooler.get_pool(cr.dbname)
     all_pv_ids=data["ids"]
     pv_groups={}
     for pv in pool.get("account.voucher").browse(cr,uid,all_pv_ids):
         if pv.type!="payment":
             raise wizard.except_wizard("Error","Wrong voucher type: %s"%pv.name)
         if pv.state in ("paid","posted"):
             raise wizard.except_wizard("Error","Payment voucher is already paid: %s"%pv.name)
         if pv.state!="checked":
             raise wizard.except_wizard("Error","Payment voucher is not approved: %s"%pv.name)
         pv_groups.setdefault(pv.pay_mode_id.id,[]).append(pv)
     bp_ids=[]
     for pay_mode_id,pvs in pv_groups.items():
         vals={
             "pay_mode_id": pay_mode_id,
         }
         bp_id=pool.get("batch.payment").create(cr,uid,vals)
         bp_ids.append(bp_id)
         for pv in pvs:
             pv.write({"batch_pay_id":bp_id})
     return {
         "type": "ir.actions.act_window",
         "res_model": "batch.payment",
         "domain": [("id","in",bp_ids)],
         "view_type": "form",
         "view_mode": "tree,form",
         "name": "Batch Payment",
     }
def _do_export(self, cr, uid, data, context):
    self.pool = pooler.get_pool(cr.dbname)
    esale_category_obj = self.pool.get('esale.oscom.category')
    product_obj = self.pool.get('product.product')

    product_ids = data['ids']
    category_ids_dict = {}
    products = product_obj.browse(cr, uid, product_ids)
    if len(product_ids) > 1:
        for product in products:
            product_by_category_list = category_ids_dict.get(product.categ_id.id, False)
            if product_by_category_list and len(product_by_category_list):
                product_by_category_list.append(product.id)
            else:
                category_ids_dict[product.categ_id.id] = [product.id]
        for category_id in category_ids_dict:
            web_categ_id = esale_category_obj.search(cr, uid, [('category_id','=',category_id)])
            if not len (web_categ_id):
                raise wizard.except_wizard(_('User Error'), _('Select only products which belong to a web category!'))
    else:
        oerp_category_id = products[0].categ_id.id
        web_categ_id = esale_category_obj.search(cr, uid, [('category_id','=',oerp_category_id)])
        if not len(web_categ_id):
            raise wizard.except_wizard(_('User Error'), _('This product must belong to a web category!'))

    return product_obj.oscom_export(cr, uid, product_ids=product_ids, context=context)
Пример #7
0
def _pay_and_reconcile(self, cr, uid, data, context):
    if not abs(data['form']['total'] - (data['form']['amount']+data['form']['amount2']+data['form']['amount3']))<0.01:
        rest=data['form']['total']-(data['form']['amount']+data['form']['amount2']+data['form']['amount3'])
        raise wizard.except_wizard('Payment aborted !', 'You should pay all the total: "%.2f" are missing to accomplish the payment.' %(round(rest,2)))
    
    pool = pooler.get_pool(cr.dbname)
    lots = pool.get('auction.lots').browse(cr,uid,data['ids'],context)
    ref_bk_s=pooler.get_pool(cr.dbname).get('account.bank.statement.line')
    
    for lot in lots:
        if data['form']['buyer_id']:
            pool.get('auction.lots').write(cr,uid,[lot.id],{'ach_uid':data['form']['buyer_id']})
        if not lot.auction_id:
            raise wizard.except_wizard('Error !', 'No auction date for "%s": Please set one.'%(lot.name))
        pool.get('auction.lots').write(cr,uid,[lot.id],{'is_ok':True})
    
    for st,stamount in [('statement_id1','amount'),('statement_id2','amount2'),('statement_id3','amount3')]:
        if data['form'][st]:
            new_id=ref_bk_s.create(cr,uid,{
                'name':'Buyer:'+str(lot.ach_login or '')+', auction:'+ lots[0].auction_id.name,
                'date': time.strftime('%Y-%m-%d'),
                'partner_id':data['form']['buyer_id'] or False,
                'type':'customer',
                'statement_id':data['form'][st],
                'account_id':lot.auction_id.acc_income.id,
                'amount':data['form'][stamount]
            })
            for lot in lots:
                pool.get('auction.lots').write(cr,uid,[lot.id],{'statement_id':[(4,new_id)]})
    return {}
    def _select_prices_prog(self, cr, uid, data, context):
        if context.has_key('prices_prog_id'):
            prices_prog_id = context['prices_prog_id']
        else :
            prices_prog_id = data['form']['prices_progression']

        pool=pooler.get_pool(cr.dbname)
        prop_obj=pool.get('dm.campaign.proposition').browse(cr, uid, data['ids'])[0]
        offer_id=prop_obj.camp_id.offer_id.id
        step_ids=pool.get('dm.offer.step').search(cr, uid, [('offer_id', '=', offer_id)])
        step_obj=pool.get('dm.offer.step').browse(cr, uid, step_ids)
        pprog_obj=pool.get('dm.campaign.proposition.prices_progression').browse(cr, uid, prices_prog_id)
        if prop_obj.item_ids:
            for p in prop_obj.item_ids:
                pool.get('dm.campaign.proposition.item').unlink(cr, uid, p.id)

        stp=0

        """Creates proposition items"""
        if not prop_obj.camp_id.state == 'draft':
            raise wizard.except_wizard(_('UserError'),_('Campaign should be in draft state'))
        for step in step_obj:
            for item in step.item_ids:
                if item:
                    if prop_obj.force_sm_price:
                        if prop_obj.price_prog_use:
                            if pprog_obj.type == 'fixed':
                                price = prop_obj.sm_price + (stp * pprog_obj.value)
                            elif pprog_obj.type == 'percent':
                                price = prop_obj.sm_price + (prop_obj.sm_price * ((stp * pprog_obj.value) / 100))
                        else:
                            price = prop_obj.sm_price
                    else :
                        if not prop_obj.customer_pricelist_id:
                            raise wizard.except_wizard('Error !', 'Select a product pricelist !')
                        price = pool.get('product.pricelist').price_get(cr, uid,
                            [prop_obj.customer_pricelist_id.id], item.id, 1.0,
                            context=context)[prop_obj.customer_pricelist_id.id]

                    vals = {'product_id' : item.id,
                            'proposition_id' : data['ids'][0],
                            'offer_step_id' : step.id,
                            'qty_planned' : item.virtual_available,
                            'qty_real' : item.qty_available,
                            'price': price,
                            'notes': item.description,
                            'forecasted_yield' : step.forecasted_yield,
                            'qty_default' : item.qty_default,
                            'forwarding_charge' : prop_obj.forwarding_charge
                            }
                    new_id=pool.get('dm.campaign.proposition.item').create(cr, uid, vals)
            stp=stp+1
        """
        pool=pooler.get_pool(cr.dbname)
        prop_obj = pool.get('dm.campaign.proposition')
        for r in prop_obj.browse(cr, uid, data['ids']):
            if not r.campaign_group_id:
                camp_obj.write(cr, uid, r.id, {'campaign_group_id': group_id})
        """
        return {}
Пример #9
0
 def _construct_bvr_in_chf(self,bvr_string):
         if len(bvr_string) <> 53:
             raise wizard.except_wizard('AccountError', 
                 'BVR CheckSum Error Première partie')
         elif self._check_number(bvr_string[0:12]) <> int(bvr_string[12]):
             raise wizard.except_wizard('AccountError', 
                 'BVR CheckSum Error Deuxième partie')
         elif self._check_number(bvr_string[14:40]) <> int(bvr_string[40]):
             raise wizard.except_wizard('AccountError', 
                 'BVR CheckSum Error troisème partie')
         elif self._check_number(bvr_string[43:51]) <> int(bvr_string[51]):
             raise wizard.except_wizard('AccountError', 
                 'BVR CheckSum Error 4 partie')
         else:
                 bvr_struct = {
                               'type' : bvr_string[0:2],
                               'amount' : float(bvr_string[2:12])/100,
                               'reference' : bvr_string[14:41],
                               'bvrnumber' : bvr_string[14:20],
                               'beneficiaire' : self._create_bvr_account(
                                     bvr_string[43:52]
                                 ),
                               'domain' : '',
                               'currency' : ''
                               }
                 return bvr_struct
Пример #10
0
 def _construct_bvrplus_in_chf(self,bvr_string):
         ##
         if len(bvr_string) <> 43:
             raise wizard.except_wizard('AccountError', 
                 'BVR CheckSum Error Première partie')
         elif self._check_number(bvr_string[0:2]) <> int(bvr_string[2]):
             raise wizard.except_wizard('AccountError', 
                 'BVR CheckSum Error Deuxième partie')
         elif self._check_number(bvr_string[4:30]) <> int(bvr_string[30]):
             raise wizard.except_wizard('AccountError', 
                 'BVR CheckSum Error troisème partie')
         elif self._check_number(bvr_string[33:41]) <> int(bvr_string[41]):
             raise wizard.except_wizard('AccountError', 
                 'BVR CheckSum Error 4 partie')
         else:
                 bvr_struct = {
                               'type' : bvr_string[0:2],
                               'amount' : 0.0,
                               'reference' : bvr_string[4:31],
                               'bvrnumber' : bvr_string[4:10],
                               'beneficiaire' : self._create_bvr_account(
                                     bvr_string[33:42]
                                 ),
                               'domain' : '',
                               'currency' : ''
                               }
                 return bvr_struct
 def _check(self, invoices):
     """Check if the invoice is ready to be printed"""
     cursor = self.cr
     pool = self.pool
     invoice_obj = pool.get('account.invoice')
     ids = [x.id for x in invoices]
     for invoice in invoice_obj.browse(cursor, self.uid, ids):
         if not invoice.partner_bank_id:
             raise wizard.except_wizard(_('UserError'),
                     _('No bank specified on invoice:\n' + \
                             invoice_obj.name_get(cursor, self.uid, [invoice.id],
                                 context={})[0][1]))
         if not self._compile_check_bvr.match(
                 invoice.partner_bank_id.post_number or ''):
             raise wizard.except_wizard(_('UserError'),
                     _("Your bank BVR number should be of the form 0X-XXX-X! " +
                             'Please check your company ' +
                             'information for the invoice:\n' + 
                             invoice_obj.name_get(cursor, self.uid, [invoice.id],
                                 context={})[0][1]))
         if invoice.partner_bank_id.bvr_adherent_num \
                 and not self._compile_check_bvr_add_num.match(
                         invoice.partner_bank_id.bvr_adherent_num):
             raise wizard.except_wizard('UserError',
                     'Your bank BVR adherent number must contain exactly seven' +
                             'digits!\nPlease check your company ' +
                             'information for the invoice:\n' +
                             invoice_obj.name_get(cursor, self.uid, [invoice.id],
                                 context={})[0][1])
     return ""
 def _get_accounts(self, cr, uid, data, context):
     """give the default aa that are recursively linked to timesheet line
     it will retviev the upper level parent account"""
     if not len(data['ids']):
         return {}
     ids = ','.join(map(str,data['ids']))
     try :
         cr.execute   (
                         "SELECT distinct(a.parent_id) \
                         from account_analytic_account \
                         a join account_analytic_line l \
                         on (l.account_id=a.id) where l.id IN (%s) ;" %(ids,)
                         )
         projects_ids = cr.fetchall()
         cr.execute(
                     "SELECT l.id from account_analytic_account \
                      a join account_analytic_line l \
                      on (l.account_id=a.id) \
                      where l.id IN (%s) \
                      and invoice_id is not null;"%(ids,)
                 )
         test=cr.fetchall()
         if len (test)>0:
             raise wizard.except_wizard(
                                         'Error !', 
                                         'Please select only line wich \
                                          are not already invoiced !!!'
                                         )
     except Exception, e :
         cr.rollback()
         raise wizard.except_wizard(
                                     'Error !', 
                                      str(e)
                                   )
def _numerotate_alpha(self,cr,uid,data,context={}):
    list_alpha=['A01','B01','C01','D01','E01','F01','G01','H01',
                'A02','B02','C02','D02','E02','F02','G02','H02',
                'A03','B03','C03','D03','E03','F03','G03','H03',
                'A04','B04','C04','D04','E04','F04','G04','H04',
                'A05','B05','C05','D05','E05','F05','G05','H05',
                'A06','B06','C06','D06','E06','F06','G06','H06',
                'A07','B07','C07','D07','E07','F07','G07','H07',
                'A08','B08','C08','D08','E08','F08','G08','H08',
                'A09','B09','C09','D09','E09','F09','G09','H09',
                'A10','B10','C10','D10','E10','F10','G10','H10',
                'A11','B11','C11','D11','E11','F11','G11','H11',
                'A12','B12','C12','D12','E12','F12','G12','H12'
                ]
    st_a=data['form']['start_alpha'].upper()
    la_a=data['form']['last_alpha'].upper()
    
    if st_a not in list_alpha:
        raise wizard.except_wizard('Error!', 'Please, Set the right number to the first number')

    if la_a not in list_alpha:
        raise wizard.except_wizard('Error!', 'Please, Set the right number to the last number ')
    
    obj_ls = pooler.get_pool(cr.dbname).get('labo.sample')
    refs_ls=obj_ls.browse(cr,uid,data['ids'])
    start_at=list_alpha.index(st_a)
    stop_at=list_alpha.index(la_a)
    if stop_at<start_at:
        raise wizard.except_wizard('Error!', 'Please check your numerotation "%s" comes after "%s"'%(st_a,la_a))

    for r in refs_ls:
        if start_at<=stop_at:
            k=obj_ls.write(cr,uid,[r.id],{'num_alpha':list_alpha[start_at]})
        start_at+=1
    return{}
 def _associate(self, cr, uid, data, context):
     """ function that will fill the field invoice_id of analytic lines"""
     if len (data['ids'])<1:
         raise wizard.except_wizard(
                                     'Error !', 
                                     'You must select at leat one line !'
                                 )
     try :
         pool = pooler.get_pool(cr.dbname)
         line_ids = data['ids']
         line_obj=pool.get('account.analytic.line')
         vals =  {'invoice_id': data['form']['invoice']}
         for line_id in line_ids:
             line_obj.write(
                             cr, 
                             uid, 
                             line_id,
                             vals
                         )
         return  {
                 'domain': "[('id','=', "+str(data['form']['invoice'])+")]",
                 'name': 'Invoices',
                 'view_type': 'form',
                 'view_mode': 'tree,form',
                 'res_model': 'account.invoice',
                 'view_id': False,
                 'type': 'ir.actions.act_window'
             }
     except Exception, e:
         raise wizard.except_wizard(
                                     'Error !', 
                                      str(e.name)+' '+str(e.value)
                                   )
Пример #15
0
 def _scheduling(self, cr, uid, data, context):
     pool = pooler.get_pool(cr.dbname)
     hr_int_obj = pool.get("hr.interview")
     if time.strptime(str(data['form']['start_interview']),"%Y-%m-%d %H:%M:%S") < time.strptime(data['form']['end_interview'],"%Y-%m-%d %H:%M:%S") and time.strptime(str(data['form']['start_interview']),"%Y-%m-%d %H:%M:%S")[:3] ==time.strptime(str(data['form']['end_interview']),"%Y-%m-%d %H:%M:%S")[:3] :  
         if datetime.datetime(*time.strptime(str(data['form']['end_interview']),"%Y-%m-%d %H:%M:%S")[:6]) >= datetime.datetime(*time.strptime(str(data['form']['start_interview']),"%Y-%m-%d %H:%M:%S")[:6]) + datetime.timedelta(minutes=int(data['form']['interval_time'])):
             cur_time = data['form']['start_interview']
             re_id = deepcopy(data['ids'])
             list_all="Interview ID \t Name "
             for rec in data['ids']:
                 wf_service = netsvc.LocalService('workflow')
                 wf_service.trg_validate(uid, 'hr.interview', rec, 'state_scheduled', cr)
                 record = hr_int_obj.read(cr,uid,rec,['hr_id','name'])
                 list_all +="\n" + record['hr_id']+"\t\t" + record['name'] 
                 id = hr_int_obj.write(cr,uid,rec,{'date':cur_time,'state':'scheduled'})
                 cur_time  = datetime.datetime(*time.strptime(str(cur_time),"%Y-%m-%d %H:%M:%S")[:6]) + datetime.timedelta(minutes=int(data['form']['interval_time']))
                 re_id.remove(rec)
                 end_time  = datetime.datetime(*time.strptime(str(cur_time),"%Y-%m-%d %H:%M:%S")[:6]) + datetime.timedelta(minutes=int(data['form']['interval_time']))
                 if len(re_id) > 0 and time.strptime(str(end_time),"%Y-%m-%d %H:%M:%S") > time.strptime(data['form']['end_interview'],"%Y-%m-%d %H:%M:%S") :
                     remain="Interview ID \t Name "
                     for record in hr_int_obj.read(cr,uid,re_id,['hr_id','name']):
                         remain +="\n" + record['hr_id']+"\t\t" + record['name'] 
                     data['form']['list']=remain
                     data['form']['list_all']=list_all
                     return data['form']
         else :
             raise  wizard.except_wizard(_('UserError'),_('Insert appropriate interval time!!!'))
             return {}
     else :
         raise  wizard.except_wizard(_('UserError'),_('The Scheduling is not Appropriate. Enter appropriate date and time '))
         return {}
     
     data['form']['list_all']= list_all
     data['form']['list']= "None"
     
     return data['form']
def _send_fax(self, cr, uid, datas, context):
	# Number of sent FAX
	nbOk = 0
	nbError = 0
	logger = netsvc.Logger()
	pool = pooler.get_pool(cr.dbname)
	# Get file attachement and prepare for sending
	if datas['form']['attachment']:
		fFax = "/tmp/hfx_attach" + str(random.randint(0,100))
		try:
			fc = open(fFax, "w")
			fc.write(base64.decodestring(datas['form']['attachment']))
			fc.close()
		except IOError:
			raise wizard.except_wizard('[HeoFAX - Error]', 'Unable to open temporary file for file attachement: %s !!!' % fFax)
		cmd['listFile'].append(fFax)
		if debug: logger.notifyChannel("[HeoFAX - Debug]", netsvc.LOG_INFO, " File attached: %s" % " ".join(cmd['listFile']))

	partners = pool.get('res.partner').browse(cr, uid, datas['ids'], context)
	for partner in partners:
		for adr in partner.address:
			if adr.name:
				name = adr.name + ' (' + partner.name + ')'
			else:
				name = partner.name
			if adr.fax:
				cmd['to_number'] = adr.fax
				cmd['to_company'] = partner.name
				cmd['to_name'] = name
				# Build FAX command line
				cmdFax = hnm_heofax_lib.build_fax_cmd(self, cr, uid, datas, cmd)
				cmdFax = cmdFax.encode('utf8')
				if debug:
					# For trace only
					logger.notifyChannel("[HeoFAX - Debug]", netsvc.LOG_INFO, " Fax for: %s with fax nb: %s" % (name,cmd['to_number']))
					logger.notifyChannel("[HeoFAX - Debug]",netsvc.LOG_INFO, " Command used: %s" % cmdFax)
				pipe = subprocess.Popen(cmdFax, stdout=subprocess.PIPE, 
					stderr=subprocess.PIPE, shell=True)
				sts = pipe.wait()
				out = pipe.stdout.read() + pipe.stderr.read()
				if debug:
					logger.notifyChannel("[HeoFAX - Debug]",netsvc.LOG_INFO, " ID: %d:%s" % (sts,out))
				# increment number of fax
				nbOk += 1
				# Record event if selected
				if datas['form']['recordEvent']:
					ret = pool.get('res.partner.event').create(cr, uid, {'name':'Sent to FAX server: '+ datas['form']['subject'], 'partner_id':partner.id,'user_id':cmd['user'].id})
				# Test if sending to first contact only
				if datas['form']['firstonly']: break
			else:
				nbError += 1
				logger.notifyChannel("[HeoFAX - Info]",netsvc.LOG_INFO, " No fax number for name: %s" % name)
				if len(partners) < 1:
					raise wizard.except_wizard('[HeoFAX - Error]', ' No fax number for name: %s' % name)
		# Remove working files
	for f in cmd['listFile']:
		os.remove(f)
		if debug: logger.notifyChannel("[HeoFAX - Debug]",netsvc.LOG_INFO, " Removed file: %s" % f)
	cmd['listFile'] = []
	return {'fax_sent': nbOk, 'fax_error': nbError}
Пример #17
0
    def _create_control_sector(self):
        vals = self.compo
        opae_control_string =[] 
        ## chapter 4.2 secteur de controle -> identificateur de fichier
        opae_control_string.append(u'036')
        if not vals.get('line_date', False) :
            raise wizard.except_wizard(
                                        _('Error'), 
                                        _('Missing date planned  \n' \
                                        'for the payment order line: %s\n')
                                        )
     
        ## chapter 4.2 secteur de controle -> date decheance
        opae_control_string.append(vals['line_date'])
        ## chapter 4.2 secteur de controle -> reserve + element de commande fix val
        opae_control_string.append('0'* 5 + '1')
        ## chapter 4.2 secteur de controle -> No de compte de debit

        opae_control_string.append(vals['debit_account_number'].rjust(6,u'0'))
        ## chapter 4.2 secteur de controle -> N0 de compte de debit de tax
        opae_control_string.append(vals['debit_account_number'].rjust(6,u'0'))
        opae_control_string.append(vals['order_number'])


        try:
            print vals['transaction_type'], CODEEQUIV
            opae_control_string.append(CODEEQUIV[vals['transaction_type']])
            
        except Exception, e:
            raise wizard.except_wizard(_('Error'), _("Type doesn 't exists or isn 't supported yet."))
Пример #18
0
def _upload(self, cr, uid, datas, context):
    pool = pooler.get_pool(cr.dbname)
    mod = pool.get('ir.module.module').browse(cr, uid, datas['id'])
    download = datas['form']['url_download'] or ''
    if not download:
        res = module_zip.createzip(cr, uid, datas['id'], context,
                b64enc=False, src=datas['form']['include_src'])
        download = 'http://www.openerp.com/download/modules/'+res['module_filename']
        result = post_multipart('www.openerp.com', '/mtree_upload.php',
            [
                ('login', datas['form']['login']),
                ('password', datas['form']['password']),
                ('module_name', str(mod.name))
            ], [
                ('module', res['module_filename'], res['module_file'])
            ])
        if result and result[0] == "1":
            raise wizard.except_wizard(_('Error'), _('Login failed!'))
        elif result and result[0] == "2":
            raise wizard.except_wizard(_('Error'),
                    _('This version of the module is already exist on the server'))
        elif result and result[0] != "0":
            raise wizard.except_wizard(_('Error'), _('Failed to upload the file'))

    updata = {
        'link_name': mod.shortdesc or '',
        'new_cat_id': datas['form']['category'],
        'link_desc': (mod.description or '').replace('\n','<br/>\n'),
        'website': mod.website or '',
        'price': '0.0',
        'email': datas['form']['email'] or '',
        'cust_1': download,
        'cust_2': datas['form']['demourl'] or '',   # Put here the download url
        'cust_3': mod.url or '/',
        'cust_4': datas['form']['docurl'] or '',
        'cust_5': datas['form']['license'] or '',
        'cust_6': mod.installed_version or '0',
        'cust_7': mod.name,
        'option': 'com_mtree',
        'task': 'savelisting',
        'Itemid': '99999999',
        'cat_id': '0',
        'adminForm': '',
        'auto_login': datas['form']['login'],
        'auto_password': datas['form']['password']
    }
    name = mod.name
    a = urllib.urlopen('http://www.openerp.com/mtree_interface.php?module=%s' % (name,))
    aa = a.read()
    if aa[0]<>'0':
        updata['link_id']=aa.split('\n')[0]
        updata['option'] = 'mtree'

    files = []
    if datas['form']['image']:
        files.append(('link_image', 'link_image.png',
            base64.decodestring(datas['form']['image'])))
    result = post_multipart('www.openerp.com', '/index.php', updata.items(), files)
    return {'result': result}
def _check_state(self, cr, uid, data, context):
    job_obj = pooler.get_pool(cr.dbname).get('etl.job')
    job = job_obj.browse(cr, uid, data['ids'])[0]
    if not job.state in ('draft'):
        raise wizard.except_wizard(_('Job not in draft state !'), _('You can not add transitions in job which is in "%s" state') % job.state.upper())
    if len(job.component_ids) < 2:
        raise wizard.except_wizard(_('No enough Components !'), _('You need at-least  two component to add transition'))
    return {}
 def _get_defaults(self, cr, uid, data, context):
     inv_obj = pooler.get_pool(cr.dbname).get('account.invoice')
     for obj_inv in inv_obj.browse(cr,uid,data['ids']):
         if obj_inv.type not in ('out_invoice','out_refund'):
             raise wizard.except_wizard('User Error!','VCS is associated with Customer Invoices and Refund only.')
         if not obj_inv.number:
             raise wizard.except_wizard('Data Insufficient!','No Invoice Number Associated with the Invoice ID '+ str(obj_inv.id) +'!')
     return data['form']
Пример #21
0
def _create_user(self, cr, uid, data, context):
    pool = pooler.get_pool(cr.dbname)
    portal = pool.get("portal.portal").browse(cr, uid, data["form"]["portal_id"])
    user_ref = pool.get("res.users")
    out = "login,password\n"
    skipped = 0
    existing = ""
    created = ""
    for partner in pool.get("res.partner").browse(cr, uid, data["ids"]):
        for addr in partner.address:
            if not addr.email:
                skipped += 1
                continue
            user = user_ref.search(cr, uid, [("login", "=", addr.email)])

            if user:
                user = user_ref.browse(cr, uid, user[0])
                existing += "- %s (Login: %s,  Password: %s)\n" % (user.name, addr.email, user.password)
                mail = data["form"]["mail"] % {"login": addr.email, "passwd": user.password}
                if data["form"]["send_mail_existing"]:
                    if not data["form"]["mail_from"]:
                        raise wizard.except_wizard("Error !", 'Please provide a "from" email address.')
                    tools.email_send(
                        data["form"]["mail_from"], [addr.email], data["form"]["mail_subject_existing"], mail
                    )
                continue

            passwd = genpasswd()
            out += addr.email + "," + passwd + "\n"
            user_ref.create(
                cr,
                uid,
                {
                    "name": addr.name or "Unknown",
                    "login": addr.email,
                    "password": passwd,
                    "address_id": addr.id,
                    "action_id": portal.home_action_id and portal.home_action_id.id or portal.menu_action_id.id,
                    "menu_id": portal.menu_action_id.id,
                    "groups_id": [(4, portal.group_id.id)],
                    "company_id": portal.company_id.id,
                },
            )
            mail = data["form"]["mail"] % {"login": addr.email, "passwd": passwd}
            if data["form"]["send_mail"]:
                if not data["form"]["mail_from"]:
                    raise wizard.except_wizard("Error !", 'Please provide a "from" email address.')
                tools.email_send(data["form"]["mail_from"], [addr.email], data["form"]["mail_subject"], mail)
            created += "- %s (Login: %s,  Password: %s)\n" % (addr.name or "Unknown", addr.email, passwd)

    note = ""
    if created:
        note += "Created users:\n%s\n" % (created)
    if existing:
        note += "Already existing users:\n%s\n" % (existing)
    if skipped:
        note += "%d contacts where ignored (an email address is missing).\n" % (skipped)
    return {"note": note}
def _check_orders(self, cursor, uid, data, context):
    """
    Check payment type for all orders.

    Combine orders into one. All parameters harvested by the wizard
    will apply to all orders. This will in effect create one super
    batch for ClieOp, instead of creating individual parameterized
    batches. As only large companies are likely to need the individual
    settings per batch, this will do for now.
    """
    form = data["form"]
    today = date.today()
    pool = pooler.get_pool(cursor.dbname)
    payment_order_obj = pool.get("payment.order")

    runs = {}
    # Only orders of same type can be combined
    payment_orders = payment_order_obj.browse(cursor, uid, data["ids"])
    for payment_order in payment_orders:

        payment_type = payment_order.mode.type.code
        if payment_type in runs:
            runs[payment_type].append(payment_order)
        else:
            runs[payment_type] = [payment_order]

        if payment_order.date_prefered == "fixed":
            if payment_order.date_planned:
                execution_date = strpdate(payment_order.date_planned)
            else:
                execution_date = today
        elif payment_order.date_prefered == "now":
            execution_date = today
        elif payment_order.date_prefered == "due":
            # Max processing date is 30 days past now, so limiting beyond that
            # will catch too early payments
            max_date = execution_date = today + timedelta(days=31)
            for line in payment_order.line_ids:
                if line.move_line_id.date_maturity:
                    date_maturity = strpdate(line.move_line_id.date_maturity)
                    if date_maturity < execution_date:
                        execution_date = date_maturity
                else:
                    execution_date = today
            if execution_date and execution_date >= max_date:
                raise wizard.except_wizard(
                    _("Error"), _("You can't create ClieOp orders more than 30 days in advance.")
                )
        # Sanity check: can't process in the past
        form["execution_date"] = strfdate(max(execution_date, today))

    if len(runs) != 1:
        raise wizard.except_wizard(_("Error"), _("You can only combine payment orders of the same type"))

    form["batchtype"] = type = runs.keys()[0]
    form["reference"] = runs[type][0].reference[-5:]
    return form
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 {}
def _convert_file(self, cr, uid, data, context):
    fields={'allele1_dog':False,
            'allele2_dog': False,
            'progenus_number':False,
            'marker_dog':False
            }
    content=base64.decodestring(data['form']['attach'])
    obj_sample=pooler.get_pool(cr.dbname).get('labo.sample')
    obj_dog=pooler.get_pool(cr.dbname).get('labo.dog')
    obj_allele=pooler.get_pool(cr.dbname).get('dog.allele')
    obj_allele_h=pooler.get_pool(cr.dbname).get('dog.allele.history')
    obj_setup=pooler.get_pool(cr.dbname).get('analysis.setup')
    obj_type=pooler.get_pool(cr.dbname).get('labo.analysis.type')
    v_hist = pooler.get_pool(cr.dbname).get('file.history')
    
    file_name=data['form']['file_name']

    list= content.split('\n')[1:]
#    name_sort=file_name[0].split('-')
#    type_s=name_sort[0].upper()
#    page_n=name_sort[1].upper()
    re= content.split('\n')[:1][0].split('\t')

#    type_id=obj_type.search(cr,uid,[('code','like',type_s)])
#    setup_page=name_sort[1]
 #   cr.execute("SELECT s.progenus_number from labo_analysis_type t, labo_analysis_request r,labo_setup ls, labo_sample s, analysis_setup e where e.set_up=ls.id and s.file_setup=e.id and ls.name='%s' and r.type_id=t.id and s.sample_id=r.id and t.code = '%s' "%(setup_page, type_s))
    flag=''
    sample_name=''
    z=0
    grp_dog_alleles={}
   # for item in list:
    try:
        for line in csv.DictReader(list, re, delimiter='\t'):
            if 'Run Name' not in line.keys():
               raise wizard.except_wizard('Error!', 'Please check the structure of your file. \n The column "Run Name" does not exist')
            l=[]
           # l=item.split('\t')
            if len(line):
                cr.execute("select id from labo_dog where progenus_number='%s' order by create_date desc "%(line['Sample Name'].strip()))
                res=cr.fetchone()
                result=res and res[0] or None
                if result:
                    ids_dogs=obj_dog.browse(cr,uid, result)
                    for v_id in ids_dogs.allele_ids:
                        obj_allele_h.create(cr,uid, {'allele_dog1':v_id.allele_dog1,
                                               'allele_dog2':v_id.allele_dog2,
                                               'marker_dog':v_id.marker_dog,
                                               'creation_date':v_id.creation_date,
                                               'dog_id1':result
                        })

                    cr.execute("delete from dog_allele where dog_id1=%d "%(result))
    except Exception, e:
        raise wizard.except_wizard('Error!',' Please check your file. \n The structure seems not to be correct: %s' %( e,))
 def _check_date(self, cr, uid, data, context):
     sql = """
         SELECT f.id, f.date_start, f.date_stop FROM account_fiscalyear f  Where %s between f.date_start and f.date_stop """
     cr.execute(sql, (data['form']['date_from'],))
     res = cr.dictfetchall()
     if res:
         if (data['form']['date_to'] > res[0]['date_stop'] or data['form']['date_to'] < res[0]['date_start']):
             raise  wizard.except_wizard(_('UserError'),_('Date to must be set between %s and %s') % (res[0]['date_start'], res[0]['date_stop']))
         else:
             return 'report'
     else:
         raise wizard.except_wizard(_('UserError'),_('Date not in a defined fiscal year'))
    def _send_mail(self, cr, uid, data, context):

        # Check of the first email address given by the user
        ptrn = re.compile('(\w+@\w+(?:\.\w+)+)')
        result=ptrn.search(data['form']['email_to'])
        if result==None:
            raise wizard.except_wizard('Error !', 'Enter Valid Destination E-Mail Address.')

        # Check of the first second email address given by the user
        ptrn = re.compile('(\w+@\w+(?:\.\w+)+)')
        result=ptrn.search(data['form']['email_rcp'])
        if result==None:
            raise wizard.except_wizard('Error !', 'Enter Valid Reception E-Mail Address.')

        # Determine the first and last date to select
        month=data['form']['month']
        year=int(data['form']['year'])
        self.first_day=datetime.date(year,int(month),1)
        self.last_day=datetime.date(year,int(month),lengthmonth(year, int(month)))
        period="to_date('" + self.first_day.strftime('%Y-%m-%d') + "','yyyy-mm-dd') and to_date('" + self.last_day.strftime('%Y-%m-%d') +"','yyyy-mm-dd')"

        #determine the type of certificates to send
        certificate_type = data['form']['cert_type']
        cancel_clause = not(data['form']['canceled']) and " and b.state not in ('cancel_customer','cancel_cci')" or ''
        query = 'select a.id from cci_missions_certificate as a, cci_missions_dossier as b where ( a.dossier_id = b.id ) and ( a.sending_spf is null ) and ( b.type_id = %s ) and ( b.date between %s )' + cancel_clause
        #Extraction of corresponding certificates
        cr.execute(query % (certificate_type,period))
        res_file1=cr.fetchall()

        #If no records, cancel of the flow
        if res_file1==[]:
            raise wizard.except_wizard('Notification !', 'No Records Found to be sended. Check your criteria.')

        lines=[]
        root_path=tools.config.options['root_path']
        if res_file1:
            lines=self.make_lines(cr, uid, res_file1, data )
            self.write_txt(root_path+'/certificates.txt',lines)

        # Sending of the file as attachment
        files_attached=[]
        file1=tools.file_open(root_path+'/certificates.txt','rb',subdir=None)
        files_attached=[('certificates.txt',file1.read())]

        src = tools.config.options['smtp_user']  # parametre quand on lance le server ou dans bin\tools\config.py
        dest = [data['form']['email_to']]
        body = "Hello,\nHere are the certificates files for Federation.\nThink Big Use Tiny."
        tools.email_send(src,dest,"Federation Sending Files From TinyERP",body,attach=files_attached)
        pool = pooler.get_pool(cr.dbname)
        certificates_ids = [x[0] for x in res_file1]
        obj_certificate = pool.get('cci_missions.certificate')
        obj_certificate.write(cr, uid, certificates_ids,{'sending_spf':time.strftime('%Y-%m-%d')})
        return {}
    def _send_mail(self, cr, uid, data, context):

        ptrn = re.compile('(\w+@\w+(?:\.\w+)+)')
        result = ptrn.search(data['form']['email'])
        if result==None:
            raise wizard.except_wizard('Error !', 'Enter Valid E-Mail Address.')

        fields=['Id','Name','Partner','Related Type of Carnet','Emission Date','Validity Date','Holder Name','Holder Address','Holder City','Representer Name','Representer Address','Representer City','Usage','Goods','Area','Insurer Agreement','Own Risks','Goods Value','Double Signature','Initial No. of Pages','Additional No. of Pages','Warranty','Related Warranty Product','Date of Return','State','Date of Closure','Date of Sending to the Federation','Apply the Member Price']
        # For First CSV

        month=data['form']['month']
        yr=int(time.strftime('%Y'))
        self.first_day=datetime.date(yr,int(month),1)
        self.last_day=datetime.date(yr,int(month),lengthmonth(yr, int(month)))

        period="to_date('" + self.first_day.strftime('%Y-%m-%d') + "','yyyy-mm-dd') and to_date('" + self.last_day.strftime('%Y-%m-%d') +"','yyyy-mm-dd')"

        cr.execute('select id from cci_missions_ata_carnet where federation_sending_date is  null and ok_state_date between %s'%(period))
        res_file1=cr.fetchall()
        lines=[]
        root_path=tools.config.options['root_path']
        if res_file1:
            lines=self.make_csv(cr, uid,res_file1,file2=0)
            self.write_csv(root_path+'/carnet_1.csv',fields,lines)
        # First CSV created
        # Process for second CSV -Start
        today=datetime.datetime.today()
        _date=datetime.date(today.year-2,today.month,today.day)
        comp_date=_date.strftime('%Y-%m-%d')
        cr.execute('select id from cci_missions_ata_carnet where federation_sending_date is  null and state='"'pending'"' and return_date <='"'%s'"''%(str(comp_date)))
        res_file2=cr.fetchall()
        lines=[]
        if res_file2:
            lines=self.make_csv(cr, uid,res_file2,file2=1)
            self.write_csv(root_path+'/carnet_2.csv',fields,lines)
        # Second CSV created.
        if res_file1==[] and res_file2==[]:
            raise wizard.except_wizard('Notification !', 'No Records Found to make the CSV files.Choose other criteria.')
        files_attached=[]

        if res_file1:
            file_csv1=tools.file_open(root_path+'/carnet_1.csv','rb',subdir=None)
            files_attached=[('Ata_carnet_csv_1.csv',file_csv1.read())]
        if res_file2:
            file_csv2=tools.file_open(root_path+'/carnet_2.csv','rb',subdir=None)
            files_attached.append(('Ata_carnet_csv_2.csv',file_csv2.read()))

        src=tools.config.options['smtp_user']
        dest=[data['form']['email']]
        body="Hello,\nHere are the CSV files for Federation Sending.\nThanks You For Using TinyERP.\nThink Big Use Tiny."
        tools.email_send_attach(src,dest,"Federation Sending Files From TinyERP",body,attach=files_attached)
        return {}
Пример #28
0
def activate(self, cr, uid, data, context):
    plan_obj = pooler.get_pool(cr.dbname).get('account.analytic.plan.instance')
    if data['id']:
        plan = plan_obj.browse(cr, uid, data['id'], context)
        if (not plan.name) or (not plan.code):
            raise wizard.except_wizard(_('Error'), _('Please put a name and a code before saving the model !'))
        pids  =  pooler.get_pool(cr.dbname).get('account.analytic.plan').search(cr, uid, [], context=context)
        if (not pids):
            raise wizard.except_wizard(_('Error'), _('No analytic plan defined !'))
        plan_obj.write(cr,uid,[data['id']],{'plan_id':pids[0]})
        return 'info'
    else:
        return 'endit'
Пример #29
0
 def import_ical(self, cr, uid, data, context):
     employee_id = _employee_get(pooler.get_pool(cr.dbname).get('hr.attendance'), cr, data['form']['user_id'])
     if not employee_id:
         raise wizard.except_wizard('No employee found for the user', 'Login ID: %s' % data['form']['user_id'])
     
     first, end = [datetime.date(*(map(int, x.split('-')))) for x in [data['form']['startdate'], data['form']['enddate']]]
     end = min(end, datetime.date.today())
     try:
         user_obj = pooler.get_pool(cr.dbname).get('res.users')
         user = user_obj.read(cr, uid, [data['form']['user_id']])
         events = icalendar.read_icalendar(get_url('%s/persons/%s/calendar.ics' % (CALENDAR_URL, user[0]['login']), {'user': '******', 'pass': '******'}))
     except urllib2.HTTPError, e:
         raise wizard.except_wizard('Erreur HTTP', '%s - %s' % (e.code, e.msg))
Пример #30
0
    def _generate_dest_bank_string(self, vals):
        bank_string = []
        btype = vals['transaction_type']
        if btype == 'bvbank':
            if not vals['bic'] and not vals['iban']:
                raise wizard.except_wizard(
                                            _('Error'),
                                            _('Bic/swift number is requiered'+
                                            ' for bank %s if iban is not set'\
                                                %(vals['benef_bank_name']))
                                        )
            if vals['bic'] and (len(vals['bic']) < 8 or len(vals['bic']) >15)  :
                raise wizard.except_wizard(
                                            _('Error'),
                                            _('Error in bic.\nIf iban is present, just delete bic')
                                            )

            bank_string.append(vals['bic'].ljust(15, ' '))
        if btype in ('bvpost', 'bvbank'):    
            if btype == 'bvpost':
                if vals['postal_account_number']:
                    
                    bank_string.append(self._format_post_account(vals['postal_account_number'], 6))
                else:
                    raise wizard.except_wizard(
                                                _('Error'), 
                                                _('Missing postal account number')
                                            )

                bank_string.append(' '*6)

            if btype == 'bvbank' :
                if not vals['iban'] and not vals['postal_account_number']:
                    raise wizard.except_wizard(
                                            _('Error'),
                                            _('Missing IBAN or Postal account number')
                                        )

        
            if btype == 'bvbank' and not vals['iban']:
                if vals['postal_account_number']:
                    bank_string.append(self._format_post_account(vals['postal_account_number'], 6))
            else:
                if not vals['iban']:
                    raise wizard.except_wizard(
                                                     _('Error'), 
                                                     _('Iban missing')
                                                 )
                # error Iban lenght
                bank_string.append(vals['iban'].rjust(35,'0'))
        return u''.join(bank_string)
Пример #31
0
def _sale_complete(self, cr, uid, data, context):
    pool = pooler.get_pool(cr.dbname)
    order = pool.get('pos.order').browse(cr, uid, data['id'], context)

    if order.state in ('paid', 'invoiced'):
        raise wizard.except_wizard(_('UserError'), _("You can't modify this order. It has already been paid"))

    pick = pool.get('stock.picking').browse(cr, uid, data['form']['picking_id'], context)

    pool.get('pos.order').write(cr, uid, data['id'], {
        'last_out_picking': data['form']['picking_id'],
        'partner_id': pick.address_id and pick.address_id.partner_id.id
    })

    order = pool.get('stock.picking').write(cr, uid, [data['form']['picking_id']], {
        'invoice_state': 'none',
        'pos_order': data['id']
    })

    for line in pick.move_lines:
        pool.get('pos.order.line').create(cr, uid, {
            'name': line.sale_line_id.name,
            'order_id': data['id'],
            'qty': line.product_qty,
            'product_id': line.product_id.id,
            'price_unit': line.sale_line_id.price_unit,
            'discount': line.sale_line_id.discount,
        })

    return {}
Пример #32
0
    def _add_group(self, cr, uid, data, context):
        if context.has_key('group_id'):
            group_id = context['group_id']
        else:
            group_id = data['form']['group']
        pool = pooler.get_pool(cr.dbname)
        grp_ids = pool.get('dm.campaign.group').browse(cr, uid, group_id)
        camp_obj = pool.get('dm.campaign')
        for r in camp_obj.browse(cr, uid, data['ids']):
            if not grp_ids.campaign_ids:
                if not r.campaign_group_id:
                    camp_obj.write(cr, uid, [r.id],
                                   {'campaign_group_id': group_id})
            else:
                for c in grp_ids.campaign_ids:
                    if c.offer_id.id == r.offer_id.id:
                        if not r.campaign_group_id:
                            camp_obj.write(cr, uid, [r.id],
                                           {'campaign_group_id': group_id})
                    else:
                        raise wizard.except_wizard(
                            'Error !',
                            'Offer should be same for all the campaigns in a group : %s !'
                            % c.offer_id.name)

        return {}
Пример #33
0
    def _repair_action(self, cr, uid, data, context):
        """
        Action that repairs the invoice numbers 
        """
        logger = netsvc.Logger()

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

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

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

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

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

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

        vals = {
        }
        return vals
def _commissions_collection_calculated_ter(self, cr, uid, data, context={}):
    if not data:
        raise wizard.except_wizard(_('Error !'), _('No Existen Datos !!!'))
    form = data['form']
    period_id = form['period_id']
    ter_id = form['ter_id']
    dias = form['number_day']
    tipo = form['commissions_type']
    cuota = form['amount']
    periodo = pooler.get_pool(cr.dbname).get('sale.commissionsperiod').browse(
        cr, uid, period_id, context)
    desde = periodo.date_start
    hasta = periodo.date_stop
    nomb = periodo.name
    #Gerente Territorial
    obj_partner = pooler.get_pool(cr.dbname).get('res.partner')
    partner_id = pooler.get_pool(cr.dbname).get('res.partner').search(
        cr, uid, [('code_zone_id', '=', ter_id), ('salesman', '=', 1)])
    if partner_id and partner_id[0]:
        partn_id = partner_id[0]
    else:
        return {
            'resultado':
            "No hay Gerente Territorial Asignado, por favor signar uno y procesar nuevamente...!"
        }

    zone_ids = []
    if ter_id:
        zone_ids = pooler.get_pool(cr.dbname).get('res.partner.zone').search(
            cr, uid, [('parent_id', '=', ter_id)])
        datos = _collection_calculated_territory(cr, uid, ter_id, zone_ids,
                                                 period_id, nomb, dias, tipo,
                                                 cuota, partn_id, desde, hasta)
    return {}
Пример #35
0
def _create_yaml(self, cr, uid, data, context):
    pool = pooler.get_pool(cr.dbname)
    mod = pool.get('ir.module.record')
    try:
        res_xml = mod.generate_yaml(cr, uid)
    except Exception, e:
        raise wizard.except_wizard(_('Error'), _(str(e)))
Пример #36
0
def _data_save(self, cr, uid, data, context):
	if not data['form']['sure']:
		raise wizard.except_wizard('UserError', 'Si está seguro de que quiere cerrar el ejercicio marque la casilla correspondiente')
	if data['form']['asiento_pyg']:
		_asiento_pyg(self, cr, uid, data, context)
	_procedure_cierre(self, cr, uid, data, context)
	return {}
def _commissions_calculated_seller_div(self, cr, uid, data, context={}):
    if not data:
        raise wizard.except_wizard(_('Error !'), _('No Existen Datos !!!'))
    form = data['form']
    period_id = form['period_id']
    div_id = form['zone_id']
    dias = form['number_day']
    periodo = pooler.get_pool(cr.dbname).get('sale.commissionsperiod').browse(
        cr, uid, period_id, context)
    desde = periodo.date_start
    hasta = periodo.date_stop
    nomb = periodo.name
    zone_ids = []
    division_ids = []
    #Cuotas
    cuota_percent = 0
    if periodo.percent:
        cuota_percent = periodo.percent
    if not div_id:
        division_ids = pooler.get_pool(
            cr.dbname).get('res.partner.zone').search(
                cr, uid, [('type', '=', 'division')])
    else:
        division_ids.append(div_id)
    for d in division_ids:
        zone_ids = pooler.get_pool(cr.dbname).get('res.partner.zone').search(
            cr, uid, [('parent_id', '=', d)])
        datos = _commissions_calculated(cr, uid, d, zone_ids, period_id, nomb,
                                        dias, cuota_percent)
    return {}
Пример #38
0
def _calc_dates(self, cr, uid, data, context):
	res = {}
	period_length = data['form']['period_length']
	if period_length<=0:
		raise wizard.except_wizard('UserError', 'You must enter a period length that cannot be 0 or below !')
	start = mx.DateTime.strptime(data['form']['date_to'], '%Y-%m-%d')
	for i in range(5)[::-1]:
		stop = start-RelativeDateTime(days=period_length)
		end_date = mx.DateTime.strptime(data['form']['date_from'], '%Y-%m-%d')
		if stop < end_date:
			stop = end_date
			res[str(i)] = {
			'name' : 'over '+str((5-i)*period_length)+' days',
			'stop': end_date.strftime('%Y-%m-%d'),
			'start' : end_date.strftime('%Y-%m-%d'),
		}
			start = end_date
		else :
			res[str(i)] = {
				'name' : 'over '+str((5-i)*period_length)+' days',
				'stop': start.strftime('%Y-%m-%d'),
				'start' : stop.strftime('%Y-%m-%d'),
			}
			start = stop - RelativeDateTime(days=1)
	return res
def _check_data(self, cr, uid, data, context={}):
    pool = pooler.get_pool(cr.dbname)
    invoice = pool.get('account.invoice').browse(cr, uid, data['id'], context)
    if invoice.islr:
        raise wizard.except_wizard(_('Alerta !'),
                                   _('La Factura Ya Fue Retenida'))
    if not invoice.islr_type_id:
        raise wizard.except_wizard(
            _('Alerta !'), _('La Factura No posee un Tipo de Islr Asignado'))
    if not invoice.partner_id.special:
        raise wizard.except_wizard(_('Alerta !'),
                                   _('El Cliente no es Contribuyente'))
    if invoice.state in ['draft', 'proforma2', 'cancel']:
        raise wizard.except_wizard(
            _('Alerta !'),
            _('No puede pagar islr de Facturas en Estatus draft o cancel'))
    return {'date': time.strftime('%Y-%m-%d')}
 def _check_item_selection(self, cr, uid, data, context):
     """ test if there is one and only one item selected when this wizard is run """
     if len(data['ids']) != 1:
         raise wizard.except_wizard(
             'Selection Error',
             'You need to select one, and only one, budget structure to run this action'
         )
     return {}
Пример #41
0
def _delete(self, cr, uid, data, context):
    mailbox_obj = pooler.get_pool(cr.dbname).get('webmail.mailbox')
    mailbox = mailbox_obj.browse(cr, uid, data['ids'][0])
    if mailbox.parent_id:
        raise wizard.except_wizard('Error!', 'You can not delete parent folder')
    
    mailbox_obj._delete(cr, uid, data['ids'], context)    
    return {}
Пример #42
0
def _rename_process(self, cr, uid, data, context):
    old_name = data['form']['old_name']
    new_name = data['form']['new_name']
    if not old_name:
        raise wizard.except_wizard('Error!', 'Please enter old folder name')
    mailbox_obj = pooler.get_pool(cr.dbname).get('webmail.mailbox')    
    mailbox_obj.rename(cr, uid, data['ids'] , context, old_name, new_name)    
    return {}
Пример #43
0
def _set_run(self, cr, uid, data, context={}):
    refs_ls = pooler.get_pool(cr.dbname).get('labo.sample')
    refs_as = pooler.get_pool(cr.dbname).get('analysis.setup')
    rec_ids = refs_ls.browse(cr, uid, data['ids'])
    if not len(rec_ids):
        raise wizard.except_wizard('Error!',
                                   'Please, set the number of the setup page')
    for r in rec_ids:
        if not r.file_setup:
            raise wizard.except_wizard(
                'Error!',
                'The sample "%s" has no setup page, please set one"' %
                (r.progenus_number))

        s_id = refs_as.write(cr, uid, [r.file_setup.id], {
            'run_setup': data['form']['run'],
        })
    return {}
Пример #44
0
def get_detail(self, cr, uid, datas, context=None):
    data = pooler.get_pool(cr.dbname).get('module.quality.detail').browse(
        cr, uid, datas['id'])
    if not data.detail:
        raise wizard.except_wizard(_('Warning'), _('No report to save!'))
    buf = cStringIO.StringIO(data.detail)
    out = base64.encodestring(buf.getvalue())
    buf.close()
    return {'module_file': out, 'name': data.name + '.html'}
def _do_export(self, cr, uid, data, context):
    self.pool = pooler.get_pool(cr.dbname)
    esale_web_obj = self.pool.get('esale.oscom.web')
    esale_category_obj = self.pool.get('esale.oscom.category')
    product_obj = self.pool.get('product.product')

    if data['model'] == 'ir.ui.menu':
        website_ids = esale_web_obj.search(cr, uid, [('active', '=', True)])
    else:
        website_ids = []
        website_not = []
        for id in data['ids']:
            exportable_website = esale_web_obj.search(cr, uid,
                                                      [('id', '=', id),
                                                       ('active', '=', True)])
            if exportable_website:
                website_ids.append(exportable_website[0])
            else:
                website_not.append(id)

        if len(website_not) > 0:
            raise wizard.except_wizard(
                _("Error"),
                _("You asked to synchronize to non-active OScommerce web shop: IDs %s"
                  ) % website_not)

    prod_new = 0
    prod_update = 0
    prod_delete = 0
    for website_id in website_ids:
        website = esale_web_obj.browse(cr, uid, website_id)
        esale_category_ids = esale_category_obj.search(
            cr, uid, [('web_id', '=', website.id),
                      ('category_id', '!=', False)])
        esale_categories = esale_category_obj.browse(cr, uid,
                                                     esale_category_ids)
        product_ids = []
        for esale_category in esale_categories:
            product_ids.extend(
                product_obj.search(
                    cr, uid,
                    [('categ_id', '=', esale_category.category_id.id)]))

        res = product_obj.oscom_export(cr,
                                       uid,
                                       website=website,
                                       product_ids=product_ids,
                                       context=context)
        prod_new = prod_new + res['prod_new']
        prod_update = prod_update + res['prod_update']
        prod_delete = prod_delete + res['prod_delete']

    return {
        'prod_new': prod_new,
        'prod_update': prod_update,
        'prod_delete': prod_delete
    }
def _check_date(self, cr, uid, data, context):
    sql = """
		SELECT f.id, f.date_start, f.date_stop FROM account_fiscalyear f  Where '%s' between f.date_start and f.date_stop """ % (
        data['form']['date_from'])
    cr.execute(sql)
    res = cr.dictfetchall()
    if res:
        if (data['form']['date_to'] > res[0]['date_stop']
                or data['form']['date_to'] < res[0]['date_start']):
            raise wizard.except_wizard(
                'UserError', 'Date to must be set between ' +
                res[0]['date_start'] + " and " + res[0]['date_stop'])
        else:
            return 'checkreport'

    else:
        raise wizard.except_wizard('UserError',
                                   'Date not in a defined fiscal year')
Пример #47
0
def _invoice_merge(self, cr, uid, data, context):
    if (len(data['ids']) < 2):
        raise wizard.except_wizard(_('UserError'),
                                   _('No need to merge less than 2 invoices!'))
    pool = pooler.get_pool(cr.dbname)
    inv_obj = pool.get('account.invoice')
    invs = inv_obj.read(cr, uid, data['ids'])
    vals = {}
    inv_ids = []

    for d in invs[1:]:
        inv_ids.append(d['id'])
        if d['comment']:
            if not vals.has_key('comment'):
                vals['comment'] = invs[0]['comment'] or ''
            vals['comment'] += ' ' + d['comment']
        if d['date_due']:
            if not vals.has_key('date_due'):
                vals['date_due'] = invs[0]['date_due']
            if vals['date_due'] and (vals['date_due'] > d['date_due']):
                vals['date_due'] = d['date_due']

    if len(vals):
        inv_obj.write(cr, uid, [
            invs[0]['id'],
        ], vals, context)

    # Locate the fields (o2m) that reference this invoice, and update
    # them to point to the new invoice
    mod_fields = [
        ('account.invoice.line', None, True),
        ('account.invoice.tax', None, True),
        ('account.analytic.line', None, False),
        ('hr.expense.expense', None, False),
        ('mrp.repair', None, False),
        ('proforma.followup.history', None, False),
        ('purchase.order', None, False),
        ('training.subscription.line', None, False),
    ]
    # please, add your module's models here, so that their refs
    # get updated, too.

    for model, field, oblig in mod_fields:
        try:
            mobj = pool.get(model)
            if (not mobj) and (not oblig):
                continue
            mfie = field or 'invoice_id'
            mids = mobj.search(cr, uid, [(mfie, 'in', inv_ids)])
            if mids and len(mids):
                mobj.write(cr, uid, mids, {mfie: invs[0]['id']})
        except Exception, e:
            print "Exception while merging %s" % model, e
            if oblig:
                raise
            pass
    def init(self, cr, uid, data, context=None):
        proxy = pooler.get_pool(cr.dbname).get(data['model'])
        name = None
        languages = set()
        for course in proxy.browse(cr, uid, data['ids'], context=context):
            if course.state_course != 'validated':
                raise wizard.except_wizard(
                    _('Warning'),
                    _("Please, The state of all courses must be 'validated'"))
            if name is None:
                name = course.name
            languages.add(course.lang_id.id)

        if len(languages) > 1:
            raise wizard.except_wizard(
                _('Warning'),
                _('You have selected a course with a different language'))

        return {'name': name, 'lang_id': list(languages)[0]}
Пример #49
0
def _check(self, cr, uid, data, *a):
    pool = pooler.get_pool(cr.dbname)
    order_lst = pool.get('pos.order').browse(cr, uid, data['ids'])
    for order in order_lst:
        if order.state_2 in ('to_verify'):
            raise wizard.except_wizard(
                'Error!',
                'Can not print the receipt because of discount and/or payment '
            )
    return data
 def init(self, cr, uid, data, context=None):
     if data['id']:
         offer = pooler.get_pool(cr.dbname).get(data['model']).browse(
             cr, uid, data['id'])
         if offer.state != 'validated':
             raise wizard.except_wizard(
                 _('Warning'),
                 _("Please, you can create a session with a validated offer"
                   ))
         return {'name': offer.name}
Пример #51
0
 def init(self, cr, uid, data, context=None):
     if data['id']:
         course = pooler.get_pool(cr.dbname).get(data['model']).browse(
             cr, uid, data['id'])
         if course.state_course != 'validated':
             raise wizard.except_wizard(
                 _('Warning'),
                 _("Please, you can create an offer with a validated course"
                   ))
     return {}
    def _get_budget_lines(self, cr, uid, data, context):
        """ retrieve lines to work on """

        #check there is at least one version selected
        if len(data['form']['versions'][0][2]) == 0:
            raise wizard.except_wizard(
                'Versions Missing',
                "Select at least on version to run this report")

        #check there is max 10 versions
        if len(data['form']['versions'][0][2]) > 10:
            raise wizard.except_wizard(
                'Too Many Versions',
                "Select at most 10 versions of the same budget")

        #check all versions belong to the same budget
        version_obj = pooler.get_pool(cr.dbname).get('c2c_budget.version')
        versions = version_obj.browse(cr,
                                      uid,
                                      data['form']['versions'][0][2],
                                      context=context)
        budget_id = versions[0].budget_id.id
        for v in versions:
            if budget_id != v.budget_id.id:
                raise wizard.except_wizard(
                    'Incompatible Versions',
                    "The selected versions do not belong to the same budget. Select only versions of the same budget to run the report"
                )

        #find lines to work on
        line_obj = pooler.get_pool(cr.dbname).get('c2c_budget.line')
        period_obj = pooler.get_pool(cr.dbname).get('account.period')

        criteria = [('budget_version_id', 'in', data['form']['versions'][0][2])
                    ]
        if len(data['form']['periods'][0][2]) > 0:
            criteria.append(('period_id', 'in', data['form']['periods'][0][2]))

        line_ids = line_obj.search(cr, uid, criteria, context=context)

        values = {'ids': line_ids}

        return values
def _check_state(self, cr, uid, data, context):
    job_obj = pooler.get_pool(cr.dbname).get('etl.job')
    job = job_obj.browse(cr, uid, data['ids'])[0]

    if not job.state in ('draft'):
        raise wizard.except_wizard(
            _('Job not in draft state !'),
            _('You can not add components in job which is in "%s" state') %
            job.state.upper())
    return {}
Пример #54
0
    def next(self, cr, uid, data, context):
        answer = data['form']['answer']
        answer_obj = pooler.get_pool(cr.dbname).get('crm_profiling.answer')
        next_id = answer_obj.read(cr, uid, answer, ['next'], context)
        if not next_id:
            raise wizard.except_wizard(_('Error'), _('An error unknown'))

        x_form, x_fields = self.build_form(cr, uid, next_id['next'], context)
        _POLL_FORM.__init__(x_form)
        _POLL_FIELDS.__init__(x_fields)
        return {}
    def create_session(self, cr, uid, data, context=None):
        pool = pooler.get_pool(cr.dbname)
        proxy = pool.get('training.offer')
        offer = proxy.browse(cr, uid, data['id'], context=context)

        if not offer.can_be_planned:
            raise wizard.except_wizard(
                _('Warning'),
                _("You can not create a session with a non-validated offer"))

        proxy = pool.get('training.session')
        session_id = proxy.create(
            cr, uid, {
                'offer_id':
                data['id'],
                'date':
                data['form']['date'],
                'name':
                "%s (%s)" % (data['form']['name'],
                             time.strftime(
                                 "%Y-%m-%d",
                                 time.strptime(data['form']['date'],
                                               '%Y-%m-%d %H:%M:%S'))),
                'format_id':
                offer.format_id.id,
            })
        vals = proxy.on_change_offer(cr, uid, None, data['id'])
        if isinstance(vals, dict):
            # we have specified a custom name on session creation,
            # don't let on_change overwrite it now.
            try:
                if 'name' in vals['value']:
                    del vals['value']['name']
            except KeyError:
                pass
            proxy.write(cr, uid, [session_id], vals['value'], context=context)

        return {
            'view_type':
            'form',
            "view_mode":
            'form',
            'res_model':
            'training.session',
            'view_id':
            pool.get('ir.ui.view').search(
                cr, uid, [('name', '=', 'training.session.form')]),
            'type':
            'ir.actions.act_window',
            'target':
            'current',
            'res_id':
            int(session_id),
        }
Пример #56
0
 def _select_format(self, cr, uid, data, context=None):
     if context is None:
         context = {}
     wiz_name = self.wiz_name.replace('jasper.', '')
     pool = pooler.get_pool(cr.dbname)
     document_obj = pool.get('jasper.document')
     doc_ids = document_obj.search(cr, uid, [('service', '=', wiz_name)])
     if not doc_ids:
         raise wizard.except_wizard(_('Error'), _('No report found!'))
     document = document_obj.browse(cr, uid, doc_ids[0], context=context)
     if document.id:
         if document.format_choice == 'mono':
             action = 'create_wizard'
         elif document.format_choice == 'multi':
             action = 'format_choice'
             raise wizard.except_wizard(_('Error'), _('No implemented yet!'))
     ##
     # Compose the uri to launch to JasperServer
     #
     return action
def _get_type(obj, cr, uid, data, context):
    picking_obj = pooler.get_pool(cr.dbname).get('stock.picking')
    type = 'out_invoice'
    pick = picking_obj.browse(cr, uid, data['id'], context)
    if pick.state != 'done':
        raise wizard.except_wizard(
            'Error',
            'La Nota de Salida Debe estar Realizada, para poder Facturar!!!')
    if pick.invoice_state == 'invoiced':
        raise wizard.except_wizard('UserError',
                                   'La Nota de Salida ya fue Facturada')
    if pick.invoice_state == 'none':
        raise wizard.except_wizard(
            'UserError', 'Esta Nota de Salida no puede ser facturada.')

    if not pick.move_lines:
        raise wizard.except_wizard(
            'Error', 'No se puede crear la Factura, no existen productos')

    return {'type': type}
Пример #58
0
 def _get_invoice_address(self, cr, uid, partner_address):
     valid_address_id = ''
     for partner_address_object in partner_address:
         if partner_address_object.type == "invoice":
             valid_address_id = partner_address_object.id
     if not valid_address_id:
         if len(partner_address) > 0:
             valid_address_id = partner_address[0].id
         else:
             raise wizard.except_wizard(
                 'AddressError', 'No Address Assign to this partner')
     return valid_address_id
Пример #59
0
 def _riase_error(self, cr, uid, data, context):
     form=data['form']
     if not form['emp_ids'][0][2] :
         raise wizard.except_wizard('Error', 'You must select Employee(s) For report !')
     
     if form['active1'] and form['active2']:
         raise wizard.except_wizard('TyepError', 'You must select only one type For report !')
     if form['active1']:
         temp=form['year']
         if not form['month']:
             raise wizard.except_wizard('MonthError', 'You must select month For month-wise report !')
         
             
     elif form['active2']:
         temp=0
         if not form['fromdate'] or not form['todate']:
             raise wizard.except_wizard('DateError', 'You must select Dates For date-wise report !')
         else:
             d=form['fromdate']
             dd=form['todate']
             d1=d.split('-')
             d2=dd.split('-')
             d1[2]=d1[2].split(' ')
             d2[2]=d2[2].split(' ')
             a=datetime.date(int(d1[0]),int(d1[1]),int(d1[2][0]))
             b=datetime.date(int(d2[0]),int(d2[1]),int(d2[2][0]))
             if  a>b :
                 raise wizard.except_wizard('DateError', 'You must select Dates proparly !')
     else:
         raise wizard.except_wizard('typeError', 'You must select Type !')
     return {'year':temp}
def _commissions_file_seller(self, cr, uid, data, context={}):
    resp ='message'
    saltoln	= chr(13)
    if not data:
        return {'resultado':"No hay datos...!"}
    form = data['form']
    period_id = form['period_id']
    #periodo = pooler.get_pool(cr.dbname).get('period.generalperiod').browse(cr, uid, period_id, context)
    periodo = pooler.get_pool(cr.dbname).get('sale.commissionsperiod').browse(cr, uid, period_id, context)
    desde = periodo.date_start
    hasta = periodo.date_stop
    nomb = periodo.name
    #ruta =  "/home/public/" # Ruta Desarrollo
    ruta =  "/opt/openerp/reportes/personal/" # Ruta Server
    sql = """
    SELECT b.acc_number,p.vat,c.commission_pay,p.name   
    FROM commissions_seller AS c
    INNER JOIN res_partner AS p ON c.salesman_id=p.id 
    INNER JOIN res_partner_bank AS b ON p.id=b.partner_id 
    WHERE c.commission_period_id=%d;"""%period_id
    cr.execute (sql)
    result = cr.fetchall()
    if not result:
        raise wizard.except_wizard(_('Error !'), _('No existes datos!!!'))

    filename	= ruta+'comisiones.txt'
    output		= codecs.open(filename,"w", "utf-8")
    for d in result:
        cta = '02'
        ci  = ''
        monto = 0
        nombre = ''
        if d[0]:
            cta += d[0]
        if d[1]:
            ci = d[1]
            ci = ci.replace('V','') 
        if d[2]:
            monto = d[2]
        cta = cta.zfill(22)
        ci  = ci.strip()
        ci  = ci.zfill(8)
        ci  = 'V'+ci
        monto = locale.format('%.2f',  monto, grouping=True)
        monto	= monto.replace(',','')
        monto = monto.zfill(17)
        monto = monto.rjust(24)
        nombre = d[3]
        nombre = nombre.ljust(43)
        output.write(cta+ci+monto+nombre+'\r\n')
    output.close()
    return resp