from odoo import models, fields, api,_ from odoo.exceptions import UserError, ValidationError,Warning from psycopg2 import sql, DatabaseError from werkzeug import utils import json import logging import xlwt from io import BytesIO import base64 import csv import os,secrets class opendons_operation_batch_export(models.Model): _name = 'opendons.operation.batch_export' _description = 'lot export' name=fields.Char(string='Name',required=True,track_visibility='always') operation_id = fields.Many2one( 'opendons.operation', String='Operation', index=True, readonly=True, track_visibility='onchange', ondelete='cascade' ) chanel=fields.Selection([ ('mail', 'Mailing'), ('email', 'E-mailing'), ('event', 'Event'), ('face_to_face', 'Face to face')], string='Chanel',required=True, translate=True,track_visibility='always') partner_ids = fields.Many2many('res.partner', 'partner_batch_export_rel', 'partner_id', 'batch_export__id', string='partners') csv_export = fields.Binary('csv export', filters='.csv', readonly=True) document_fname=fields.Char() exported_date=fields.Date(string='Exported Date',track_visibility='always', readonly=True) def csv_export_batch(self): if self.operation_id.quantity==0: raise Warning('You must generate export at the operation level first') segments=self.env['opendons.segment'].search([('operation_id','=',int(self.operation_id)),('batch_export_id','=',int(self.id))]) #récupération des contacts sélectionnées et lié au segments du batch for seg in segments: for p in seg.partner_ids: self.write({'partner_ids':[(4,p.id)]}) tmstp=secrets.token_hex(16) csv_filename='/tmp/export_'+tmstp+'.csv' with open(csv_filename, mode='w') as file: writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) if self.chanel=='email': writer.writerow(['id','key','name','firstname','email','operation','segment']) if self.chanel=='mail': writer.writerow(['id','key','name','firstname','title','street','street2','city','cp','country_name','operation','segment']) for p in self.partner_ids: #raise UserError(p) id=p.id key=p.key name=p.name firstname=p.firstname if p.firstname else '' street=p.street if p.street else '' street2=p.street2 if p.street2 else '' city=p.city if p.city else '' cp=p.zip if p.zip else '' country_name=p.country_id.name if p.country_id else '' title=p.title.name if p.title else '' operation=int(self.id) segment=int(seg.id) if self.chanel=='email': writer.writerow([id,key,name,firstname,email,operation,segment]) if self.chanel=='mail': writer.writerow([id,key,name,firstname,title,street,street2,city,cp,country_name,operation,segment]) with open(csv_filename, 'r', encoding="utf-8") as f2: data = str.encode(f2.read(), 'utf-8') self.csv_export=base64.encodestring(data) self.document_fname=str(self.id)+'_'+self.name+'.csv' self.exported_date=fields.Date.context_today(self) os.unlink(csv_filename) return True