예제 #1
0
class acco_location_report(models.TransientModel):
    
    _name = 'acco.location.report'
        
    @api.model
    def default_get(self, fields):
        if self._context is None:
            context = {}
            
        context = self._context
        res = super(acco_location_report, self).default_get(fields)
        res.update({'name': 'Locationwise.xls'})
        if self._context.get('file'):
            res.update({'file': context['file']})
        return res

    file = fields.Binary('File')
    name = fields.Char(string='File Name', size=32)

    @api.multi
    def action_back(self):
        if self._context is None:
            context = {}
        return {
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'wiz.accommodation.employee.report',
            'target': 'new',
        }
예제 #2
0
class born_shop_category(models.Model):
    _name = 'born.shop.category'

    @api.one
    @api.depends('image')
    def _make_local_url(self):
        for line in self:
            if self.image:
                domain = [('type', '=', 'binary'), ('res_field', '=', 'image'),
                          ('res_model', '=', 'born.shop.category'),
                          ('res_id', '=', self.id)]
                attachment = self.env['ir.attachment'].search(domain, limit=1)
                if attachment:
                    server_url = openerp.tools.config['localhost_server_url']
                    image_url = '%s%s' % (server_url, attachment.local_url)
                    line.image_url = image_url

    name = fields.Char(u'名称')
    image = fields.Binary(u'标志图片', attachment=True)
    image_url = fields.Char(string=u'图片地址',
                            compute='_make_local_url',
                            multi='_make_local_url',
                            help=u"图片地址")
    type = fields.Selection([('url', u'链接'), ('product_ids', u'商品'),
                             ('category_ids', u'分类'), ('content_ids', u'文章'),
                             ('function_ids', u'功能')],
                            default='url',
                            string=u'类型',
                            help=u'类型')
    sequence = fields.Integer(u'排序')
    description = fields.Text(u'说明')
예제 #3
0
class stagiaires(models.Model):
    _name = "hr.stagiaires"
    _description = "liste des stagiaires"
    _rec_name = "nom"
    image = fields.Binary('Image')
    nom = fields.Char("Nom du stagiaire")
    adresse_pro = fields.Char("Adresse Professionelle")
    tel_pro = fields.Char('Tél. portable professionel')
    user_id = fields.Many2one('res.users', string="Utilisateur lié")
    departement = fields.Many2one('hr.department', string="Département")
    job = fields.Many2one('hr.job', string="Titre de poste")
    responsa = fields.Many2one('hr.employee', string="Responsable")
    date_entre = fields.Date('Date debut')
    date_fin = fields.Date('Date fin de stage')
    nationalite = fields.Many2one('res.country', string="Nationalité")
    cin = fields.Integer('CIN')
    deliv = fields.Date('Date delivrance CIN')
    naiss = fields.Date('Date naissance')
    naisslieux = fields.Many2one('res.country.state',
                                 string="Lieux de naissance")
    pers_addr = fields.Char('Adresse personnelle')
    gender = fields.Selection(selection=[('Masculin', 'Masculin'),
                                         ('Feminin', 'Feminin')],
                              string="Genre")
    etciv = fields.Selection(selection=[('Divorcé', 'Divorcé'),
                                        ('Marié', 'Marié'),
                                        ('Celibataire', 'Celibataire'),
                                        ('Voeuf', 'Voeuf')],
                             string="etat Civil")
    actif = fields.Boolean('Active')
    theme = fields.Char('Théme de stage')
예제 #4
0
class born_lottery(osv.osv):
    _name = 'born.lottery'

    name = fields.Char(u'名称', size=255, help=u"名称")
    path = fields.Char(u'文件夹名称', size=255, help=u"文件夹名称")
    image = fields.Binary(u"预览")
    level = fields.Integer(u'中奖等级', digits=(2, 0))
    description = fields.Text(u'说明', )
예제 #5
0
class born_activity_tpl(osv.osv):
    _name = 'born.activity.tpl'
    _description = u"模板"

    name = fields.Char(u'名称', size=255, help=u"活动名称", required=True)
    image = fields.Binary(string=u"活动海报", attachment=True, help=u"活动海报")
    image_url = fields.Char(u'海报地址', size=255, help=u"海报地址")
    file_name = fields.Char(u'海报名称', size=255, help=u"海报名称")
    note = fields.Text(u'活动简介', required=True, help=u'活动简介')
    description = fields.Text(u'活动描叙', required=True, help=u'活动详细描叙,活动参与流程')
    provision = fields.Text(u'活动条款', help=u'参与活动的条款')
    active = fields.Boolean(u'归档', default=True)
    price = fields.Float(u'报名费', help=u'参与活动的报名费用')
    company_id = fields.Many2one('res.company',
                                 u'公司',
                                 ondelete='cascade',
                                 required=True,
                                 help=u'活动所属公司')
    game_id = fields.Many2one('born.game', u'游戏', help=u'参与活动的游戏')
    app_id = fields.Many2one('tl.weixin.app', u'公众号', ondelete="cascade")
    activity_ids = fields.One2many('born.activity',
                                   'active_tpl_id',
                                   string=u'活动',
                                   help=u'商户报名活动列表')
    company_ids = fields.Many2many('res.company',
                                   'born_activity_company_rel',
                                   'activity_id',
                                   'company_id',
                                   u'允许发行的公司',
                                   help=u'限制该活动允许发行的公司,不设置表示所有的平台都可以看到该活动')
    default_gift_ids = fields.Many2many('born.game.gift',
                                        'born_activity_default_gift_rel',
                                        'activity_id',
                                        'gift_id',
                                        u'默认奖品',
                                        help=u'该奖品为发行活动的公司提供,所有参与的公司都能够使用该奖品')

    @api.model
    def create(self, vals):

        if vals.get('image', False):
            s3 = s3client(self)
            image_url = s3.upload(self._cr, self._uid, vals.get('image'),
                                  vals.get('file_name', 'image.png'))
            vals['image_url'] = image_url
        return super(born_activity_tpl, self).create(vals)

    @api.multi
    def write(self, vals):

        if vals.get('image', False):
            s3 = s3client(self)
            image_url = s3.upload(self._cr, self._uid, vals.get('image'),
                                  vals.get('file_name', 'image.png'))
            vals['image_url'] = image_url
        return super(born_activity_tpl, self).write(vals)
예제 #6
0
class od_document_request_attach_here_line(models.Model):
    _name = 'od.document.request.attach.here.line'
    _description = "od.document.request.attach.here.line"
    name = fields.Char(string='Description')
    scanned_copy = fields.Binary(string='Scanned Copy')
    scanned_fname = fields.Char(string='Comp', size=32)
    reference = fields.Char(string='Reference')
    issue_date = fields.Date(string='Issue Date')
    expiry_date = fields.Date(string='Expiry Date')
    document_attach_here_line_id = fields.Many2one('od.document.request',
                                                   string='Document')
예제 #7
0
class pricelist_se_import(models.Model):
    _name = 'product.pricelist.import'
    _description = 'Import PriceList file'
    file_data = fields.Binary('Import PriceList File', required=True)
    file_fname = fields.Char('Import PriceList Filename',
                             size=128,
                             required=True)
    note = fields.Text('Log')

    _defaults = {
        'file_fname': lambda *a: '',
    }
예제 #8
0
class he_employee(models.Model):
    _name = "hr.employee.medical"

    name = fields.Char(string="Referencia", required=True)
    employee_id = fields.Many2one('hr.employee', 'Employee', required=True)

    fichero = fields.Binary()

    fecha_revision = fields.Date()

    fecha_validez = fields.Date()

    observaciones = fields.Html()
예제 #9
0
class vetclinic_classification(models.Model):
    _name = 'vetclinic.classification'

    name = fields.Char('Name:')
    breed_id = fields.One2many('vetclinic.breed', 'classification_id_of_breed',
                               'Breeds :')
    image_id = fields.Many2one('vetclinic.images', 'Choose Your Image:')
    display_image = fields.Binary(related='image_id.image')
    # vacc_class = fields.One2many('vetclinic.images','image_id','EXECUTE',related='image_id.image')

    @api.multi
    def Pass(self):
        print "Button is Pressed=============================="
예제 #10
0
class born_spread(osv.osv):
    _name = 'born.spread'

    name = fields.Char(u'名称', size=255, help=u"名称")
    lottery_id = fields.Many2one("born.lottery", u'抽奖方式')
    description = fields.Text(u'说明', )
    image = fields.Binary(u"展示图片")
    start_date = fields.Date(u'开始日期')
    end_date = fields.Date(u'结束日期')
    start_order_amount = fields.Float(
        u'最小订单金额',
        digits_compute=dp.get_precision('Account'),
        help=u"参加抽奖需要订单金额达到金额")
    product_ids = fields.One2many('born.spread.product', 'spread_id', u'奖品列表')
    product_limit_ids = fields.One2many('born.spread.limit.product',
                                        'spread_id', u'必须购买以下产品后才能参与抽奖')
예제 #11
0
class tools_helpdesk_adjuntos(models.Model):
    _name = 'tools.helpdesk.adjuntos'
    #_rec_name = 'nombre'

    adjunto = fields.Binary(
        string="Adjuntos",
        attachment=True,
        help=
        'Se suben los archivos adicionales que guardan relacion con el documento',
        filters=
        "*.png,*.svg,*.jpg,*jpeg,*.pdf,*.ods,*.xls,*.xlsx,*.odt,*.doc,*.docx,*.ppt,*.pptx,*.odp"
    )
    observacion = fields.Text(
        string="Descripción",
        size=50,
        help='Breve nota sobre el archivo que se adjunta')
    incidencia_id = fields.Many2one('tools.helpdesk.incidencia', 'incidencia')
예제 #12
0
class od_hr_employee_document_line(models.Model):
    _name = 'od.hr.employee.document.line'
    _description = "od.hr.employee.document.line"
    employee_id = fields.Many2one('hr.employee', string='Employee')
    document_type_id = fields.Many2one('od.employee.document.type',
                                       string='Document Type',
                                       required=True)
    document_referance = fields.Char(string='Document Reference')
    attach_file = fields.Binary(string='Scanned Copy')
    issue_date = fields.Date(string='Issue Date')
    expiry_date = fields.Date(string='Expiry Date')
    attach_fname = fields.Char(string='Comp', size=32)

    def default_get(self, cr, uid, ids, context=None):
        res = super(od_hr_employee_document_line,
                    self).default_get(cr, uid, ids, context=context)
        res.update({'employee_id': context['active_id']})
        return res
예제 #13
0
class born_game_gift(osv.osv):
    _name = 'born.game.gift'
    _description = u"游戏奖品"

    name = fields.Char(u'名称', size=255, required=True, help=u"游戏名称")
    image = fields.Binary(string=u"图片", attachment=True, help=u"图片")
    product_id = fields.Many2one('product.product',
                                 string=u'产品',
                                 ondelete='cascade',
                                 help=u'商品')
    wxcard_id = fields.Many2one('tl.wxcard',
                                string=u'微信优惠券',
                                ondelete='cascade',
                                help=u'微信优惠券')
    redpack_amount = fields.Float(string=u"微信红包金额",
                                  digits=(2, 0),
                                  help=u'发送微信现金红包')

    description = fields.Text(u'说明', help=u"奖品说明")
예제 #14
0
class born_game(osv.osv):
    _name = 'born.game'
    _description = u"游戏"

    name = fields.Char(
        u'名称',
        size=255,
        help=u"游戏名称",
        required=True,
    )
    note = fields.Text(u'简介', size=255, required=True, help=u"简介")
    path = fields.Char(u'文件夹名称', size=255, required=True, help=u"文件夹名称")
    image_url = fields.Char(u'海报地址', size=255, help=u"海报地址")
    file_name = fields.Char(u'海报名称', size=255, help=u"海报名称")
    image = fields.Binary(string=u"游戏海报",
                          required=True,
                          attachment=True,
                          help=u"游戏海报")
    description = fields.Text(u'玩法说明', required=True, help=u"游戏玩法和说明")

    @api.model
    def create(self, vals):

        if vals.get('image', False):
            s3 = s3client(self)
            image_url = s3.upload(self._cr, self._uid, vals.get('image'),
                                  vals.get('file_name', 'image.png'))
            vals['image_url'] = image_url
        return super(born_game, self).create(vals)

    @api.multi
    def write(self, vals):

        if vals.get('image', False):
            s3 = s3client(self)
            image_url = s3.upload(self._cr, self._uid, vals.get('image'),
                                  vals.get('file_name', 'image.png'))
            vals['image_url'] = image_url
        return super(born_game, self).write(vals)
예제 #15
0
class SchoolTest(models.Model):
    _inherit = 'school.test'

    attachment = fields.Binary('Assignment File')
    file_name = fields.Char('File Name')

    @api.model
    def create(self, vals):
        school_test_obj = self.env['school.test.inmo']
        stest_id = school_test_obj.search([
            ('name', '=', vals['exam_id']),
            ('module_id', '=', vals['module_id']),
            ('intake_id', '=', vals['class_id'])
        ])
        if not stest_id:
            school_test_obj.create({
                'name': vals['exam_id'],
                'module_id': vals['module_id'],
                'intake_id': vals['class_id']
            })
        return super(SchoolTest, self).create(vals)

    @api.onchange('class_id', 'module_id')
    @api.depends('class_id', 'module_id')
    def _onchange_module_id(self):
        for rc in self:
            if rc.class_id and rc.module_id:
                school_test_obj = self.env['school.test.inmo']
                stest_id = school_test_obj.search([
                    ('module_id', '=', rc.module_id.id),
                    ('intake_id', '=', rc.class_id.id)
                ])
                if stest_id:
                    rc.exam_id = school_test_obj.browse(stest_id[0].id).name.id

    module_id = fields.Many2one('school.module', string='Module')
예제 #16
0
class res_users(models.Model):

    _inherit = 'res.users'

    signature_logo = fields.Binary(string='Signature Logo')
예제 #17
0
class ReporteCaja(models.Model):
    _name="reporte.orden_pago"
    _rec_name = 'titulo'

    orden_line=fields.One2many('reporte.orden_pago_detalle','id_relacion',string="Relacion")
    titulo=fields.Char(string="Titulo",default='Reporte de Orden de Pago')
    fecha_desde = fields.Date(string="Fecha desde")
    fecha_hasta = fields.Date(string="Fecha hasta")
    journal_ids=fields.Many2many('account.journal',string='Metodo de Pagos')
    partner_id=fields.Many2one('res.partner',string='Proveedor')
    usuario_id=fields.Many2one('res.users',string="Usuario", default=lambda self:self.env.user ,readonly=True)
    fecha_emision = fields.Date(string="Fecha Emision")
    estado_pagos =fields.Selection( (('draft','Borrador'),
                               ('posted','Contabilizado')),string='Estados de Pagos', required=False)
    tipo_reporte =fields.Selection( (('1','PDF - EXCEL'),
                               ('2','BIZ')),string='Tipo de Reporte', required=True,default='1')
    active = fields.Boolean(string="Activo",default=False)
    submotivo_pago = fields.Selection((('RPA','Orden de pago'),
                                        ('VIA','Viáticos'),
                                        ('TRA','Transporte'),
                                        ('COM','Comisiones'),
                                        ('HON','Honorarios'),
                                        ('ANT','Anticipo'),
                                        ('PRE','Préstamo'),
                                        ('UTI','Utilidades'),
                                        ('REE','Rembolso'),
                                        ('BON','Bono')),string="Sub Motivo de pago")

    filename=fields.Char(string="Nombre de archivo")
    archivo_xls=fields.Binary(string='Archivo Excel')
    filename_pdf=fields.Char(string="Nombre de archivo")
    archivo_pdf=fields.Binary(string='Archivo PDF')
    filename_txt=fields.Char(string="Nombre de archivo")
    archivo_txt=fields.Binary(string='Archivo BIZ')

    _defaults = {
        'fecha_emision': fields.datetime.now(),
    }

    def normalize(self,s):
        replacements = (
            ("á", "a"),
            ("é", "e"),
            ("í", "i"),
            ("ó", "o"),
            ("ú", "u"),
        )
        for a, b in replacements:
            s = s.replace(a, b).replace(a.upper(), b.upper())
        return s

    @api.constrains('fecha_desde','fecha_hasta','tipo_reporte')
    def validar_reporte(self):
        if self.tipo_reporte=='2':
            self.active=True
        else:
            self.active=False
#----------------------------------------------------------
#                     Obtencion de datos                  -
#---------------------------------------------------------- 
    @api.multi
    def consultar(self):
        self.env.cr.execute("delete from reporte_orden_pago_detalle where id_relacion={0}".format(self.id))
        lista_id=''
        if self.tipo_reporte=='2':
            self.active=True
        else:
            self.active=False
        if self.tipo_reporte!='':
            if self.fecha_desde and self.fecha_hasta and self.journal_ids and self.estado_pagos:
                for j in self.journal_ids:
                    if lista_id!='':
                        lista_id=lista_id+','+str(j.id)
                    else:
                        lista_id=str(j.id)
                sql="""SELECT id from account_voucher where date between '{0}' AND '{1}' and journal_id in ({2}) and state in ('{3}') and  type='payment' order by id,date,number asc""".format(self.fecha_desde,self.fecha_hasta,lista_id,self.estado_pagos)
            elif self.fecha_desde and self.fecha_hasta and len(self.journal_ids)==0 and self.estado_pagos== False:
                sql="""SELECT id from account_voucher where date between '{0}' AND '{1}' and  type='payment' order by id,date,number asc""".format(self.fecha_desde,self.fecha_hasta)
            elif self.fecha_desde and self.fecha_hasta and self.journal_ids and self.estado_pagos==False:
                for j in self.journal_ids:
                    if lista_id!='':
                        lista_id=lista_id+','+str(j.id)
                    else:
                        lista_id=str(j.id)            
                sql="""SELECT id from account_voucher where date between '{0}' AND '{1}' and journal_id in ({2}) and  type='payment' order by id,date,number asc""".format(self.fecha_desde,self.fecha_hasta,lista_id)
            elif self.fecha_desde and self.fecha_hasta and len(self.journal_ids)==0 and self.estado_pagos:
                sql="""SELECT id from account_voucher where date between '{0}' AND '{1}' and state in ('{2}') and  type='payment' order by id,date,number asc""".format(self.fecha_desde,self.fecha_hasta,self.estado_pagos)
        else:
            if self.fecha_desde and self.fecha_hasta and self.journal_ids and self.partner_id:
                for j in self.journal_ids:
                    if lista_id!='':
                        lista_id=lista_id+','+str(j.id)
                    else:
                        lista_id=str(j.id)
                sql="""SELECT id from account_voucher where date between '{0}' AND '{1}' and journal_id in ({2}) and partner_id={3} and state='posted' and  type='payment' order by id,date,number asc""".format(self.fecha_desde,self.fecha_hasta,lista_id,self.partner_id.id)
            elif self.fecha_desde and self.fecha_hasta and len(self.journal_ids)==0 and self.partner_id:
                sql="""SELECT id from account_voucher where date between '{0}' AND '{1}' and partner_id={2} and state='posted' and  type='payment' order by id,date,number asc""".format(self.fecha_desde,self.fecha_hasta,self.partner_id.id)
        self.env.cr.execute(sql)
        lista_facturas=self.env.cr.dictfetchall()
        lista_facturas_id = [value['id'] for value in lista_facturas]
        obj_datos=self.env['account.voucher'].search([('id','in',lista_facturas_id)])
        dic={}
        lista_datos=[]
        descripcion=''
        for l in obj_datos:
            obj_line = self.env['reporte.orden_pago_detalle'].create({
                'id_relacion':self.id,
                'id_proveedor':l.partner_id.id,
                'journal_id':l.journal_id.id,
                'date':l.date,
                'res_partner_bank_id': l.res_partner_bank_id.id,
                'amount':l.amount,
                'id_pago':l.id
                })
            #INTEGRACION: SE CAMBIA POR PEDIDO DE CAMBIO DE NUMERO
            number=''
            if l.numerofac=='' or l.numerofac == False :
                number='Borrador'
            else:
                number=l.numerofac
            print(str(l.journal_id.code),'str(l.journal_id.code)')
            vat_1=''
            if l.partner_id.vat!= False:
                vat_1=l.partner_id.vat
            else:
                vat_1='NA'
            dic={
            'id_pago':l.id,
            'fecha_emision':l.date,
            'egreso':l.egreso,
            'cheque':number,
            'beneficiario':l.partner_id.name,
            'observacion':l.narration,
            'valor':l.amount,
            'partner_id':l.partner_id.id,
            'nit':vat_1,
            'partner_name':l.partner_id.name,
            'journal_id':str(l.journal_id.code),
            'cod_banco':l.res_partner_bank_id.bank_bic,
            'cod_proveedor':l.res_partner_bank_id.codigo_proveedor
            }
            lista_datos.append(dic)

            if l.enviado== False:
                l.enviado= True
                l.veces_descarga=1
            else:
                l.veces_descarga=l.veces_descarga+1


        cadena=''
        for fil in self.journal_ids:
            obj_move_line=self.env['account.journal'].search([('id','=',fil.id)])
            if cadena=='':
                cadena=obj_move_line.name
            else:
                cadena=cadena+' ,'+obj_move_line.name

        if cadena=='':
            cadena='Todos los metodos de pago'

        if self.estado_pagos==False:
            cadena1="Todos"
        elif self.estado_pagos=='draft':
            cadena1="Borrador"
        else:
            cadena1="Contabilizado"

        datos={
            'lista':lista_datos,
            'cant':len(obj_datos),
            'filtro':cadena,
            'filtro1':cadena1,
        }

        return datos

#-------------------------------------------------------------------------------------------------------------------
#                     CREACION DE TXT                                                                              -
#-------------------------------------------------------------------------------------------------------------------
    @api.multi
    def generar_txt(self):
        contenido=""
        nombre=""
        A1=5
        A2=6
        A3=18
        A4=1
        A5=14
        A6=60
        A7=3
        A8=3
        A9=2
        A10=2
        A11=20
        A12=1
        A13=15
        A14=60
        A15=15
        A16=15
        A17=15
        A18=20
        A19=10
        A20=50
        A21=50
        A22=20
        A23=3
        A24=10
        A25=10
        A26=10
        A27=1
        A28=5
        A29=6
        A30=3
        A31=10

        secuencial=1
        for l in self.orden_line:
            A_1=''
            A_2=''
            A_3=''
            A_4=''
            A_5=''
            A_6=''
            A_7=''
            A_8='001'
            A_9=''
            A_10=''
            A_11=''
            A_12='1'
            A_13=''
            A_14=''
            A_15=''
            A_16=''
            A_17=''
            A_18=''
            A_19='          '
            A_20='                                                  '
            A_21='                                                  '
            A_22='                    '
            A_23='TER'
            A_24='          '
            A_25='          '
            A_26='          '
            A_27=' '
            A_28=''
            A_29='      '
            A_30=''
            A_31=''
            if l.pagar==True:
                A_1='BZDET'
                fun='%0{0}d'.format(A2)
                A_2=fun % secuencial
                val=str(l.id_pago.res_partner_bank_id.bank_bic).split(' ')
                fun='%0{0}d'.format(A3)
                if len(val)>1:
                    val=0.0
                    val=(val[0])
                    A_3=fun % (val)
                else:
                    A_3=fun % int(l.id_pago.res_partner_bank_id.bank_bic)
                ###  VALIDACION DE IDENTIFICACION
                if l.id_proveedor.vat!= False:
                    A_5=l.id_proveedor.vat
                else:
                    A_5='NA'
                if len(l.id_proveedor.vat)==10:
                    A_4='C'
                elif len(l.id_proveedor.vat)==13:           
                    A_4='R'
                else:
                    A_4='P'
                if len(l.id_proveedor.name)>=60:
                    A_6 =l.id_proveedor.name
                else:
                    A_6 =l.id_proveedor.name
                
                ### VALIDACION DEL METODO DE PAGO
                A_7=str(l.id_pago.journal_id.code)

                text1 = l.id_pago.narration
                lista_metodos = ['EFE','CHE','IMP','PEF']
                pago=''
                if str(l.id_pago.journal_id.code)in lista_metodos and l.id_pago.journal_id.exigir_codigo==False:
                   A_9='000'
                elif str(l.id_pago.journal_id.code) not in lista_metodos and l.id_pago.journal_id.exigir_codigo==False:
                   raise osv.except_osv(('Alerta'),("Configurar de manera correcta el Diario."))
                else:
                   A_9=l.id_pago.res_partner_bank_id.bank.bic

                if A_9==False:
                    A_9=''

                A_10=l.id_pago.res_partner_bank_id.state
                A_11=l.id_pago.res_partner_bank_id.acc_number

                ### VALIDACION DE MONTO
                A_13=''
                valor=str(l.id_pago.amount).split('.')
                if len(valor[1])==1:
                    cant=len(valor[0])
                    val=''
                    for i in range(cant, 13):
                        val=str(val)+'0'

                    A_13=str(val)+str(valor[0])+'00'
                else:
                    cant=len(valor[0])
                    val=''
                    for i in range(cant, 13):
                        val=str(val)+'0'

                    A_13=str(val)+str(valor[0])+str(valor[1])

                A_14=l.id_pago.narration
                if l.id_pago.number=='' or l.id_pago.number == False :
                    A_15='Borrador'
                else:
                    A_15=l.id_pago.number
                fun='%0{0}d'.format(A16)
                A_16=fun % 0
                fun='%0{0}d'.format(A17)
                A_17=fun % 0
                fun='%0{0}d'.format(A18)
                A_18=fun % 0

                if (l.id_proveedor.street)!=False:
                    A_21=str(l.id_proveedor.street)+' '+str(l.id_proveedor.street2)

                if (l.id_proveedor.phone)!=False:
                    A_22=str(l.id_proveedor.phone)

                A_30=str(self.submotivo_pago)

                contenido = contenido +str(A_1)+str(A_2)+str(A_3) + str(A_4) + str(A_5) + str(A_6) +  str(A_7) + str(A_8) + str(A_9.strip()) + str(A_10) + str(A_11)+ str(A_12) + str(A_13) + str(A_14) + str(A_15) + str(A_16) + str(A_17) + str(A_18) + str(A_19) + str(A_20)+ str(A_21) + str(A_22) + str(A_23) + str(A_24)+ str(A_25)+ str(A_26)+ str(A_27)+ str(A_28)+ str(A_29)+ str(A_30)+ str(A_31)
                contenido = contenido + str('\n')
                secuencial=secuencial+1

        now = datetime.now()
        anio = now.strftime('%Y')
        mes = now.strftime('%m')
        dia = now.strftime('%d')
        nombre=str(self.partner_id.name) + str(anio) + str(mes) + str(dia) + ".BIZ"
        contenido2 = contenido.encode('utf-8')
        self.write({'filename_txt': nombre, 'archivo_txt': bytes(base64.b64encode(contenido2))})
        return True


#-------------------------------------------------------------------------------------------------------------------
#                     CREACION DE EXCEL                                                                            -
#-------------------------------------------------------------------------------------------------------------------

    @api.multi
    def generar_excel(self):
        fp =io.BytesIO()
        workbook = self.crear_excel_info()
        workbook.save(fp)
        self.filename = 'Informe.xlsx'
        self.archivo_xls=base64.b64encode(fp.getvalue())      
        return True

    def crear_excel_info(self):
        wb = crear_informe_orden_pago_excel.crear_wb_informe()
        self.crear_informe(wb)
        return wb 


    def crear_informe(self, wb):
        fecha_a = datetime.strptime(self.fecha_emision, '%Y-%m-%d')
        fecha_actual = datetime.strftime(fecha_a, '%d/%b/%Y')
        dic ={
            'fecha_desde':self.fecha_desde,
            'fecha_hasta':self.fecha_hasta,
            'usuario_id':self.usuario_id.name,
            'fecha_corte':fecha_actual,
            'company_id':self.usuario_id.company_id.name,
        }

        lista_alumnos=[]
        cant_alumno=0
        datos=self.consultar()
        lista_datos=datos['lista']
        cant_datos=datos['cant']
        filtro=datos['filtro']
        filtro1=datos['filtro1']

        sheet_info = crear_informe_orden_pago_excel.crea_hoja_info(wb, 'Informe ',0)
        sheet_view = openpyxl.worksheet.SheetView()
        sheet_view.zoomScale = "130"
        sheet_view.zoomScaleNormal = "130"
        sheet_info.sheet_view = sheet_view
        sheet_info.zoomScale = "130"
        crear_informe_orden_pago_excel.Informe(sheet_info, dic,lista_datos,cant_datos,filtro,filtro1)

#-------------------------------------------------------------------------------------------------------------------
#                     CREACION DE PDF                                                                              -
#-------------------------------------------------------------------------------------------------------------------
    @api.multi
    def generar_pdf(self):
        filename_pdf=''
        filename_pdf=''
        fp =io.BytesIO()
        workbook = self.crear_excel_info_pdf()
        workbook.save(fp)
        filename_pdf = 'Informe.xlsx'
        archivo_pdf=base64.b64encode(fp.getvalue())
        obj=self.env['ir.attachment']
        obj_xls=obj.create({'res_model':self.id,'name':filename_pdf,'datas':archivo_pdf,'type':'binary','datas_fname':filename_pdf})
        direccion_xls=obj._get_path(obj_xls.datas)[1]
        direccion=obj._get_path(obj_xls.datas)[0]
        nombre_bin=obj_xls.store_fname
        nombre_archivo=obj_xls.datas_fname
        separa = direccion_xls.rstrip(direccion)
        os.chdir(separa)
        os.rename(nombre_bin,nombre_archivo)
        commands.getoutput(""" libreoffice --headless --convert-to pdf *.xlsx""") 
        with open(direccion_xls.rstrip(direccion)+'/'+nombre_archivo.split('.')[0]+'.pdf', "rb") as f:
            data = f.read()
            file= data.encode("base64")
        self.write({'filename_pdf':nombre_archivo.split('.')[0]+'.pdf','archivo_pdf':file})
        os.rename(nombre_archivo,nombre_bin)
        obj_xls.unlink()
        
        return True

    def crear_excel_info_pdf(self):
        wb = crear_informe_orden_pago_excel.crear_wb_informe()
        self.crear_informe_pdf(wb)
        return wb 

    def crear_informe_pdf(self, wb):
        fecha_a = datetime.strptime(self.fecha_emision, '%Y-%m-%d')
        fecha_actual = datetime.strftime(fecha_a, '%d/%b/%Y')
        dic ={
            'fecha_desde':self.fecha_desde,
            'fecha_hasta':self.fecha_hasta,
            'usuario_id':self.usuario_id.name,
            'fecha_corte':fecha_actual,
            'company_id':self.usuario_id.company_id.name,
        }

        lista_alumnos=[]
        cant_alumno=0
        datos=self.consultar()
        lista_datos=datos['lista']
        cant_datos=datos['cant']
        filtro=datos['filtro']
        filtro1=datos['filtro1']
        sheet_info = crear_informe_orden_pago_excel.crea_hoja_info_pdf(wb, 'Informe ',0)
        #sheet_info = crear_informe_cobranza_excel.crea_hoja_info(wb, 'Informe ',0)
        sheet_view = openpyxl.worksheet.SheetView()
        sheet_view.zoomScale = "70"
        sheet_view.zoomScaleNormal = "70"
        sheet_info.sheet_view = sheet_view
        sheet_info.zoomScale = "70"
        crear_informe_orden_pago_excel.Informe_pdf(sheet_info, dic,lista_datos,cant_datos,filtro,filtro1)
예제 #18
0
class vetclinic_images(models.Model):
    _name = 'vetclinic.images'

    name = fields.Char('Name:')
    image = fields.Binary('Image :')
예제 #19
0
class PagosAutomaticos(models.Model):
    _name = "pagos.automaticos"
    _rec_name = "display_name"

    usuario_id = fields.Many2one('res.users',
                                 string="Usuario",
                                 default=lambda self: self.env.user,
                                 readonly=True)
    codigo = fields.Char(string='Codigo')
    banco_id = fields.Many2one('res.partner.bank',
                               'Banco',
                               copy=False,
                               index=True)
    cuenta_banco = fields.Char(related='banco_id.acc_number',
                               string='Cuenta Bancaria',
                               size=20)
    fecha_creacion = fields.Datetime(
        'Fecha Creacion',
        readonly=True,
        copy=False,
        select=True,
    )
    archivo = fields.Binary(string='Archivo')
    filename = fields.Char(string="Nombre")
    pagos_line = fields.One2many('pagos.automaticos.detalle',
                                 'pagos_id',
                                 string="Relacion")
    estado = fields.Selection((('0', 'Borrador'), ('1', 'Validado')),
                              'Estado',
                              required=False,
                              default='0')
    display_name = fields.Char(string="Nombre a mostrar")
    journal_id = fields.Many2one('account.journal', string='Metodo de Pago')
    notas = fields.Text(string="Notas")
    account_journal_caja_id = fields.Many2one(
        'account.journal',
        string="Caja",
        default=lambda self: self._default_route_ids())
    exigir_doc_banco = fields.Boolean(related='journal_id.exigir_doc_banco',
                                      string="Exigir datos bancarios en pago")
    usuario_id = fields.Many2one('res.users',
                                 string="Usuario",
                                 default=lambda self: self.env.user,
                                 readonly=True)
    fecha_cobro = fields.Date(string='Fecha Cobro')
    active = fields.Boolean(string="Activo", default=False)

    @api.model
    def _default_route_ids(self):
        obj_datos = self.env['account.journal'].search([('usuarios_ids', 'in',
                                                         self._uid),
                                                        ('caja', '=', True)])
        if len(obj_datos) == 1:
            return obj_datos.id
        else:
            return False

    @api.constrains('codigo', 'banco_id', 'cuenta_banco')
    def guardar_display_name(self):
        if self.codigo == False:
            self.display_name = str(str('Cobro Automatico'))
        else:
            self.display_name = str(
                str('Cobro Automatico') + '/' + str(self.codigo))

    _defaults = {
        'fecha_creacion': fields.datetime.now(),
    }

    @api.multi
    def cargar_archivo(self):
        self.validar_xlsx(self.filename, self.archivo)

    @api.multi
    def validar_xlsx(self, filename, file):
        tmp = filename.split('.')
        ext = tmp[len(tmp) - 1]
        if ext == 'xlsx':
            self.cargar_xlsx(file)
        else:
            raise osv.except_osv(('Alerta'),
                                 ("El tipo de archivo debe ser xlsx."))

    def cambiar_formato(self, fecha):
        datetime_object = datetime.strptime(fecha, DATE_FORMAT)
        fecha_dato = datetime_object.date()
        return fecha_dato

    @api.multi
    def cargar_xlsx(self, file):
        #ssssssssssssstry:
        decoded_data = base64.b64decode(file)
        xls_file = io.BytesIO(decoded_data)
        wb = load_workbook(filename=xls_file, read_only=True)
        count = 0
        data2 = []
        ws = wb.active
        for i in range(1, ws.max_row + 1):
            data = []
            for j in range(1, ws.max_column + 1):

                cell_obj = ws.cell(row=i, column=j)
                data.append(cell_obj.value)

            data2.append(data)
        l = []
        orden = 0
        self.env.cr.execute(
            "delete from pagos_automaticos_detalle where pagos_id={0}".format(
                self.id))
        for l in data2:
            NUM_ORDEN = ''
            FECHA = ''
            NUM_CONTRATO = ''
            SERVICIO = ''
            CONCEPTO = ''
            IDENTFICACION = ''
            NOM_BENEF = ''
            FORMA_COBRO = ''
            CUENTA = ''
            MONEDA = ''
            VALOR = ''
            SALDO = ''
            EST_DETALLE = ''
            COD_ERROR = ''
            DESC_ERROR = ''
            TEXTO1 = ''
            TEXTO2 = ''
            if orden >= 1:
                NUM_ORDEN = str(l[0])
                FECHA = str(l[1])
                NUM_CONTRATO = str(l[2])
                SERVICIO = str(l[3])
                CONCEPTO = str(l[4])
                IDENTFICACION = str(l[5])
                NOM_BENEF = str(l[6])
                FORMA_COBRO = str(l[7])
                CUENTA = str(l[8])
                MONEDA = str(l[9])
                VALOR = str(l[10])
                SALDO = str(l[11])
                EST_DETALLE = str(l[12])
                COD_ERROR = str(l[13])
                DESC_ERROR = str(l[14])
                TEXTO1 = str(l[15])
                TEXTO2 = str(l[16])
                anio = FECHA[0:4]
                mes = FECHA[4:6]
                dia = FECHA[6:8]
                fecha_registro = str(anio + '-' + mes + '-' + dia)
                NUM_ORDEN = NUM_ORDEN.split('"')
                NUM_CONTRATO = NUM_CONTRATO.split('"')
                if len(NUM_CONTRATO[1]) != 0:
                    NUM_CONTRATO = NUM_CONTRATO[1].replace(' ', '')
                CUENTA = CUENTA.split('"')
                if len(CUENTA[1]) != 0:
                    CUENTA = CUENTA[1].replace(' ', '')
                VALOR = VALOR.split('"')
                if len(VALOR[1]) != 0:
                    VALOR = VALOR[1].replace(' ', '')
                SALDO = SALDO.split('"')
                if len(SALDO[1]) != 0:
                    SALDO = SALDO[1].replace(' ', '')
                CONCEPTO_FECHA = CONCEPTO.split(' ')
                CONCEPTO_FECHA = CONCEPTO_FECHA[1].split('/')
                fecha_factura = str(CONCEPTO_FECHA[2] + '-' +
                                    CONCEPTO_FECHA[1] + '-' +
                                    CONCEPTO_FECHA[0])
                obj_datos = self.env['res.partner'].search([
                    ('codigo_alumno', 'like', str(NUM_CONTRATO))
                ])
                if self.codigo == False:
                    obj_orden = self.env['pagos.automaticos'].search([
                        ('codigo', '=', NUM_ORDEN[1])
                    ])
                    if len(obj_orden) > 1:
                        raise osv.except_osv(('Alerta'), (
                            "El archivo cuenta con un codigo ya cargado al sistema."
                        ))
                    else:
                        self.codigo = NUM_ORDEN[1]
                if obj_datos:
                    if len(obj_datos) > 1:
                        for l in obj_datos:
                            obj_factura = self.env['account.invoice'].search([
                                ('alumno_id', '=', l.id),
                                ('residual', '=', VALOR),
                                ('date_invoice', '=', fecha_factura)
                            ])
                            if obj_factura.id:
                                lista_fact = [obj_factura.id]
                            else:
                                lista_fact = []
                            descripcion = ''
                            for fact in obj_factura.invoice_line:
                                descripcion = descripcion + fact.name + ' '
                            obj_detalle = self.env[
                                'pagos.automaticos.detalle'].create({
                                    'num_orden':
                                    NUM_ORDEN[1],
                                    'fecha_creacion':
                                    fecha_registro,
                                    'num_contrato':
                                    l.codigo_alumno,
                                    'servicios':
                                    SERVICIO,
                                    'concepto':
                                    CONCEPTO,
                                    'identificacion':
                                    l.vat,
                                    'nom_benef':
                                    l.name,
                                    'estudiante_id':
                                    l.id,
                                    'forma_cobro':
                                    FORMA_COBRO,
                                    'cuenta_banco':
                                    CUENTA,
                                    'moneda':
                                    MONEDA,
                                    'valor':
                                    VALOR,
                                    'saldo':
                                    SALDO,
                                    'est_detale':
                                    EST_DETALLE,
                                    'cod_error':
                                    COD_ERROR,
                                    'desc_error':
                                    DESC_ERROR,
                                    'descripcion':
                                    descripcion,
                                    #'texto1':'',
                                    #'texto2':'',
                                    'pagos_id':
                                    self.id,
                                    #'factura_id':lista_fact
                                })
                            if len(lista_fact) != 0:
                                obj_detalle.factura_id = lista_fact
                            else:
                                obj_detalle.factura_id = False
                            self.active = True
                        self.validar_facturas()
                    else:
                        obj_datos = self.env['res.partner'].search([
                            ('codigo_alumno', 'like', str(NUM_CONTRATO))
                        ])
                        descripcion = ''
                        obj_factura = self.env['account.invoice'].search([
                            ('alumno_id', '=', obj_datos.id),
                            ('residual', '=', VALOR),
                            ('date_invoice', '=', fecha_factura)
                        ])

                        if obj_factura.id:
                            lista_fact = [obj_factura.id]
                        else:
                            lista_fact = []
                        for fact in obj_factura.invoice_line:
                            descripcion = descripcion + fact.name + ' '
                        obj_detalle = self.env[
                            'pagos.automaticos.detalle'].create({
                                'num_orden':
                                NUM_ORDEN[1],
                                'fecha_creacion':
                                fecha_registro,
                                'num_contrato':
                                obj_datos.codigo_alumno,
                                'servicios':
                                SERVICIO,
                                'concepto':
                                CONCEPTO,
                                'identificacion':
                                obj_datos.vat,
                                'nom_benef':
                                obj_datos.name,
                                'estudiante_id':
                                obj_datos.id,
                                'forma_cobro':
                                FORMA_COBRO,
                                'cuenta_banco':
                                CUENTA,
                                'moneda':
                                MONEDA,
                                'valor':
                                VALOR,
                                'saldo':
                                SALDO,
                                'est_detale':
                                EST_DETALLE,
                                'cod_error':
                                COD_ERROR,
                                'desc_error':
                                DESC_ERROR,
                                'descripcion':
                                descripcion,
                                'pagos_id':
                                self.id,
                            })
                        if len(lista_fact) != 0:
                            obj_detalle.factura_id = lista_fact
                        else:
                            obj_detalle.factura_id = False
                        self.active = True
                        self.validar_facturas()
                else:
                    descripcion = ''
                    obj_detalle = self.env['pagos.automaticos.detalle'].create(
                        {
                            'num_orden': NUM_ORDEN[1],
                            'fecha_creacion': fecha_registro,
                            'num_contrato': str(NUM_CONTRATO),
                            'servicios': SERVICIO,
                            'concepto': CONCEPTO,
                            'identificacion': str(IDENTFICACION),
                            'nom_benef': str(NOM_BENEF),
                            'forma_cobro': FORMA_COBRO,
                            'cuenta_banco': CUENTA,
                            'moneda': MONEDA,
                            'valor': VALOR,
                            'saldo': SALDO,
                            'est_detale': EST_DETALLE,
                            'cod_error': 'Error del Número de Contrato',
                            'desc_error': DESC_ERROR,
                            'descripcion': descripcion,
                            'error': 'S',
                            'pagos_id': self.id,
                        })
                    self.env.cr.execute(
                        "update pagos_automaticos_detalle set num_contrato='{0}', nom_benef='{1}', identificacion='{2}' where pagos_id={3} and id={4}"
                        .format(str(NUM_CONTRATO), str(NOM_BENEF),
                                str(IDENTFICACION), self.id, obj_detalle.id))
            orden = 1

        self.estado = '0'

    # except Exception as e:
    #     comentario=("Por favor revisar el formato del archivo y los datos sean correctos.\n Fechas \n Concepto \n Saldo \n Valor \n Celdas vacias ")
    #     raise osv.except_osv(('Alerta'),comentario)

    @api.constrains('pagos_line')
    def validar_facturas(self):
        for l in self.pagos_line:
            cont = 0.0
            #self.env.cr.execute("delete from pagos_automaticos_facturas where cabecera_id={0}".format(l.id))
            if len(l.factura_id) != 0:
                for d in l.factura_id:
                    cont = cont + d.residual
                    if len(d.invoice_line) != 0:
                        descripcion = ''
                        for a in d.invoice_line:
                            descripcion = descripcion + a.name + ' '
                l.descripcion = descripcion
                if l.valor != cont:
                    if l.valor < cont:
                        comentario = (
                            "Contrato: {0} - Valor Cobro: {1} - Valor Facturas: {2} \n El monto de las facturas es mayor que el valor a pagar.\n "
                        ).format(l.num_contrato, l.valor, cont)
                        raise osv.except_osv(('Alerta2'), comentario)
                    else:
                        comentario = (
                            "Contrato: {0} - Valor Cobro: {1} - Valor Facturas: {2} \n El monto de las facturas es menor que el valor a pagar.\n "
                        ).format(l.num_contrato, l.valor, cont)
                        raise osv.except_osv(('Alerta2'), comentario)
                else:
                    for f in l.factura_id:
                        obj_factura_d = self.env['pagos.automaticos.facturas']
                        obj_valida = self.env[
                            'pagos.automaticos.facturas'].search([
                                ('cabecera_id', '=', l.id),
                                ('factura_id', '=', f.id)
                            ])
                        if len(obj_valida) == 0:
                            objeto = obj_factura_d.create({
                                'cabecera_id':
                                l.id,
                                'estudiante_id':
                                l.estudiante_id.id,
                                'factura_id':
                                f.id,
                            })
            else:
                l.descripcion = ''
                self.env.cr.execute(
                    "delete from pagos_automaticos_facturas where cabecera_id={0}"
                    .format(l.id))

    @api.multi
    def validar_cobros(self):
        # try:
        for l in self.pagos_line:
            if len(l.factura_id) == 0:
                #l.error_sistema='No cuenta con factura para realizar el pago'
                #l.error='S'
                obj_cobro = self.env['account.voucher']
                obj_cobro_linea = self.env['account.voucher.line']
                #obj_factura=self.env['account.invoice'].search([('id','=',f.id)])
                #obj_factura.invoice_pay_customer()
                #obj_factura.button_proforma_voucher()
                print(l.estudiante_id.id, 'l.estudiante_id')
                print(l.moneda, 'l.moneda')
                obj_alumno = self.env['res.partner'].search([
                    ('id', '=', int(l.estudiante_id.id))
                ])
                obj_moneda = self.env['res.currency'].search([('name', 'like',
                                                               l.moneda)])
                print(obj_moneda.id, 'obj_moneda')
                print(obj_alumno.id, 'obj_alumno')
                print(obj_alumno.parent_id.id, 'partner_id')
                obj_dato_c = obj_cobro.create({
                    'date_due':
                    self.fecha_cobro,
                    'escolar':
                    True,
                    'alumno_id':
                    obj_alumno.id,
                    'partner_id':
                    obj_alumno.parent_id.id,
                    'amount':
                    float(l.valor),
                    'comment':
                    'Write-Off',
                    'account_journal_caja_id':
                    self.account_journal_caja_id.id,
                    'journal_id':
                    self.journal_id.id,
                    'payment_rate_currency_id':
                    obj_moneda.id,
                    'account_id':
                    self.journal_id.default_debit_account_id.id,
                    'company_id':
                    obj_alumno.company_id.id,
                    'payment_rate':
                    1.000000,
                    #'payment_option':'without_writeoff',
                    #'currency_id': obj_factura.currency_id.id,
                    #'reference': obj_factura.name,
                    #'invoice_type': obj_factura.type,
                    #'invoice_id': obj_factura.id,
                    #'default_type': inv.type in ('out_invoice','out_refund') and 'receipt' or 'payment',
                    'type':
                    'receipt',
                })
                #obj_move_p = self.env['account.move.line'].search([('account_id','=',obj_factura.account_id.id),('ref','=',str(obj_factura.number))])
                # obj_data_c_d = obj_cobro_linea.create({
                #     'reconcile':True,
                #     'amount_unreconciled':l.valor,
                #     'company_id':self.usuario_id.company_id.id,
                #     'type':'cr',
                #     #'account_id':obj_factura.account_id.id,
                #     'voucher_id':obj_dato_c.id,
                #     'amount_original':l.valor,
                #     'name':'',
                #     #'move_line_id':obj_move_p.id,
                #     'amount':l.valor,
                #     })

                if obj_dato_c:  # and obj_data_c_d:
                    obj_dato_c.proforma_voucher()
                    obj_dato_c.button_proforma_voucher()
                #comentario=("Contrato: {0} - Valor Cobro: {1} \n Debe seleccionar factura a pagar.\n ").format(l.num_contrato,l.valor)
                #raise osv.except_osv(('Alerta'),comentario)
            else:
                for f in l.factura_id:
                    obj_cobro = self.env['account.voucher']
                    obj_cobro_linea = self.env['account.voucher.line']
                    obj_factura = self.env['account.invoice'].search([
                        ('id', '=', f.id)
                    ])
                    obj_factura.invoice_pay_customer()
                    #obj_factura.button_proforma_voucher()
                    obj_dato_c = obj_cobro.create({
                        'date_due':
                        self.fecha_cobro,
                        'escolar':
                        True,
                        'alumno_id':
                        obj_factura.alumno_id.id,
                        'partner_id':
                        obj_factura.partner_id.id,
                        'amount':
                        obj_factura.residual,
                        'account_journal_caja_id':
                        self.account_journal_caja_id.id,
                        'currency_id':
                        obj_factura.currency_id.id,
                        'reference':
                        obj_factura.name,
                        'invoice_type':
                        obj_factura.type,
                        'invoice_id':
                        obj_factura.id,
                        'journal_id':
                        self.journal_id.id,
                        'account_id':
                        self.journal_id.default_debit_account_id.id,
                        #'default_type': inv.type in ('out_invoice','out_refund') and 'receipt' or 'payment',
                        'type':
                        obj_factura.type in ('out_invoice', 'out_refund')
                        and 'receipt' or 'payment',
                    })
                    obj_move_p = self.env['account.move.line'].search([
                        ('account_id', '=', obj_factura.account_id.id),
                        ('ref', '=', str(obj_factura.number))
                    ])
                    obj_data_c_d = obj_cobro_linea.create({
                        'reconcile':
                        True,
                        'amount_unreconciled':
                        obj_factura.residual,
                        'company_id':
                        self.usuario_id.company_id.id,
                        'type':
                        'cr',
                        'account_id':
                        obj_factura.account_id.id,
                        'voucher_id':
                        obj_dato_c.id,
                        'amount_original':
                        obj_factura.residual,
                        'name':
                        '',
                        'move_line_id':
                        obj_move_p.id,
                        'amount':
                        obj_factura.residual,
                    })

                    if obj_dato_c and obj_data_c_d:
                        obj_dato_c.proforma_voucher()
                        obj_dato_c.button_proforma_voucher()

        self.estado = '1'
        viewid = self.env.ref(
            "ans_cobros_banco.cerrar_ventana_cobros_falla").id
        return {
            'name': 'Cobros Generados con Éxito!',
            'view_type': 'form',
            'views': [(viewid, 'form')],
            'res_model': 'close.window.purchase',
            'type': 'ir.actions.act_window',
            'target': 'new',
        }
예제 #20
0
class document_wiz(models.TransientModel):
    _name = 'document_wiz'
    data = fields.Binary()
    nom_fichier = fields.Char(string="Nom du fichier")
예제 #21
0
class Reporte_recordatorio(models.Model):
    _inherit = "recordatorio"

    filename = fields.Char(string="Nombre de archivo")
    archivo_xls = fields.Binary(string='Archivo Excel')
    filename_pdf = fields.Char(string="Nombre de archivo")
    archivo_pdf = fields.Binary(string='Archivo PDF')
    usuario_id = fields.Many2one('res.users',
                                 string="Usuario",
                                 default=lambda self: self.env.user,
                                 readonly=True)

    #----------------------------------------------------------
    #                     Obtencion de datos                  -
    #----------------------------------------------------------
    @api.multi
    def consultar(self):
        lista_datos = []
        orden = 0
        for l in self.recordatorio_detalle:
            orden = orden + 1
            dic = {
                'orden': orden,
                'sequence': self.sequence,
                'descripcion': l.descripcion,
                'jornada': l.jornada_id.name,
                'seccion': l.seccion_id.name,
                'curso': l.curso_id.name,
                'paralelo': l.paralelo_id.codigo,
                'alumno': l.alumno_id.name,
                'representante': l.representante_id.name,
                'correo': l.correo_repres,
                'numero_factura': l.factura_id.numerofac,
                'fecha_factura': l.fecha_factura,
                'concepto': l.concepto,
                'monto': l.monto,
                'saldo': l.saldo,
                'notificaciones': l.cant_notificacion,
                'fecha_envio_correo': l.fecha_envio_correo
            }
            lista_datos.append(dic)

        datos = {
            'lista': lista_datos,
            'cant': len(self.recordatorio_detalle),
        }

        return datos

#-------------------------------------------------------------------------------------------------------------------
#                     CREACION DE EXCEL                                                                            -
#-------------------------------------------------------------------------------------------------------------------

    @api.multi
    def generar_excel(self):
        fp = io.BytesIO()
        workbook = self.crear_excel_info()
        workbook.save(fp)
        ahora = datetime.now()
        dia = ahora.day
        mes = ahora.month
        anio = ahora.year
        self.filename = 'Recordatorio_%s_%s_%s.xlsx' % (str(dia), str(mes),
                                                        str(anio))
        self.archivo_xls = base64.b64encode(fp.getvalue())
        return True

    def crear_excel_info(self):
        wb = crear_informe_recordatorio_excel.crear_wb_informe()
        self.crear_informe(wb)
        return wb

    def crear_informe(self, wb):
        now = datetime.now()
        dic = {
            'fecha_desde': self.fecha_desde,
            'fecha_hasta': self.fecha_hasta,
            'company_id': self.usuario_id.company_id.name,
            'usuario_id': self.usuario_id.name,
            'fecha_emision': now,
            'jornada': self.jornada_id.name,
            'seccion': self.seccion_id.name,
            'curso': self.curso_id.name,
            'paralelo': self.paralelo_id.codigo,
            'representante': self.representante_id.name,
            'alumno': self.alumno_id.name
        }

        lista_alumnos = []
        cant_alumno = 0
        datos = self.consultar()
        lista_datos = datos['lista']
        cant_datos = datos['cant']
        sheet_info = crear_informe_recordatorio_excel.crea_hoja_info(
            wb, 'Recordatorio ', 0)
        #sheet_info = crear_informe_cobranza_excel.crea_hoja_info(wb, 'Informe ',0)
        sheet_view = openpyxl.worksheet.SheetView()
        sheet_view.zoomScale = "130"
        sheet_view.zoomScaleNormal = "130"
        sheet_info.sheet_view = sheet_view
        sheet_info.zoomScale = "130"
        crear_informe_recordatorio_excel.Informe(sheet_info, dic, lista_datos)

#-------------------------------------------------------------------------------------------------------------------
#                     CREACION DE PDF                                                                              -
#-------------------------------------------------------------------------------------------------------------------

    @api.multi
    def generar_pdf(self):
        filename_pdf = ''
        fp = io.BytesIO()
        workbook = self.crear_excel_info_pdf()
        workbook.save(fp)
        ahora = datetime.now()
        dia = ahora.day
        mes = ahora.month
        anio = ahora.year
        filename_pdf = 'Recordatorio_%s_%s_%s.xlsx' % (str(dia), str(mes),
                                                       str(anio))
        archivo_pdf = base64.b64encode(fp.getvalue())
        obj = self.env['ir.attachment']
        obj_xls = obj.create({
            'res_model': self.id,
            'name': filename_pdf,
            'datas': archivo_pdf,
            'type': 'binary',
            'datas_fname': filename_pdf
        })
        direccion_xls = obj._get_path(obj_xls.datas)[1]
        direccion = obj._get_path(obj_xls.datas)[0]
        nombre_bin = obj_xls.store_fname
        nombre_archivo = obj_xls.datas_fname
        separa = direccion_xls.rstrip(direccion)
        os.chdir(separa)
        os.rename(nombre_bin, nombre_archivo)
        commands.getoutput(
            """ libreoffice --headless --convert-to pdf *.xlsx""")
        with open(
                direccion_xls.rstrip(direccion) + '/' +
                nombre_archivo.split('.')[0] + '.pdf', "rb") as f:
            data = f.read()
            file = data.encode("base64")
        self.write({
            'filename_pdf': nombre_archivo.split('.')[0] + '.pdf',
            'archivo_pdf': file
        })
        os.rename(nombre_archivo, nombre_bin)
        obj_xls.unlink()

        return True

    def crear_excel_info_pdf(self):
        wb = crear_informe_recordatorio_excel.crear_wb_informe()
        self.crear_informe_pdf(wb)
        return wb

    def crear_informe_pdf(self, wb):
        now = datetime.now()
        # fecha_a = datetime.strptime(now, '%Y-%m-%d')
        # fecha_actual = datetime.strftime(fecha_a, '%d/%b/%Y')
        dic = {
            'fecha_desde': self.fecha_desde,
            'fecha_hasta': self.fecha_hasta,
            'company_id': self.usuario_id.company_id.name,
            'usuario_id': self.usuario_id.name,
            'fecha_emision': now,
            'jornada': self.jornada_id.name,
            'seccion': self.seccion_id.name,
            'curso': self.curso_id.name,
            'paralelo': self.paralelo_id.codigo,
            'representante': self.representante_id.name,
            'alumno': self.alumno_id.name
        }

        lista_alumnos = []
        cant_alumno = 0
        datos = self.consultar()
        lista_datos = datos['lista']
        cant_datos = datos['cant']
        sheet_info = crear_informe_recordatorio_excel.crea_hoja_info_pdf(
            wb, 'Recordatorio ', 0)
        #sheet_info = crear_informe_cobranza_excel.crea_hoja_info(wb, 'Informe ',0)
        sheet_view = openpyxl.worksheet.SheetView()
        sheet_view.zoomScale = "50"
        sheet_view.zoomScaleNormal = "50"
        sheet_info.sheet_view = sheet_view
        sheet_info.zoomScale = "50"
        crear_informe_recordatorio_excel.Informe_pdf(sheet_info, dic,
                                                     lista_datos)
예제 #22
0
class import_data(models.Model):
    _name = 'import.data'

    binary_data = fields.Binary('Binary Field')

    # @api.multi
    # def create_custom(self,local):
    #
    #     self.env['product.template'].sudo().create({'name':local[0]})
    #     self.env.cr.execute("SELECT id from product_template where name = '%s'" %(local[0]))
    #     vals = self.env.cr.fetchone()[0]
    #     vals1 = self.env['product.template'].browse(vals)
    #
    #     self.env.cr.execute("SELECT id from product_category where name = '%s'" % (local[2]))
    #     prod_catg1 = self.env.cr.fetchone()[0]
    #
    #     bool = True
    #     purch = True
    #     c = ''
    #     act = True
    #     pcm = ''
    #     pv = ''
    #     routes_buy1 = 0
    #
    #     if local[3] == 'Y': bool = True
    #     elif local[3] == 'N': bool = False
    #     if local[4] == 'Y': purch = True
    #     elif local[4] == 'N': purch = False
    #     if local[5] == 'Consumable' or local[5] == 'consumable' : c = 'consu'
    #     elif local[5] == 'Stockable Product' or local[5] == 'stockable product': c = 'product'
    #     elif local[5] == 'service' or local[5] == 'Service': c = 'service'
    #     if local[6] == 'Y' or local[6] == 'y' : act = True
    #     elif local[6] == 'N' or local[6] == 'n': act = False
    #
    #
    #     if local[8] == 'Standard Price' or local[8] == 'standard price': pcm = 'standard'
    #     elif local[8] == 'Average Price' or local[8] == 'average price': pcm = 'average'
    #     elif local[8] == 'Real Price' or local[8] == 'real price': pcm = 'real'
    #     if local[10] == 'Buy' or local[10] == 'buy':
    #         self.env.cr.execute("select id from stock_location_route where name = '%s'" %local[10])
    #         routes_buy1 = self.env.cr.fetchone()[0]
    #     elif local[10] == 'Make To Order' or local[10] == 'make to order' or local[10] == 'Make to Order':
    #         self.env.cr.execute("select id from stock_location_route where name = '%s'" %local[10])
    #         routes_buy1 = self.env.cr.fetchone()[0]
    #     elif local[10] == 'Manufacture' or local[10] == 'manufacture':
    #         self.env.cr.execute("select id from stock_location_route where name = '%s'" %local[10])
    #         routes_buy1 = self.env.cr.fetchone()[0]
    #     if local[11] == 'Periodic(manual)' or local[11] == 'periodic(manual)':
    #         pv = 'manual_periodic'
    #     elif local[11] == 'Perpetual(automated)' or local[11] == 'perpetual(automated)':
    #         pv = 'real_time'
    #     self.env.cr.execute("SELECT id from account_account where name = '%s' " %(local[12]))
    #     record1 = self.env.cr.fetchone()[0]
    #     self.env.cr.execute("SELECT id from account_account where name ='%s'" %(local[13]))
    #     account_record1 = self.env.cr.fetchone()[0]
    #     self.env.cr.execute("SELECT id from account_account where name = '%s'" %(local[14]))
    #     stock_record_income1 = self.env.cr.fetchone()[0]
    #     self.env.cr.execute("SELECT id from account_account where name = '%s'" %(local[15]))
    #     stock_record_outcome1 = self.env.cr.fetchone()[0]
    #
    #
    #     vals1.sudo().write({'description':local[1],
    #                         'categ_id':prod_catg1,
    #                         'sale_ok':bool,
    #                         'purchase_ok':purch,
    #                         'type':c,
    #                         'active':act,
    #                         'default_code':local[7],
    #                         'property_cost_method':pcm,
    #                         'standard_price':local[9],
    #                         'route_ids':[(6,0,[routes_buy1])],
    #                         'property_valuation':pv,
    #                         'property_account_income_id':record1,
    #                         'property_account_expense_id':account_record1,
    #                         'property_stock_account_input':stock_record_income1,
    #                         'property_stock_account_output':stock_record_outcome1,
    #                         })
    # @api.multi
    # def update_custom(self,local,new_vals):
    #     sale = ''
    #     purchase = ''
    #     product_type = ''
    #     act = ''
    #     price = ''
    #     routes_buy1 = 0
    #     property=''
    #     self.env.cr.execute("SELECT id from product_category where name = '%s'" %(local[2]))
    #     prod_catg1 = self.env.cr.fetchone()[0]
    #     if local[3] == 'Y': sale = True
    #     elif local[3] == 'N': sale = False
    #     if local[4] == 'Y': purchase = True
    #     elif local[5] == 'N': purchase = False
    #     if local[5] == 'Consumable' or local[5] == 'consumable' : product_type = 'consu'
    #     elif local[5] == 'Stockable Product' or local[5] == 'Stockable product': product_type = 'product'
    #     elif local[5] == 'service' or local[5] == 'Service': product_type = 'service'
    #     if local[6] == 'Y' or local[6] == 'y' : act = True
    #     elif local[6] == 'N' or local[6] == 'n': act = False
    #     if local[8] == 'Standard Price' or local[8] == 'standard price': price = 'standard'
    #     elif local[8] == 'Average Price' or local[8] == 'average price': price = 'average'
    #     elif local[8] == 'Real Price' or local[8] == 'real price': price = 'real'
    #     if local[10] == 'Buy' or local[10] == 'buy':
    #         self.env.cr.execute("select id from stock_location_route where name = '%s'" %local[10])
    #         routes_buy1 = self.env.cr.fetchone()[0]
    #     elif local[10] == 'Make To Order' or local[10] == 'make to order' or local[10] == 'Make to Order':
    #         self.env.cr.execute("select id from stock_location_route where name = '%s'" %local[10])
    #         routes_buy1 = self.env.cr.fetchone()[0]
    #     elif local[10] == 'Manufacture' or local[10] == 'manufacture':
    #         self.env.cr.execute("select id from stock_location_route where name = '%s'" %local[10])
    #         routes_buy1 = self.env.cr.fetchone()[0]
    #     if local[11] == 'Periodic(manual)' or local[11] == 'periodic(manual)': property = 'manual_periodic'
    #     elif local[11] == 'Perpetual(automated)' or local[11] == 'perpetual(automated)': property = 'real_time'
    #     self.env.cr.execute("SELECT id from account_account where name = '%s' " %(local[12]))
    #     record1 = self.env.cr.fetchone()[0]
    #     self.env.cr.execute("SELECT id from account_account where name ='%s'" %(local[13]))
    #     account_record1 = self.env.cr.fetchone()[0]
    #     self.env.cr.execute("SELECT id from account_account where name = '%s'" %(local[14]))
    #     stock_record_income1 = self.env.cr.fetchone()[0]
    #     self.env.cr.execute("SELECT id from account_account where name = '%s'" %(local[15]))
    #     stock_record_outcome1 = self.env.cr.fetchone()[0]
    #     new_vals.sudo().write({
    #         'description':local[1],
    #         'categ_id':prod_catg1,
    #         'sale_ok':sale,
    #         'purchase_ok':purchase,
    #         'type':product_type,
    #         'active':act,
    #         'default_code':local[7],
    #         'property_cost_method':price,
    #         'standard_price':local[9],
    #         'route_ids':[(6,0,[routes_buy1])],
    #         'property_valuation':property,
    #         'property_account_income_id':record1,
    #         'property_account_expense_id':account_record1,
    #         'property_stock_account_input':stock_record_income1,
    #         'property_stock_account_output':stock_record_outcome1,
    #     })

    @api.multi
    def mixed_function(self, local):
        print "INSIDE MIXED FUNCTION==============================\n"
        # sale = ''
        # purchase = ''
        # product_type = ''
        # act = ''
        # price = ''
        # routes_buy1 = 0
        # property=''
        #
        # self.env.cr.execute("SELECT id from product_category where name = '%s'" %(local[2]))
        # prod_catg1 = self.env.cr.fetchone()[0]
        #
        # if local[3] == 'Y': sale = True
        # elif local[3] == 'N': sale = False
        #
        # if local[4] == 'Y': purchase = True
        # elif local[5] == 'N': purchase = False
        #
        # if local[5] == 'Consumable' or local[5] == 'consumable' : product_type = 'consu'
        # elif local[5] == 'Stockable Product' or local[5] == 'stockable product': product_type = 'product'
        # elif local[5] == 'service' or local[5] == 'Service': product_type = 'service'
        #
        # if local[6] == 'Y' or local[6] == 'y' : act = True
        # elif local[6] == 'N' or local[6] == 'n': act = False
        #
        # if local[8] == 'Standard Price' or local[8] == 'standard price': price = 'standard'
        # elif local[8] == 'Average Price' or local[8] == 'average price': price = 'average'
        # elif local[8] == 'Real Price' or local[8] == 'real price': price = 'real'
        #
        # if local[10] == 'Buy' or local[10] == 'buy':
        #     self.env.cr.execute("select id from stock_location_route where name = '%s'" %local[10])
        #     routes_buy1 = self.env.cr.fetchone()[0]
        # elif local[10] == 'Make To Order' or local[10] == 'make to order' or local[10] == 'Make to Order':
        #     self.env.cr.execute("select id from stock_location_route where name = '%s'" %local[10])
        #     routes_buy1 = self.env.cr.fetchone()[0]
        # elif local[10] == 'Manufacture' or local[10] == 'manufacture':
        #     self.env.cr.execute("select id from stock_location_route where name = '%s'" %local[10])
        #     routes_buy1 = self.env.cr.fetchone()[0]
        #
        # if local[11] == 'Periodic(manual)' or local[11] == 'periodic(manual)': property = 'manual_periodic'
        # elif local[11] == 'Perpetual(automated)' or local[11] == 'perpetual(automated)': property = 'real_time'
        #
        # self.env.cr.execute("SELECT id from account_account where name = '%s' " %(local[12]))
        # record1 = self.env.cr.fetchone()[0]
        #
        # self.env.cr.execute("SELECT id from account_account where name ='%s'" %(local[13]))
        # account_record1 = self.env.cr.fetchone()[0]
        #
        # self.env.cr.execute("SELECT id from account_account where name = '%s'" %(local[14]))
        # stock_record_income1 = self.env.cr.fetchone()[0]
        #
        # self.env.cr.execute("SELECT id from account_account where name = '%s'" %(local[15]))
        # stock_record_outcome1 = self.env.cr.fetchone()[0]

        new_vals = self.env['product.template'].search([('name', '=', local[0])
                                                        ])
        if new_vals.name == local[0]:
            print "Inside UPDATE===========================\n",
            # new_vals.sudo().write({
            #                         'description':local[1],
            #                         'categ_id':prod_catg1,
            #                         'sale_ok':sale,
            #                         'purchase_ok':purchase,
            #                         'type':product_type,
            #                         'active':act,
            #                         'default_code':local[7],
            #                         'property_cost_method':price,
            #                         'standard_price':local[9],
            #                         'route_ids':[(6,0,[routes_buy1])],
            #                         'property_valuation':property,
            #                         'property_account_income_id':record1,
            #                         'property_account_expense_id':account_record1,
            #                         'property_stock_account_input':stock_record_income1,
            #                         'property_stock_account_output':stock_record_outcome1,
            #                      })

        elif new_vals.name != local[0]:
            print "INSIDE CREATE================================\n"
            self.env['product.template'].sudo().create({'name': local[0]})
            self.env.cr.execute(
                "SELECT id from product_template where name = '%s'" %
                (local[0]))
            vals = self.env.cr.fetchone()[0]
            vals1 = self.env['product.template'].browse(vals)
            # vals1.sudo().write({
            #                         'description':local[1],
            #                         'categ_id':prod_catg1,
            #                         'sale_ok':sale,
            #                         'purchase_ok':purchase,
            #                         'type':product_type,
            #                         'active':act,
            #                         'default_code':local[7],
            #                         'property_cost_method':price,
            #                         'standard_price':local[9],
            #                         'route_ids':[(6,0,[routes_buy1])],
            #                         'property_valuation':property,
            #                         'property_account_income_id':record1,
            #                         'property_account_expense_id':account_record1,
            #                         'property_stock_account_input':stock_record_income1,
            #                         'property_stock_account_output':stock_record_outcome1,
            #                      })

    @api.multi
    def variables(self, local):
        # list.append(9)
        print "INSIDE VARIABLES==============================\n"
        sale = ''
        purchase = ''
        product_type = ''
        act = ''
        price = ''
        routes_buy1 = 0
        property = ''

        self.env.cr.execute(
            "SELECT id from product_category where name = '%s'" % (local[2]))
        prod_catg1 = self.env.cr.fetchone()[0]

        if local[3] == 'Y': sale = True
        elif local[3] == 'N': sale = False

        if local[4] == 'Y': purchase = True
        elif local[5] == 'N': purchase = False

        if local[5] == 'Consumable' or local[5] == 'consumable':
            product_type = 'consu'
        elif local[5] == 'Stockable Product' or local[5] == 'stockable product':
            product_type = 'product'
        elif local[5] == 'service' or local[5] == 'Service':
            product_type = 'service'

        if local[6] == 'Y' or local[6] == 'y': act = True
        elif local[6] == 'N' or local[6] == 'n': act = False

        if local[8] == 'Standard Price' or local[8] == 'standard price':
            price = 'standard'
        elif local[8] == 'Average Price' or local[8] == 'average price':
            price = 'average'
        elif local[8] == 'Real Price' or local[8] == 'real price':
            price = 'real'

        if local[10] == 'Buy' or local[10] == 'buy':
            self.env.cr.execute(
                "select id from stock_location_route where name = '%s'" %
                local[10])
            routes_buy1 = self.env.cr.fetchone()[0]
        elif local[10] == 'Make To Order' or local[
                10] == 'make to order' or local[10] == 'Make to Order':
            self.env.cr.execute(
                "select id from stock_location_route where name = '%s'" %
                local[10])
            routes_buy1 = self.env.cr.fetchone()[0]
        elif local[10] == 'Manufacture' or local[10] == 'manufacture':
            self.env.cr.execute(
                "select id from stock_location_route where name = '%s'" %
                local[10])
            routes_buy1 = self.env.cr.fetchone()[0]

        if local[11] == 'Periodic(manual)' or local[11] == 'periodic(manual)':
            property = 'manual_periodic'
        elif local[11] == 'Perpetual(automated)' or local[
                11] == 'perpetual(automated)':
            property = 'real_time'

        self.env.cr.execute(
            "SELECT id from account_account where name = '%s' " % (local[12]))
        record1 = self.env.cr.fetchone()[0]

        self.env.cr.execute("SELECT id from account_account where name ='%s'" %
                            (local[13]))
        account_record1 = self.env.cr.fetchone()[0]

        self.env.cr.execute(
            "SELECT id from account_account where name = '%s'" % (local[14]))
        stock_record_income1 = self.env.cr.fetchone()[0]

        self.env.cr.execute(
            "SELECT id from account_account where name = '%s'" % (local[15]))
        stock_record_outcome1 = self.env.cr.fetchone()[0]

        new_list = [
            prod_catg1, sale, purchase, product_type, act, price, routes_buy1,
            property, record1, account_record1, stock_record_income1,
            stock_record_outcome1
        ]
        print "NEW LIST RECORDS======================================", new_list
        return new_list

    @api.multi
    def import_data_calculate(self):
        print "Start", datetime.now()
        data = self.binary_data
        file_datas = base64.b64decode(data)
        file = open("/home/bista/odoo-9/new_file.xls", "w")
        file.write(file_datas)
        file.close()
        book = xlrd.open_workbook("/home/bista/odoo-9/new_file.xls")
        first_sheet = book.sheet_by_index(0)
        n = 2
        for i in range(2, first_sheet.nrows):
            print "NUMBER=======================\n", i
            local = first_sheet.row_values(n, 0)
            # list = [1,2,3,4,5]
            if i == n:
                y = self.variables(local)
                print "==================\n", y

            self.mixed_function(local)
            print "OUTSIDE FUNCTION==================", y

            # new_vals = self.env['product.template'].search([('name','=',local[0])])

            # if new_vals.name == local[0]:
            #     self.update_custom(local,new_vals)
            # elif new_vals.name != local[0]:
            #     self.create_custom(local)
            n = n + 1
        print "Stop", datetime.now()
예제 #23
0
class dym_journal_elimination(models.Model):
    _name = 'dym.journal.elimination'
    _description = 'Journal Elimination (ALL COMPANY)'

    STATE_SELECTION = [
        ('draft', 'Draft'),
        ('waiting_for_approval','Waiting For Approval'),
        ('confirm','Confirmed'),
        ('cancel','Cancelled')
    ]
                    
    @api.cr_uid_ids_context
    def get_group_company(self,cr,uid, ids, context=None):
        user_obj = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid)
        company = user_obj.company_id
        while company.parent_id:
            company = company.parent_id
        return company

    @api.cr_uid_ids_context
    def _get_default_branch(self,cr,uid,ids,context=None):
        user_obj = self.pool.get('res.users')        
        user_browse = user_obj.browse(cr,SUPERUSER_ID,uid)
        branch_ids = False
        branch_ids = user_browse.branch_ids and len(user_browse.branch_ids) == 1 and user_browse.branch_ids[0].id or False                
        return branch_ids 
            
    branch_id = fields.Many2one('dym.branch', string='Branch Approval', required=True, default=_get_default_branch)
    division = fields.Selection([('Finance','Finance')], string='Division',default='Finance', required=True,change_default=True, select=True)
    name = fields.Char(string='No')
    date = fields.Date(string="Date",required=True,readonly=True, default=fields.Date.context_today)
    periode_id = fields.Many2one('account.period', required=True, string='Periode')
    state= fields.Selection(STATE_SELECTION, string='State', readonly=True,default='draft')
    move_consol_ids = fields.Many2many('account.move.line.consol', 'move_consol_elim_rel', 'consol_line_id', 'elim_id', 'Journal Consolidation')
    move_id = fields.Many2one('account.move.consol', string='Account Entry', copy=False)
    move_ids = fields.One2many('account.move.line.consol',related='move_id.line_id',string='Journal Elimination', readonly=True)
    confirm_uid = fields.Many2one('res.users',string="Confirmed by")
    confirm_date = fields.Datetime('Confirmed on')
    approval_ids = fields.One2many('dym.approval.line','transaction_id',string="Table Approval",domain=[('form_id','=',_name)])
    approval_state =  fields.Selection([
        ('b','Belum Request'),
        ('rf','Request For Approval'),
        ('a','Approved'),
        ('r','Reject')
    ],'Approval State', readonly=True,default='b')
    filename = fields.Char('Filename') 
    datafile = fields.Binary('Data File')
    move_diff_ids = fields.One2many('account.move.line.consol','elimination_id','Different Sale Journals')
    
    @api.onchange('periode_id')
    def fill_consol(self):
        domain = {}
        if self.periode_id:
            if self.periode_id.state == 'done':
                self.move_consol_ids = False
                raise osv.except_osv(('Perhatian !'), ("Period: %s sudah di close")%(self.periode_id.name))  
            company = self.get_group_company()
            period = self.periode_id
            date_start = datetime.strptime(period.date_start, DEFAULT_SERVER_DATE_FORMAT).strftime(DEFAULT_SERVER_DATE_FORMAT)
            date_stop = datetime.strptime(period.date_stop, DEFAULT_SERVER_DATE_FORMAT).strftime(DEFAULT_SERVER_DATE_FORMAT)  
            branch_period_ids = period.search([('company_id','!=',company.id),('date_start','=',period.date_start),('date_stop','=',period.date_stop)])
            branch_unconsolidated_ids = []
            if branch_period_ids:
                request = ("SELECT lx.branch_id as branch_id FROM account_move_line lx left join account_move mx on lx.move_id = mx.id left join account_period ax on mx.period_id = ax.id WHERE ax.id in %s and (lx.consolidate_posted = 'f' or  lx.consolidate_posted is null) and mx.state = 'posted' and lx.branch_id is not null group by lx.branch_id")
                params = (tuple(branch_period_ids.ids),)
                self._cr.execute(request, params)
                rows = self._cr.dictfetchall()
                branch_unconsolidated_ids = [row['branch_id'] for row in rows]

            # if branch_unconsolidated_ids:
            #     branch_unconsolidated = self.env['dym.branch'].browse(branch_unconsolidated_ids)
            #     self.move_consol_ids = False
            #     raise osv.except_osv(('Perhatian !'), ("Period: %s branch: %s belum di consolidate")%(period.name,', '.join(branch_unconsolidated.mapped('name')))) 

            # request = ("SELECT l.id as line_id FROM account_move_line_consol l left join account_move_consol m on l.move_id = m.id left join account_period a on m.period_id = a.id left join account_move_line lx on l.consolidation_move_line_id = lx.id WHERE lx.move_id in (select ly.move_id from account_move_line_consol lz left join res_partner p on p.id = lz.partner_id left join account_move_line ly on ly.id = lz.consolidation_move_line_id left join account_move_consol mz on mz.id = lz.move_id where p.partner_type = 'Konsolidasi' and lz.period_id = %s and (lz.eliminate_posted = 'f' or lz.eliminate_posted is null) and mz.state = 'posted' and lz.elimination_move_line_id is null) and a.id = %s and (l.eliminate_posted = 'f' or l.eliminate_posted is null) and m.state = 'posted' and l.elimination_move_line_id is null order by lx.move_id")
            where_account = " l.account_id in %s" % str(tuple([x.account_id.id for x in self.periode_id.company_id.account_elimination_line]))
            where_period = " l.period_id = %s" % str(self.periode_id.id)
            where_journal_type = " jx.type in ('cash','bank')"
            where_journal_jual = " jx.type in ('sale','sale_refund','purchase','purchase_refund')"
            contain = "intercompany"
            request = ("""SELECT l.id as line_id FROM account_move_line_consol l
                        left join account_move_line lx on l.consolidation_move_line_id = lx.id
                        left join account_journal jx on lx.journal_id = jx.id
                        WHERE %s  AND ((%s AND %s) OR (%s AND %s AND jx.name like '%%%%%s%%%%'))""" % (where_period,where_account,where_journal_type,where_account,where_journal_jual,contain)) 
            
            params = ((self.periode_id.id),(self.periode_id.id),)
            self._cr.execute(request, params)
            rows = self._cr.dictfetchall()
            line_ids = [row['line_id'] for row in rows]
            if not line_ids:
                self.move_consol_ids = False
                raise osv.except_osv(('Perhatian !'), ("Period: %s tidak ditemukan transaksi intercompany untuk dieliminasi")%(period.name)) 
            domain['move_consol_ids'] = [('id','in',line_ids)]
        else:
            self.move_consol_ids = False
            domain['move_consol_ids'] = [('id','=',0)]
        return {'domain':domain}

    @api.model
    def create(self,vals,context=None):
        vals['name'] = self.env['ir.sequence'].get_per_branch(vals['branch_id'], 'JEL', division=False) 
        vals['date'] = datetime.today() 
        res =  super(dym_journal_elimination, self).create(vals)  
        return res

    @api.multi
    def write(self,values,context=None):
        res =  super(dym_journal_elimination,self).write(values)
        return res

    @api.multi
    def generate_elimination(self):
        self.action_create_move_line_eliminate()
        if self.move_diff_ids:
            move = False
            for line in self.move_diff_ids:
                move = line.move_id
                line.write({'move_id':self.move_ids[0].move_id.id})
            move.unlink()

    @api.multi
    def action_create_move_line_eliminate(self):
        move_pool = self.env['account.move.consol']
        move_line_pool = self.env['account.move.line.consol']
        period_obj = self.env['account.period']
        company = self.get_group_company()
        journal_id = company.journal_eliminate_multi_company_id.id 
        if not company.journal_eliminate_multi_company_id:
            raise osv.except_osv(('Perhatian !'), ("Journal eliminasi multi company belum diisi di %s!")%(company.name)) 
        if self.periode_id.company_id != company:
            raise osv.except_osv(('Perhatian !'), ("Period yang diisi harus periode grup company")) 
        if self.periode_id.state == 'done':
            raise osv.except_osv(('Perhatian !'), ("Period: %s sudah di close")%(self.periode_id.state.name))  
        name = self.name
        date = time.strftime('%Y-%m-%d %H:%M:%S')
        partner_consol = self.move_consol_ids.mapped('partner_id').filtered(lambda r: r.partner_type != 'Konsolidasi')
        if partner_consol:
            raise osv.except_osv(_('Error!'), _('Partner %s bukan partner konsolidasi!.')%(', '.join(partner_consol.mapped('name'))))
        elim_posted = self.move_consol_ids.filtered(lambda r: r.eliminate_posted == True)
        if elim_posted:
            raise osv.except_osv(_('Error!'), _('Jurnal %s sudah di eliminasi!.')%(', '.join(elim_posted.mapped('consolidation_move_line_id.move_id.name'))))
        rows = self.move_consol_ids.read(['move_id', 'id',  'name',  'ref', 'account_id', 'credit', 'debit',  'branch_id',  'division', 'currency_id', 'product_id', 'product_uom_id', 'amount_currency', 'quantity', 'company_id', 'partner_id', 'analytic_account_id', 'tax_code_id', 'tax_amount'])
        eliminate_line = []
        eliminate_move_ids = []
        eliminate_move_line_ids = []
        for row in rows:
            row['analytic_account_id'] = row['analytic_account_id'][0] if row['analytic_account_id'] else False
            row['branch_id'] = row['branch_id'][0] if row['branch_id'] else False
            row['partner_id'] = row['partner_id'][0] if row['partner_id'] else False
            row['tax_code_id'] = row['tax_code_id'][0] if row['tax_code_id'] else False
            row['currency_id'] = row['currency_id'][0] if row['currency_id'] else False
            row['product_id'] = row['product_id'][0] if row['product_id'] else False
            row['move_id'] = row['move_id'][0] if row['move_id'] else False
            row['account_id'] = row['account_id'][0] if row['account_id'] else False
            row['product_uom_id'] = row['product_uom_id'][0] if row['product_uom_id'] else False
            row['company_id'] = row['company_id'][0] if row['company_id'] else False
            debit = row['debit']
            credit = row['credit']
            row['credit'] = debit
            row['debit'] = credit
            if row['move_id'] not in eliminate_move_ids:
                eliminate_move_ids.append(row['move_id'])
            if row['id'] not in eliminate_move_line_ids:
                eliminate_move_line_ids.append(row['id'])
            row['elimination_move_line_id'] = row['id']
            row['period_id'] = self.periode_id.id
            row['date'] = date
            move_id = row['move_id']
            row_id = row['id']
            del row['id']
            del row['move_id']
            row['eliminated'] = True

            eliminate_line.append([0,False,row])
        if not eliminate_line:
            raise osv.except_osv(('Perhatian !'), ("Period: %s, tidak ditemukan jurnal entry yang akan dieliminasi")%(self.periode_id.name))
        move = {
            'name': name,
            'ref': name,
            'journal_id': journal_id,
            'date': date,
            'period_id':self.periode_id.id,
            'line_id':eliminate_line,
        }
        move_id = move_pool.create(move)
        move_line_pool.browse(eliminate_move_line_ids).with_context(bypass_check=True).write({'eliminated':True})
        if company.journal_eliminate_multi_company_id.entry_posted:
            posted = move_id.post()
        self.write({'state': 'confirm', 'move_id': move_id.id})
        return True

    @api.multi
    def wkf_request_approval(self):
        if not self.move_consol_ids:
            raise osv.except_osv(('Perhatian !'), ("Period: %s, tidak ditemukan jurnal entry yang akan dieliminasi")%(self.periode_id.name))
        total_debit = sum(line.credit for line in self.move_consol_ids)  
        total_credit = sum(line.debit for line in self.move_consol_ids) 
        if total_debit != total_credit:
            raise osv.except_osv(('Perhatian !'), ("Hasil eliminasi tidak balance! mohon di cek kembali"))
        obj_matrix = self.env["dym.approval.matrixbiaya"]
        obj_matrix.request_by_value(self, 0)

        self.state =  'waiting_for_approval'
        self.approval_state = 'rf'
        company = self.get_group_company()
        if not company.journal_eliminate_multi_company_id:
            raise osv.except_osv(('Perhatian !'), ("Journal eliminasi multi company belum diisi di %s!")%(company.name)) 
                
    @api.multi      
    def wkf_approval(self):       
        approval_sts = self.env['dym.approval.matrixbiaya'].approve(self)
        if approval_sts == 1:
            self.write({'date':datetime.today(),'approval_state':'a','confirm_uid':self._uid,'confirm_date':datetime.now()})
            self.action_create_move_line_eliminate()
        elif approval_sts == 0:
                raise osv.except_osv(('Perhatian !'), ("User tidak termasuk group Approval"))    
            
    @api.multi
    def has_approved(self):
        if self.approval_state == 'a':
            return True
        return False
    
    @api.multi
    def has_rejected(self):
        if self.approval_state == 'r':
            self.write({'state':'draft'})
            return True
        return False
    
    @api.one
    def wkf_set_to_draft(self):
        self.write({'state':'draft','approval_state':'r'})
                            
    @api.cr_uid_ids_context
    def unlink(self, cr, uid, ids, context=None):
        for item in self.browse(cr, uid, ids, context=context):
            if item.state != 'draft':
                raise osv.except_osv(('Perhatian !'), ("Journal Eliminasi tidak bisa didelete !"))
        return super(dym_journal_elimination, self).unlink(cr, uid, ids, context=context) 

    @api.multi
    def eksport_excel(self):
        data = []
        book = xlwt.Workbook()
        sheet = book.add_sheet("Selisih Penjualan")
        sheet2 = book.add_sheet("Total Selisih Penjualan")
        now = datetime.now()
        style = xlwt.easyxf('font: bold 1;')
        style_header = xlwt.easyxf('font: bold 1, name Calibri, height 210; pattern: pattern solid, fore_colour yellow;')

        debit_credit = {}
        header = ['Transaction', 'Ref Intercompany', 'Date','Branch'] 
        account_ids = [x for x in self.periode_id.company_id.account_fields_report_line]
        for account in account_ids:
            header.append(account.account_id.name)
            debit_credit[account.account_id.name] = account.credit
        header.append('Diff Amount')
        header.append('Bisnis Unit')
        data_dict = {}
        no = 0
        branch = {}
        for line in self.move_consol_ids:
            if line.account_id.name in header:
                data_dict[line.account_id.name] = line.debit or line.credit
                # no += 1
                intercom_ref = line._get_intercom_ref_id()
                bu = str(line.analytic_2.code)+' '+str(line.analytic_2.name)
                data.append({
                        # 'No': no,
                        'Transaction': line.consol_entry.name,
                        'Ref Intercompany': intercom_ref or self.intercom_ref or '',
                        'Date': line.consol_entry.date,
                        'Branch': line.branch_id.name,
                        line.account_id.name: data_dict[line.account_id.name],
                        'Diff Amount': (data_dict[line.account_id.name] * -1) if debit_credit[line.account_id.name] == True else data_dict[line.account_id.name],
                        'Bisnis Unit': bu,
                        'branch_id': line.branch_id.id,
                        'division': line.division,
                        'account_id': line.account_id.id,
                        'journal_id': line.company_id.journal_eliminate_multi_company_id.id,
                        'company_id': line.company_id.id,
                        'analytic_account_id': line.analytic_account_id.id,
                        'period_id': line.period_id.id,
                        })

                if line.branch_id.name+'#'+str(bu) not in branch:
                    branch[line.branch_id.name+'#'+str(bu)] = (data_dict[line.account_id.name] * -1) if debit_credit[line.account_id.name] == True else data_dict[line.account_id.name]
                else:
                    branch[line.branch_id.name+'#'+str(bu)] += (data_dict[line.account_id.name] * -1) if debit_credit[line.account_id.name] == True else data_dict[line.account_id.name]
                    
                
        trans_list = []
        uniq_list = []
        debit = 0
        credit = 0
        for d in data:
            if d['Transaction'] not in trans_list:   
                uniq_list.append(d)
                trans_list.append(d['Transaction'])
            else:
                for a in account_ids:
                    for datas in uniq_list:
                        if datas['Transaction'] == d['Transaction']:
                            if a.account_id.name in d:
                                if a.account_id.name not in datas:
                                    uniq_list[uniq_list.index(datas)][a.account_id.name] = d[a.account_id.name]
                                else:
                                    uniq_list[uniq_list.index(datas)][a.account_id.name] += d[a.account_id.name]
                                    
                                if debit_credit[a.account_id.name] == True:
                                    uniq_list[uniq_list.index(datas)]['Diff Amount'] -= d[a.account_id.name]                                      
                                else:
                                    uniq_list[uniq_list.index(datas)]['Diff Amount'] += d[a.account_id.name]

        obj_amlc = self.env['account.move.line.consol']
        obj_amc = self.env['account.move.consol']

        if not self.move_diff_ids:
            amc = obj_amc.create({
                        'journal_id':uniq_list[0]['journal_id'],
                        'period_id':uniq_list[0]['period_id'],
                        })
            for line in uniq_list:
                if line['Diff Amount'] != 0:
                    if not self.periode_id.company_id.account_elimination_diff_id:
                        raise osv.except_osv(('Perhatian !'), ("Account Elimination Diff. belum dilengkapi di Company"))       
                    else:
                        acc_elim_diff = self.periode_id.company_id.account_elimination_diff_id.id
                        obj_amlc.create({
                        'move_id': amc.id,
                        'analytic_account_id': line['analytic_account_id'],
                        'branch_id': line['branch_id'],
                        'division': line['division'],
                        'name': line['Transaction'],
                        'journal_id': line['journal_id'],                
                        'account_id': acc_elim_diff,
                        'company_id': line['company_id'],
                        'debit': line['Diff Amount'] * -1 if line['Diff Amount'] < 0 else 0,
                        'credit': line['Diff Amount'] if line['Diff Amount'] > 0 else 0,
                        'elimination_id': self.id,
                        'period_id': self.periode_id.id,
                        'date': self.create_date,                

                            }) 

        branch_list = []
        for b,x in branch.items():
            branch_list.append({
                    'Branch': b.split('#')[0],
                    'Amount': x,
                    'Bisnis Unit': b.split('#')[1]
            })


        uniq_list=sorted(uniq_list,key=lambda x: (x['Ref Intercompany'],x['Transaction']))

        no = 0; 
        for line in uniq_list:
            no += 1
            col = -1
            for i in header:
                col += 1
                if i in line:
                    sheet.write(no, col, line[i])

        colh = -1
        for x in header:
            colh += 1 
            sheet.write(0, colh, x)

        no = 0; 
        for line in branch_list:
            no += 1
            col = -1
            for i in ['Branch','Amount','Bisnis Unit']:
                col += 1
                if i in line:
                    sheet2.write(no, col, line[i])

        colh = -1
        for x in ['Branch','Amount','Bisnis Unit']:
            colh += 1 
            sheet2.write(0, colh, x)



        filename = 'Elimination_Report_on_%s.xls' % (now.strftime("%Y-%m-%d %H:%M:%S"))        
        file_data = StringIO.StringIO()
        book.save(file_data)
        out = base64.encodestring(file_data.getvalue())
        self.write({'datafile':out,'filename': filename})

        return True
예제 #24
0
class sync_morsa_hr(models.Model):
    _name = 'sync.morsa.hr'

    def _get_enterprise_used(self):
        sesion = Session()
        informacion = sesion.get_session_info()
        bd = informacion.get('db')

        return bd[0:3]

    def _get_current_period(self):
        cMonth = str(datetime.now().month).rjust(2, "0")
        cYear = str(datetime.now().year)
        period = ''
        obj_period = self.env['account.period'].search([
            ('code', '=', cMonth + "/" + cYear)
        ])
        if obj_period:
            period = obj_period.id

        return period

    def _get_default_journal(self, journaldef='GTONOM'):
        journal = self.env['account.journal'].search([('code', '=', journaldef)
                                                      ])
        return journal.id

    period = fields.Char('Period', size=6, help='mmaaaa')
    period2 = fields.Many2one(
        'account.period',
        'Periodo',
        default=lambda self: self._get_current_period(),
        domain=[('state', '=', 'draft'), ('special', '=', False)],
        required=True,
    )

    enterprise = fields.Char(
        'Empresa',
        default=lambda self: self._get_enterprise_used(),
        help=
        'Write the code for enterprise \nGMM: contpaq_openerp_morsa_gmm \nMOR: contpaq_openerp_morsa_mor \nVOH: contpaq_openerp_morsa_voh\n Example: GMM'
    )

    journal = fields.Many2one(
        'account.journal',
        'Diario',
        default=lambda self: self._get_default_journal(),
        help='Diario asignado',
        #domain=[('type', 'in', ['purchase', 'general'])],
        required=True,
    )
    file_zip = fields.Binary(
        'Archivo Zip/Texto',
        help="Zip para archivos de Nomina/SUA. Texto para Pólizas en general")

    checkbox = fields.Boolean('SUA')
    polizanormal = fields.Boolean('Poliza Normal de ContPAQ')

    @api.onchange('polizanormal')
    def onchange_polizanormal(self):
        journal = ''
        if not self.polizanormal:
            journalcode = 'GTONOM' if not self.checkbox else 'GTOSUA'
            journal = self._get_default_journal(journalcode)

        self.journal = journal
        return {}

    @api.multi
    def action_sync_hr(self):
        #obj_hr = self.pool['sync.morsa.hr'].browse(cr, uid, ids[0], context=context)
        # bdname = ''
        period = ''
        #get values

        dbname = self.enterprise.upper()
        period = self.period2.code
        _logger.debug("DB: %s" % dbname)
        if dbname not in ENTERPRISE:
            raise osv.except_osv(_("Sym GMM"),
                                 _("write a enterprise correct."))

        dbname = ENTERPRISE[dbname]
        conexion = self.env['sync.morsa.conexion']._get_conexion(
            "conexion_openerp.csv", dbname)
        cursor = conexion.cursor()
        """
		@save_path = ruta donde se guardara el archivo leido desde el campo binario en la aplicacion ODOO
		@extracth_path = ruta donde se van a extraer los archivos de la ruta @save_path ya que se genera un archivo .zip
						 en esta ultima ruta, la variable @extracth_path se utilizara tambien para cuando
						 acabe el proceso de lectura de los archivos, al final borre los archivos del
						 directorio establecido en esta variable
		"""
        save_path = '/home/morsadmin/nomina_txt.zip'
        extract_path = '/home/morsadmin/archivos_extraidos/'
        if self.polizanormal:
            save_path = '/home/morsadmin/poliza_contpaq.txt'
            extract_path = '/home/morsadmin/'
        """
        Proceso de borrado de los archivos que se guardaron en la ruta establecida de la variable @extracth_p$
        para que no cause conflictos con los nuevos archivos que se generaran cada vez que se corra el proceso
        """
        file_list = os.listdir(extract_path)
        if file_list:
            for item in file_list:
                try:
                    os.remove(os.path.join(extract_path, item))
                except Exception as err:
                    if err.errno == 21:
                        pass
                    else:
                        raise

        file = self.file_zip
        decoding_file = base64.decodestring(file)
        archive = open(save_path, 'wb')
        archive.write(decoding_file)
        archive.close()
        notes = ''
        aml_name = ''
        if self.polizanormal:
            notes = 'linea[28:129].strip()'
            aml_name = "self.journal.code + '-' + linea[23:34].strip()"
        else:
            zip_ref = zipfile.ZipFile(save_path, 'r')
            zip_ref.extractall(extract_path)
            zip_ref.close()
            aml_name = "linea[2:11] + '-' + linea[73:89].strip()"
        """
		@path donde se leeran todos los archivos TXT sacados del archivo .zip que se guarda en la variable
		@save_path
		"""
        path = extract_path + '*.txt'
        # """
        #    Se usa el modulo glob para poder leer todos los archivos TXT
        #    en una carpeta, para poder utilizar esta libreria se tiene que instalar el modulo glob en la instancia virtual
        #    (sudo pip install glob2 para python 2.x y sudo pip install glob3 para python 3.x)
        #    y despues importarla en la clase como se muestra arriba
        #    La funcion glob inserta la ruta completa con el nombre de cada archivo al final en un arreglo
        #    cada ruta es un elemento en el arreglo
        #    @files_txt = variable que se le asigna el arreglo de los archivos recorridos en la ruta establecida
        # """
        files_txt = glob.glob(path)

        if files_txt:
            pass
        else:
            path = extract_path + '*.TXT'
            files_txt = glob.glob(path)
        """
			Se declaran las instancias de los objetos que utilizaremos
		"""
        account_move_obj = self.env['account.move']
        account_move_line_obj = self.env['account.move.line']
        account_period_obj = self.period2
        acc_journal = self.journal

        for file in files_txt:
            with open(file, 'r') as archivo:
                numlin = 0
                polizaref = ''
                try:
                    for linea in archivo.readlines():
                        numlin += 1
                        if linea.strip():
                            #print "Archivo: %s, #Linea: %s, Tipo: %s, Poliza: %s, Movto: %s" % ( file, numlin,
                            #			linea[0:1], polizaref if polizaref else linea[13:21], linea[2:11] + '-' + linea[73:89].strip())
                            if 'P' in linea[0:1]:
                                period_id = account_period_obj.id
                                polizaref = linea[13:21].strip()
                                # query_2 = ("select fn_get_journal_id_hr('%s','%s')"%(linea[13:21], linea[11:12]))
                                # cursor.execute(query_2)
                                # reg_1 = cursor.fetchall()
                                date = linea[2:6] + '/' + linea[
                                    6:8] + '/' + linea[8:10].strip()
                                header = {
                                    'date': date,
                                    'journal_id': acc_journal.id,
                                    'ref': polizaref,
                                    'company_id': COMPANY_ID_MOR,
                                    'period_id': period_id,
                                    'narration': eval(notes) if notes else '',
                                }
                                obj_policy = account_move_obj.create(header)
                                #print "Leyendo: ", linea[13:21]
                            elif 'M' in linea[0:1]:
                                cuenta = linea[2:5] + '-' + linea[
                                    5:7] + '-' + linea[7:10] + '-' + linea[
                                        10:12].strip()
                                query_3 = SQLSCOR + " where s.c_contpaq = '%s'" % cuenta
                                cursor.execute(query_3)
                                reg_2 = cursor.fetchall()
                                if '1' in linea[34:35]:
                                    debit = float(linea[36:52])
                                    credit = 0
                                    #si debito viene negativo es un credito
                                    if debit < 0:
                                        credit = debit * -1
                                        debit = 0
                                    # update_detalle = {
                                    #     'name': eval(aml_name), #linea[2:11]+'-'+linea[73:89].strip(),
                                    #     'partner_id': reg_2[0][1],
                                    #     'account_id': reg_2[0][3],
                                    #     'analytic_account_id': reg_2[0][4],
                                    #     'operating_unit_id': reg_2[0][2],
                                    #     'debit': debit,
                                    #     'credit': credit,
                                    #     'move_id': obj_policy.id
                                    # }
                                    #obj_line = account_move_line_obj.create(update_detalle)
                                elif '2' in linea[34:35]:
                                    #Si credito viene en negativo es un debito
                                    credit = float(linea[36:52])
                                    debit = 0
                                    if credit < 0:
                                        debit = credit * -1
                                        credit = 0
                                update_detalle = {
                                    'name': eval(
                                        aml_name
                                    ),  #linea[2:11]+'-'+linea[73:89].strip(),
                                    'partner_id': reg_2[0][1],
                                    'account_id': reg_2[0][3],
                                    'analytic_account_id': reg_2[0][4],
                                    'operating_unit_id': reg_2[0][2],
                                    'debit': debit,
                                    'credit': credit,
                                    'move_id': obj_policy.id
                                }
                                obj_line = account_move_line_obj.create(
                                    update_detalle)
                except Exception as e:
                    raise UserError(
                        "Error procesando Polizas",
                        "Archivo: %s, #Linea: %s, Tipo: %s, Poliza: %s, Movto: %s. \n\nERROR: %s"
                        % (file, numlin, linea[0:1], polizaref,
                           linea[2:11] + '-' + linea[73:89].strip(), e))

    #Metodo que aplica la logica para los archivos de nomina SUA de MORSA
    @api.multi
    def action_sync_hr_usus(self):

        dbname = self.enterprise.upper()
        period = self.period2.code
        _logger.debug("DB: %s" % dbname)
        if dbname not in ENTERPRISE:
            raise osv.except_osv(_("Sym GMM"),
                                 _("write a enterprise correct."))
        # get db
        dbname = ENTERPRISE[dbname]
        #get conexion
        conexion = self.env['sync.morsa.conexion']._get_conexion(
            "conexion_openerp.csv", dbname)
        #conexion = self.pool.get('sync.morsa.conexion')._get_conexion("conexion_openerp.csv", dbname)
        cursor = conexion.cursor()
        """
        @save_path = ruta donde se guardara el archivo leido desde el campo binario en la aplicacion ODOO
        @extracth_path = ruta donde se van a extraer los archivos de la ruta @save_path ya que se genera un archivo .zip
                        en esta ultima ruta, la variable @extracth_path se utilizara tambien para cuanddo
                        acabe el proceso de lectura de los archivos, al final borre los archivos del
                        directorio establecido en esta variable
        """
        save_path = '/home/morsadmin/nomina_txt_sua.zip'
        extract_path = '/home/morsadmin/archivos_extraidos/'
        """
        Proceso de borrado de los archivos que se guardaron en la ruta establecida de la variable @extracth_p$
        para que no cause conflictos con los nuevos archivos que se generaran cada vez que se corra el proceso
        """
        file_list = os.listdir(extract_path)
        if file_list:
            for item in file_list:
                os.remove(os.path.join(extract_path, item))

        file = self.file_zip
        decoding_file = base64.decodestring(file)
        archive = open(save_path, 'wb')
        archive.write(decoding_file)
        archive.close()
        zip_ref = zipfile.ZipFile(save_path, 'r')
        zip_ref.extractall(extract_path)
        zip_ref.close()
        """
        @path donde se leeran todos los archivos TXT sacados del archivo .zip que se guarda en la variable
        @save_path
        """
        path = '/home/morsadmin/archivos_extraidos/*.txt'
        """Se usa el modulo glob para poder leer todos los archivos TXT
            en una carpeta, para poder utilizar esta libreria se tiene que instalar el modulo glob en la instancia virtual
            y despues importarla en la clase como se muestra arriba
            La funcion glob inserta la ruta completa con el nombre de cada archivo al final en un arreglo
            cada ruta es un elemento en el arreglo
            @files_txt = variable que se le asigna el arreglo de los archivos recorridos en la ruta establecida
        """
        files_txt = glob.glob(path)
        if files_txt:
            pass
        else:
            path = '/home/morsadmin/archivos_extraidos/*.TXT'
            files_txt = glob.glob(path)
        """
        Se declaran las instancias de los objetos que utilizaremos
        """

        account_move_obj = self.env['account.move']
        account_move_line_obj = self.env['account.move.line']
        account_period_obj = self.period2
        acc_journal = self.journal
        #self.env['account.journal'].search([('code', '=', 'GTOSUA')])
        for file in files_txt:
            with open(file, 'r') as archivo:
                numlin = 0
                polizaref = ''
                try:
                    for linea in archivo.readlines():
                        numlin += 1
                        if linea.strip():
                            #print "Archivo: %s, #Linea: %s, Tipo: %s, Poliza: %s, Movto: %s" % ( file, numlin,
                            #			linea[0:1], polizaref if polizaref else linea[13:21], linea[2:11] + '-' + linea[73:89].strip())
                            if 'P' in linea[0:1]:
                                #query_2 = ("select fn_get_journal_id_hr('%s','%s')"%(linea[13:21], linea[11:12]))
                                #cursor.execute(query_2)
                                #reg_1 = cursor.fetchall()
                                date = linea[2:6] + '/' + linea[
                                    6:8] + '/' + linea[8:10].strip()
                                period_id = account_period_obj.id
                                polizaref = linea[13:21]
                                header = {
                                    'date': date,
                                    'journal_id': acc_journal.id,
                                    'ref': polizaref,
                                    'company_id': COMPANY_ID_MOR,
                                    'period_id': period_id
                                }
                                obj_policy = account_move_obj.create(header)
                            elif 'M' in linea[0:1]:
                                operating_unit = ''
                                credit = 0
                                debit = 0
                                cuenta = linea[2:5] + '-' + linea[
                                    5:7] + '-' + linea[7:10] + '-' + linea[
                                        10:12].strip()
                                if '6' in linea[2:3]:
                                    query_3 = (
                                        "select s.id_ou from sync_contpaq_openerp_rel s where s.c_contpaq = '%s'"
                                        % (cuenta))
                                    cursor.execute(query_3)
                                    reg_2 = cursor.fetchall()
                                    operating_unit = reg_2[0][0]
                                query_4 = (
                                    "select s.c_contpaq,s.id_partner,s.id_ou,s.id_open,s.id_ananew from sync_contpaq_openerp_rel s where s.c_contpaq = '%s'"
                                    % (cuenta))
                                cursor.execute(query_4)
                                reg_3 = cursor.fetchall()
                                if '1' in linea[34:35]:
                                    debit = float(linea[36:52])
                                    #Si debito viene en negativo es un credito
                                    if debit < 0:
                                        credit = debit * -1
                                        debit = 0
                                    # update_detalle = {
                                    #     'name': linea[2:12]+'-'+linea[73:89].strip(),
                                    #     'partner_id': reg_3[0][1],
                                    #     'account_id': reg_3[0][3],
                                    #     'analytic_account_id': reg_3[0][4],
                                    #     'operating_unit_id': operating_unit,
                                    #     'debit': debit,
                                    #     'credit': credit,
                                    #     'move_id': obj_policy.id
                                    # }
                                    # obj_line = account_move_line_obj.create(update_detalle)
                                elif '2' in linea[34:35]:
                                    credit = float(linea[36:52])
                                    #Si credito viene en negativo es un debito
                                    if credit < 0:
                                        debit = credit * -1
                                        credit = 0
                                update_detalle = {
                                    'name':
                                    linea[2:11] + '-' + linea[73:89].strip(),
                                    'partner_id':
                                    reg_3[0][1],
                                    'account_id':
                                    reg_3[0][3],
                                    'analytic_account_id':
                                    reg_3[0][4],
                                    'operating_unit_id':
                                    operating_unit,
                                    'debit':
                                    debit,
                                    'credit':
                                    credit,
                                    'move_id':
                                    obj_policy.id
                                }
                                obj_line = account_move_line_obj.create(
                                    update_detalle)
                except Exception as e:
                    raise UserError(
                        "Error procesando Polizas",
                        "Archivo: %s, #Linea: %s, Tipo: %s, Poliza: %s, Movto: %s. \n\nERROR: %s"
                        % (file, numlin, linea[0:1], polizaref,
                           linea[2:11] + '-' + linea[73:89].strip(), e))
예제 #25
0
class Reporte_cobros(models.Model):
    _inherit = "pagos.automaticos"

    filename = fields.Char(string="Nombre de archivo")
    archivo_xls = fields.Binary(string='Archivo Excel')
    filename_pdf = fields.Char(string="Nombre de archivo")
    archivo_pdf = fields.Binary(string='Archivo PDF')

    #----------------------------------------------------------
    #                     Obtencion de datos                  -
    #----------------------------------------------------------
    @api.multi
    def consultar(self):
        lista_datos = []
        for l in self.pagos_line:
            for f in l.factura_id:
                lista_pagos = [value.ref for value in f.payment_ids]
                cont_num = ''
                lis = 0.0
                for n in lista_pagos:
                    lis = lis + 1
                    if lis < len(lista_pagos):
                        cont_num = cont_num + n + ','
                    else:
                        cont_num = cont_num + n
                obser = ''
                for d in f.invoice_line:
                    obser = obser + d.name

                dic = {
                    'tipo': f.journal_id.tipo_reporte,
                    #INTEGRACION: SE CAMBIA POR PEDIDO DE CAMBIO DE NUMERO
                    #'numero_factura':f.number,
                    'numero_factura': f.numerofac,
                    'alumno': f.alumno_id.name,
                    'codigo_alumno': f.alumno_id.codigo_alumno,
                    'observacion': obser,
                    'valor': f.amount_total,
                    'numero_pago': cont_num,
                    'jornada': f.jornada_id.codigo,
                    'curso': f.curso_id.name,
                    'paralelo': f.paralelo_id.codigo,
                    'fecha_factura': f.date_invoice
                }
                lista_datos.append(dic)

        datos = {
            'lista': lista_datos,
            'cant': len(self.pagos_line),
        }

        return datos

#-------------------------------------------------------------------------------------------------------------------
#                     CREACION DE EXCEL                                                                            -
#-------------------------------------------------------------------------------------------------------------------

    @api.multi
    def generar_excel(self):
        fp = io.BytesIO()
        workbook = self.crear_excel_info()
        workbook.save(fp)
        self.filename = 'Informe.xlsx'
        self.archivo_xls = base64.b64encode(fp.getvalue())
        return True

    def crear_excel_info(self):
        wb = crear_informe_cobros_automaticos_excel.crear_wb_informe()
        self.crear_informe(wb)
        return wb

    def crear_informe(self, wb):
        fecha_a = datetime.strptime(self.fecha_emision, '%Y-%m-%d')
        fecha_actual = datetime.strftime(fecha_a, '%d/%b/%Y')
        dic = {
            'fecha_desde': self.fecha_desde,
            'fecha_hasta': self.fecha_hasta,
            'usuario_id': self.usuario_id.name,
            'fecha_corte': fecha_actual,
            'company_id': self.usuario_id.company_id.name,
        }

        lista_alumnos = []
        cant_alumno = 0
        datos = self.consultar()
        lista_datos = datos['lista']
        cant_datos = datos['cant']
        filtro = datos['filtro']
        filtro1 = datos['filtro1']

        sheet_info = crear_informe_cobros_automaticos_excel.crea_hoja_info(
            wb, 'Informe ', 0)
        sheet_view = openpyxl.worksheet.SheetView()
        sheet_view.zoomScale = "130"
        sheet_view.zoomScaleNormal = "130"
        sheet_info.sheet_view = sheet_view
        sheet_info.zoomScale = "130"
        crear_informe_cobros_automaticos_excel.Informe(sheet_info, dic,
                                                       lista_datos)

#-------------------------------------------------------------------------------------------------------------------
#                     CREACION DE PDF                                                                              -
#-------------------------------------------------------------------------------------------------------------------

    @api.multi
    def generar_pdf(self):
        filename_pdf = ''
        filename_pdf = ''
        fp = io.BytesIO()
        workbook = self.crear_excel_info_pdf()
        workbook.save(fp)
        filename_pdf = 'Informe.xlsx'
        archivo_pdf = base64.b64encode(fp.getvalue())
        obj = self.env['ir.attachment']
        obj_xls = obj.create({
            'res_model': self.id,
            'name': filename_pdf,
            'datas': archivo_pdf,
            'type': 'binary',
            'datas_fname': filename_pdf
        })
        direccion_xls = obj._get_path(obj_xls.datas)[1]
        direccion = obj._get_path(obj_xls.datas)[0]
        nombre_bin = obj_xls.store_fname
        nombre_archivo = obj_xls.datas_fname
        separa = direccion_xls.rstrip(direccion)
        os.chdir(separa)
        os.rename(nombre_bin, nombre_archivo)
        commands.getoutput(
            """ libreoffice --headless --convert-to pdf *.xlsx""")
        with open(
                direccion_xls.rstrip(direccion) + '/' +
                nombre_archivo.split('.')[0] + '.pdf', "rb") as f:
            data = f.read()
            file = data.encode("base64")
        self.write({
            'filename_pdf': nombre_archivo.split('.')[0] + '.pdf',
            'archivo_pdf': file
        })
        os.rename(nombre_archivo, nombre_bin)
        obj_xls.unlink()

        return True

    def crear_excel_info_pdf(self):
        wb = crear_informe_cobros_automaticos_excel.crear_wb_informe()
        self.crear_informe_pdf(wb)
        return wb

    def crear_informe_pdf(self, wb):
        estado = ''
        if self.estado == '0':
            estado = 'Borrador'
        else:
            estado = 'Validado'
        now = datetime.now()
        # fecha_a = datetime.strptime(now, '%Y-%m-%d')
        # fecha_actual = datetime.strftime(fecha_a, '%d/%b/%Y')
        dic = {
            'codigo': self.banco_id.bank_bic,
            'banco': self.banco_id.bank_name,
            'met_pago': self.journal_id.name,
            'fecha_creacion': self.fecha_creacion,
            'cuenta_bancaria': self.cuenta_banco,
            'caja': self.account_journal_caja_id.name,
            'fecha_cobro': self.fecha_cobro,
            'estado': estado,
            'company_id': self.usuario_id.company_id.name,
            'usuario_id': self.usuario_id.name,
            'fecha_emision': now
        }

        lista_alumnos = []
        cant_alumno = 0
        datos = self.consultar()
        lista_datos = datos['lista']
        cant_datos = datos['cant']
        sheet_info = crear_informe_cobros_automaticos_excel.crea_hoja_info_pdf(
            wb, 'Informe ', 0)
        #sheet_info = crear_informe_cobranza_excel.crea_hoja_info(wb, 'Informe ',0)
        sheet_view = openpyxl.worksheet.SheetView()
        sheet_view.zoomScale = "70"
        sheet_view.zoomScaleNormal = "70"
        sheet_info.sheet_view = sheet_view
        sheet_info.zoomScale = "70"
        crear_informe_cobros_automaticos_excel.Informe_pdf(
            sheet_info, dic, lista_datos)
예제 #26
0
class ReporteCobranza(models.TransientModel):
    _name = "reporte.cobranza"
    _inherit = "reporte.utileria"
    _rec_name = 'jornada_id'

    fecha_desde = fields.Date(string="Fecha desde")
    fecha_hasta = fields.Date(string="Fecha hasta")
    jornada_id = fields.Many2one('jornada', 'Jornada', copy=False, index=True)
    seccion_id = fields.Many2one('seccion', 'Sección', copy=False, index=True)
    curso_id = fields.Many2one('curso', 'Curso', copy=False, index=True)
    paralelo_id = fields.Many2one('paralelo',
                                  'Paralelo',
                                  copy=False,
                                  index=True)
    # saldo = fields.Boolean(string="Presentar Saldo",default=False)
    # total = fields.Boolean(string="Presentar Total",default=False)
    # facturas_saldos = fields.Selection( (('S','SI'),
    #                            ('N','NO'),
    #                            ('T','TODAS')),default='T' ,string='Facturas con Saldos')
    #total_grupos = fields.Boolean(string="Total por grupos",default=False)
    journal_ids = fields.Many2many('account.journal', string='Diario')
    usuario_id = fields.Many2one('res.users',
                                 string="Usuario",
                                 default=lambda self: self.env.user,
                                 readonly=True)

    filename = fields.Char(string="Nombre de archivo")
    archivo_xls = fields.Binary(string='Archivo Excel')
    filename_pdf = fields.Char(string="Nombre de archivo")
    archivo_pdf = fields.Binary(string='Archivo PDF')
    tipo_reporte = fields.Selection(
        string='Tipo De Reporte',
        selection=[
            ('reporte_financiero', 'Informe Financiero'),
            ('reporte_gestion_cobranza', 'Informe Gestión Cobranzas'),
            ('reporte_tutor', 'Informe Tutor Sin Valores'),
            ('reporte_tutor_resumido', 'Informe Tutor Resumido'),
            ('reporte_alumno', 'Resumen Cuentas Por Cobrar'),
        ])

    _defaults = {
        'fecha_emision': fields.datetime.now(),
    }

    @api.onchange('jornada_id')
    def onchange_jornada(self):
        for l in self:
            if l.jornada_id:
                l.seccion_id = False
                l.curso_id = False
                l.paralelo_id = False

    @api.onchange('seccion_id')
    def onchange_seccion(self):
        for l in self:
            if l.seccion_id:
                l.curso_id = False
                l.paralelo_id = False

    @api.onchange('curso_id')
    def onchange_curso(self):
        for l in self:
            if l.curso_id:
                l.paralelo_id = False

    def strToDatetime(self, strdate):
        return datetime.strptime(strdate, DEFAULT_SERVER_DATE_FORMAT)

#----------------------------------------------------------
#                     Obtencion de datos                  -
#----------------------------------------------------------

    @api.multi
    def consultar(self):
        # lista_id=''
        # if self.journal_ids:
        #     for j in self.journal_ids:
        #         if lista_id!='':
        #             lista_id=lista_id+','+str(j.id)
        #         else:
        #             lista_id=str(j.id)
        # print(lista_id)

        model_invoice = self.env['account.invoice']
        cliente_id = "[('partner_id', '=', %s)]" % (
            self.cliente_id) if self.cliente_id else "[]"
        alumno_id = "[('alumno_id', '=', %s)]" % (
            self.alumno_id.id) if self.alumno_id else "[]"
        journal_ids = "[('journal_id', 'in', %s)]" % (
            self.journal_ids.ids) if self.journal_ids else "[]"

        invoice_ids = model_invoice.search([
            ('type', '=', 'out_invoice'),
        ] + safe_eval(cliente_id) + safe_eval(alumno_id) +
                                           safe_eval(journal_ids), )

        if 'T' == 'T':
            if self.jornada_id:
                if self.seccion_id:
                    if self.curso_id:
                        if self.paralelo_id:
                            self.env.cr.execute(
                                """SELECT id from account_invoice where date_invoice between '{0}' AND '{1}' and escuela=True and state in ('open','paid') and
                                    jornada_id={2} and seccion_id={3} and curso_id={4} and paralelo_id={5} and id in {6}"""
                                .format(self.fecha_desde, self.fecha_hasta,
                                        self.jornada_id.id, self.seccion_id.id,
                                        self.curso_id.id, self.paralelo_id.id,
                                        str(tuple(invoice_ids.ids))))
                            lista_facturas = self.env.cr.dictfetchall()
                        else:
                            self.env.cr.execute(
                                """SELECT id from account_invoice where date_invoice between '{0}' AND '{1}' and escuela=True and state in ('open','paid') and
                                    jornada_id={2} and seccion_id={3} and curso_id={4} and id in {5}"""
                                .format(self.fecha_desde, self.fecha_hasta,
                                        self.jornada_id.id, self.seccion_id.id,
                                        self.curso_id.id,
                                        str(tuple(invoice_ids.ids))))
                            lista_facturas = self.env.cr.dictfetchall()
                    else:
                        self.env.cr.execute(
                            """SELECT id from account_invoice where date_invoice between '{0}' AND '{1}' and escuela=True and state in ('open','paid') and
                                    jornada_id={2} and seccion_id={3} and id in {4}"""
                            .format(self.fecha_desde, self.fecha_hasta,
                                    self.jornada_id.id, self.seccion_id.id,
                                    str(tuple(invoice_ids.ids))))
                        lista_facturas = self.env.cr.dictfetchall()
                else:
                    self.env.cr.execute(
                        """SELECT id from account_invoice where date_invoice between '{0}' AND '{1}' and escuela=True and state in ('open','paid') and
                                    jornada_id={2} and id in {3}""".format(
                            self.fecha_desde, self.fecha_hasta,
                            self.jornada_id.id, str(tuple(invoice_ids.ids))))
                    lista_facturas = self.env.cr.dictfetchall()
        elif self.facturas_saldos == 'S':
            if self.jornada_id:
                if self.seccion_id:
                    if self.curso_id:
                        if self.paralelo_id:
                            self.env.cr.execute(
                                """SELECT id from account_invoice where date_invoice between '{0}' AND '{1}' and escuela=True and state in ('open','paid') and residual is not null and
                                    jornada_id={2} and seccion_id={3} and curso_id={4} and paralelo_id={5} and journal_id in ({6})"""
                                .format(self.fecha_desde, self.fecha_hasta,
                                        self.jornada_id.id, self.seccion_id.id,
                                        self.curso_id.id, self.paralelo_id.id,
                                        invoice_ids))
                            lista_facturas = self.env.cr.dictfetchall()
                        else:
                            self.env.cr.execute(
                                """SELECT id from account_invoice where date_invoice between '{0}' AND '{1}' and escuela=True and state in ('open','paid') and residual is not null and
                                    jornada_id={2} and seccion_id={3} and curso_id={4} and journal_id in ({5})"""
                                .format(self.fecha_desde, self.fecha_hasta,
                                        self.jornada_id.id, self.seccion_id.id,
                                        self.curso_id.id, invoice_ids))
                            lista_facturas = self.env.cr.dictfetchall()
                    else:
                        self.env.cr.execute(
                            """SELECT id from account_invoice where date_invoice between '{0}' AND '{1}' and escuela=True and state in ('open','paid') and residual is not null and
                                    jornada_id={2} and seccion_id={3} and journal_id in ({4})"""
                            .format(self.fecha_desde, self.fecha_hasta,
                                    self.jornada_id.id, self.seccion_id.id,
                                    invoice_ids))
                        lista_facturas = self.env.cr.dictfetchall()
                else:
                    self.env.cr.execute(
                        """SELECT id from account_invoice where date_invoice between '{0}' AND '{1}' and escuela=True and state in ('open','paid') and residual is not null and
                                    jornada_id={2} and journal_id in ({3})""".
                        format(self.fecha_desde, self.fecha_hasta,
                               self.jornada_id.id, invoice_ids))
                    lista_facturas = self.env.cr.dictfetchall()
        elif self.facturas_saldos == 'N':
            if self.jornada_id:
                if self.seccion_id:
                    if self.curso_id:
                        if self.paralelo_id:
                            self.env.cr.execute(
                                """SELECT id from account_invoice where date_invoice between '{0}' AND '{1}' and escuela=True and state in ('open','paid') and residual is null and
                                    jornada_id={2} and seccion_id={3} and curso_id={4} and paralelo_id={5} and journal_id in ({6})"""
                                .format(self.fecha_desde, self.fecha_hasta,
                                        self.jornada_id.id, self.seccion_id.id,
                                        self.curso_id.id, self.paralelo_id.id,
                                        invoice_ids))
                            lista_facturas = self.env.cr.dictfetchall()
                        else:
                            self.env.cr.execute(
                                """SELECT id from account_invoice where date_invoice between '{0}' AND '{1}' and escuela=True and state in ('open','paid') and residual is NULL and
                                    jornada_id={2} and seccion_id={3} and curso_id={4} and journal_id in ({5})"""
                                .format(self.fecha_desde, self.fecha_hasta,
                                        self.jornada_id.id, self.seccion_id.id,
                                        self.curso_id.id, invoice_ids))
                            lista_facturas = self.env.cr.dictfetchall()
                    else:
                        self.env.cr.execute(
                            """SELECT id from account_invoice where date_invoice between '{0}' AND '{1}' and escuela=True and state in ('open','paid') and residual is null and
                                    jornada_id={2} and seccion_id={3} and journal_id in ({4})"""
                            .format(self.fecha_desde, self.fecha_hasta,
                                    self.jornada_id.id, self.seccion_id.id,
                                    invoice_ids))
                        lista_facturas = self.env.cr.dictfetchall()
                else:
                    self.env.cr.execute(
                        """SELECT id from account_invoice where date_invoice between '{0}' AND '{1}' and escuela=True and state in ('open','paid') and residual is null and
                                    jornada_id={2} and journal_id in ({3})""".
                        format(self.fecha_desde, self.fecha_hasta,
                               self.jornada_id.id, invoice_ids))
                    lista_facturas = self.env.cr.dictfetchall()

        lista_facturas_id = [value['id'] for value in lista_facturas]
        obj_datos = self.env['account.invoice'].search(
            [('id', 'in', lista_facturas_id)], order='jornada_id')
        dic = {}
        lista_datos = []
        descripcion = ''
        for l in obj_datos:
            descripcion = ''
            for det in l.invoice_line:
                descripcion = descripcion + ' ' + det.name
            objDate = datetime.strptime(l.date_invoice, '%Y-%m-%d')
            fecha_emision = datetime.strftime(objDate, '%d/%m/%Y')

            dic = {
                'tipo':
                l.journal_id.tipo_reporte,
                "codigo_alumno":
                l.alumno_id.codigo_alumno,
                'numero':
                l.numerofac,
                'emision':
                fecha_emision,
                "vencimiento":
                l.date_due,
                "dias_mora":
                (datetime.now() - self.strToDatetime(l.date_due)).days,
                'alumno':
                l.alumno_id.name,
                'jornada':
                l.jornada_id.name,
                'seccion':
                l.seccion_id.name,
                'curso':
                l.curso_id.name,
                'paralelo':
                l.paralelo_id.codigo,
                'saldo':
                l.residual,
                'total':
                l.amount_total,
                "pagos":
                sum(line.credit for line in (
                    l.filtered(lambda diario: diario.journal_id.
                               cheques_postfechados == False)).payment_ids),
                "cheques_postfechados":
                sum(line.credit for line in (
                    l.filtered(lambda diario: diario.journal_id.
                               cheques_postfechados == True)).payment_ids),
                'comentario':
                descripcion
            }
            lista_datos.append(dic)
            dic = {}
        #-------------------------------------------------------------------------------------------------------------------
        #                     AGRUPAR LAS CABECERAS                                                                        -
        #  SE AGRUPA LAS JORNADAS,SECCION,CURSO,PARALELO PARA TENER UNA SOLA LISTA DE TODAS SI DUPLICADOS                  -
        #-------------------------------------------------------------------------------------------------------------------
        lista_cabecera = []
        dic_cab = {}
        for m in lista_datos:
            dic_cab = {
                'jornada': m['jornada'],
                'seccion': m['seccion'],
                'curso': m['curso'],
                'paralelo': m['paralelo'],
            }
            if dic_cab not in lista_cabecera:
                lista_cabecera.append(dic_cab)
        #-------------------------------------------------------------------------------------------------------------------
        #                     AGRUPAR LAS CABECERAS Y DETALLE                                                              -
        #  CON LA CABECERAS AGRUPADAS SOLO SE LES AGREGA UNA LISTA CON LOS DETALLES DE LOS ALUMNOS                         -
        #-------------------------------------------------------------------------------------------------------------------
        lista_completa = []
        for n in lista_cabecera:
            dic_cab = {
                'jornada': n['jornada'],
                'seccion': n['seccion'],
                'curso': n['curso'],
                'paralelo': n['paralelo'],
            }
            detalle = {}
            lista_detalle = []
            for deta in lista_datos:
                if deta['jornada'] == n['jornada'] and deta['seccion'] == n[
                        'seccion'] and deta['curso'] == n['curso'] and deta[
                            'paralelo'] == n['paralelo']:
                    detalle = {
                        'tipo': deta['tipo'],
                        "codigo_alumno": deta["codigo_alumno"],
                        "vencimiento": deta["vencimiento"],
                        "dias_mora": deta["dias_mora"],
                        "pagos": deta["pagos"],
                        "cheques_postfechados": deta["cheques_postfechados"],
                        'numero': deta['numero'],
                        'emision': deta['emision'],
                        'alumno': deta['alumno'],
                        'comentario': deta['comentario'],
                        'saldo': deta['saldo'],
                        'total': deta['total'],
                    }
                    lista_detalle.append(detalle)
            dic_det = {
                'jornada': n['jornada'],
                'seccion': n['seccion'],
                'curso': n['curso'],
                'paralelo': n['paralelo'],
                'detalle': lista_detalle,
            }
            lista_completa.append(dic_det)

        for d in lista_completa:
            print(d['jornada'], '   ', d['seccion'], '   ', d['curso'],
                  '     ', d['paralelo'], '     ', len(d['detalle']))

        datos = {
            'lista': lista_completa,
            'cant': len(obj_datos),
        }

        return datos
#-------------------------------------------------------------------------------------------------------------------
#                     CREACION DE EXCEL                                                                            -
#-------------------------------------------------------------------------------------------------------------------

    @api.multi
    def generar_excel(self):
        fp = io.BytesIO()
        workbook = self.crear_excel_info()
        workbook.save(fp)
        self.filename = 'Informe.xlsx'
        self.archivo_xls = base64.b64encode(fp.getvalue())
        return True

    def crear_excel_info(self):
        wb = crear_informe_cobranza_excel.crear_wb_informe()
        self.crear_informe(wb)
        return wb

    def crear_informe(self, wb):
        fecha_a = datetime.strptime(self.fecha_hasta, '%Y-%m-%d')
        fecha_actual = datetime.strftime(fecha_a, '%d/%b/%Y')
        dic = {
            'jornada_id': self.jornada_id.name,
            'seccion_id': self.seccion_id.name,
            'curso_id': self.curso_id.name,
            'curso_codigo': self.curso_id.codigo,
            'paralelo_id': self.paralelo_id.codigo,
            'usuario_id': self.usuario_id.name,
            'fecha_corte': fecha_actual,
            #'fecha':fecha_actual,
        }

        datos = self.consultar()
        lista_datos = datos['lista']
        cant_datos = datos['cant']

        sheet_info = crear_informe_cobranza_excel.crea_hoja_info_pdf(
            wb, 'Informe ', 0)
        # sheet_view = openpyxl.worksheet.views.SheetView()
        # sheet_view.zoomScale = "70"
        # sheet_view.zoomScaleNormal = "70"
        # sheet_info.sheet_view = sheet_view
        # sheet_info.zoomScale = "70"
        crear_informe_cobranza_excel.Informe_financiero(
            sheet_info, dic, lista_datos, cant_datos, self.saldo, self.total)

#-------------------------------------------------------------------------------------------------------------------
#                     CREACION DE PDF                                                                              -
#-------------------------------------------------------------------------------------------------------------------

    @api.multi
    def generar_pdf(self):
        filename_pdf = ''
        filename_pdf = ''
        fp = io.BytesIO()
        workbook = self.crear_excel_info_pdf()
        workbook.save(fp)
        filename_pdf = 'Informe.xlsx'
        archivo_pdf = base64.b64encode(fp.getvalue())
        obj = self.env['ir.attachment']
        obj_xls = obj.create({
            'res_model': self.id,
            'name': filename_pdf,
            'datas': archivo_pdf,
            'type': 'binary',
            'datas_fname': filename_pdf
        })
        direccion_xls = obj._get_path(obj_xls.datas)[1]
        direccion = obj._get_path(obj_xls.datas)[0]
        nombre_bin = obj_xls.store_fname
        nombre_archivo = obj_xls.datas_fname
        separa = direccion_xls.rstrip(direccion)
        # separa = "/home/rrojas/.local/share/Odoo/filestore/ans_escuela_01-12-2020"
        os.chdir(separa)
        os.rename(nombre_bin, nombre_archivo)
        commands.getoutput(
            """ libreoffice --headless --convert-to pdf *.xlsx""")
        with open(separa + '/' + nombre_archivo.split('.')[0] + '.pdf',
                  "rb") as f:
            data = f.read()
            file = data.encode("base64")
        self.write({
            'filename_pdf': nombre_archivo.split('.')[0] + '.pdf',
            'archivo_pdf': file
        })
        os.rename(nombre_archivo, nombre_bin)
        obj_xls.unlink()

        return True

    def crear_excel_info_pdf(self):
        wb = crear_informe_cobranza_excel.crear_wb_informe()
        self.crear_informe_pdf(wb)
        return wb

    def crear_informe_pdf(self, wb):
        fecha_a = datetime.strptime(self.fecha_hasta, '%Y-%m-%d')
        fecha_actual = datetime.strftime(fecha_a, '%d/%b/%Y')
        dic = {
            'jornada_id': self.jornada_id.name,
            'seccion_id': self.seccion_id.name,
            'curso_id': self.curso_id.name,
            'curso_codigo': self.curso_id.codigo,
            'paralelo_id': self.paralelo_id.codigo,
            'usuario_id': self.usuario_id.name,
            'fecha_corte': fecha_actual,
        }

        datos = self.consultar()
        lista_datos = datos['lista']
        cant_datos = datos['cant']
        sheet_info = crear_informe_cobranza_excel.crea_hoja_info_pdf(
            wb, 'Informe ', 0)
        # sheet_info = crear_informe_cobranza_excel.crea_hoja_info(wb, 'Informe ',0)
        # sheet_view = openpyxl.worksheet.views.SheetView()
        # sheet_view.zoomScale = "70"
        # sheet_view.zoomScaleNormal = "70"
        # sheet_info.sheet_view = sheet_view
        # sheet_info.zoomScale = "70"
        crear_informe_cobranza_excel.Informe_financiero(
            sheet_info, dic, lista_datos, cant_datos, self.saldo, self.total)

    ##Archivos tutor
    @api.multi
    def generar_excel_tutor(self):
        fp = io.BytesIO()
        workbook = self.crear_excel_info_tutor()
        workbook.save(fp)
        return self.download_file(fp, 'Informe Tutor.xlsx')

    @api.multi
    def generar_pdf_tutor(self):
        fp = io.BytesIO()
        workbook = self.crear_excel_info_tutor()
        workbook.save(fp)
        return self.download_file(fp, 'Informe Tutor.xlsx', True)

    def crear_excel_info_tutor(self):
        wb = crear_informe_cobranza_excel.crear_wb_informe()
        self.crear_informe_tutor_xlsx(wb)
        return wb

    def crear_informe_tutor_xlsx(self, wb):
        fecha_a = datetime.strptime(self.fecha_hasta, '%Y-%m-%d')
        fecha_actual = datetime.strftime(fecha_a, '%d/%b/%Y')
        dic = {
            'jornada_id': self.jornada_id.name,
            'seccion_id': self.seccion_id.name,
            'curso_id': self.curso_id.name,
            'curso_codigo': self.curso_id.codigo,
            'paralelo_id': self.paralelo_id.codigo,
            'usuario_id': self.usuario_id.name,
            'fecha_corte': fecha_actual,
        }

        datos = self.consultar()
        lista_datos = datos['lista']
        cant_datos = datos['cant']
        sheet_info = crear_informe_cobranza_excel.crea_hoja_info_pdf(
            wb, 'Informe Tutor', 0, True)
        crear_informe_cobranza_excel.Informe_financiero(
            sheet_info, dic, lista_datos, cant_datos, 0, 0,
            True)  #self.saldo, self.total, True)
예제 #27
0
class MrpRawmaterial(models.Model):
    _name = 'mrp.raw.material.request'
    _inherit = ['mail.thread']
    _order = 'id desc'

    rm_reject_reason = fields.Char(string='RM Reject Reason',
                                   track_visibility='always',
                                   copy=False)
    name = fields.Char('Name')
    production_id = fields.Many2one('mrp.production', string='Production No.')
    request_line_ids = fields.One2many('mrp.raw.material.request.line',
                                       'material_request_id',
                                       string='Request Line')
    state = fields.Selection([('draft', 'Requested'), ('approve', 'Approved'),
                              ('partialy', 'Partialy Send'), ('send', 'Send'),
                              ('reject', 'Rejeted'), ('cancel', 'Cancelled')],
                             string='Status',
                             default='draft')

    wastage_qty = fields.Float('Wastage Qty')
    request_date = fields.Datetime('Requested Date')
    partner_id = fields.Many2one(related='production_id.partner_id',
                                 store=True)
    expected_compl_date = fields.Datetime('Expected Completion Date')
    wastage_allow = fields.Float('Wastage Allowed')
    required_qty = fields.Float('Required Qty')
    allow_wastage_uom_id = fields.Many2one('product.uom')
    wastage_uom_id = fields.Many2one('product.uom')
    required_uom_id = fields.Many2one('product.uom')
    product_id = fields.Many2one('product.product', string='Product')
    note = fields.Text('Remark')
    note_mgnr = fields.Text('Manager Remark')
    document = fields.Binary('Document')
    request_type = fields.Selection([('normal', 'Normal Request'),
                                     ('extra', 'Extra Request')],
                                    string='Request Type')
    reason = fields.Selection([('wastage', 'Wastage'),
                               ('extra production', 'Extra Production')],
                              string='Reason')

    delivery_id = fields.Many2one('stock.picking', 'Delivery No.')
    picking_ids = fields.Many2many(
        'stock.picking',
        'raw_material_request_send_picking_rel',
        'rm_id',
        'picking_id',
        'Delivery No.',
        help="Send Raw Material To Manufacturing Department")

    work_order_ids = fields.One2many('mrp.production.workcenter.line',
                                     'rm_request_id',
                                     string='Work Orders')
    work_rm_ids = fields.One2many('workorder.raw.material',
                                  'rm_request_id',
                                  string='Work Orders')
    #schedule_raw_bool=fields.Boolean('Hide Schedule Raw button', default=False)
    source_location = fields.Many2one('stock.location')
    shift_request_line = fields.One2many('mrp.workorder.rm.shifts',
                                         'request_id',
                                         string='Delivery Numbers')
    mo_cancel = fields.Boolean('MO Cancel')

    @api.model
    def create(self, vals):
        if not vals.get('name'):
            vals['name'] = self.env['ir.sequence'].next_by_code(
                'mrp.raw.material.request') or 'New'
        result = super(MrpRawmaterial, self).create(vals)
        return result

    @api.multi
    def cancel_state(self):
        self.state = 'cancel'

    @api.multi
    @api.onchange('source_location')
    def on_change_source(self):
        #to get available qty from stock>>>
        try:
            for line in self:
                if line.source_location:
                    for res in line.request_line_ids:
                        qty = 0
                        quants = self.env['stock.quant'].search([
                            ('product_id', '=', res.product_id.id),
                            ('location_id', '=', line.source_location.id)
                        ])
                        for q in quants:
                            qty += q.qty
                        res.available_qty = qty - res.product_id.qty_reserved if (
                            qty - res.product_id.qty_reserved) > 0 else 0
        except Exception as err:
            raise UserError(
                "Exception in Source Location selection in raw Material Request -: {} "
                .format(err))

    @api.multi
    def approve_state(self):
        error_print = ''
        try:
            for rec in self:
                #                   for both extra and normal reqest type of mrp production order internal pikcing shud get created
                if rec.request_type in ('extra', 'normal'):
                    location_1 = False
                    if rec.production_id.product_id.categ_id.cat_type == 'film':
                        location_1 = 'send_film_rm_picking'
                    elif rec.production_id.product_id.categ_id.cat_type == 'injection':
                        location_1 = 'send_injection_rm_picking'
                    else:
                        error_print = "Product Internal Type is not proper"
                        raise

                    data_obj = self.env['ir.model.data']
                    raw_picking_location1 = data_obj.get_object_reference(
                        'api_raw_material', location_1)[1]
                    picking_type1 = self.env['stock.picking.type'].search(
                        [('id', '=', raw_picking_location1)], limit=1)
                    print "picking_type1picking_type1", picking_type1
                    procurement_id = self.env['procurement.group'].create({
                        'name':
                        rec.production_id.name,
                        'move_type':
                        'direct'
                    })
                    lst = []
                    picking = picking1 = False
                    if any(line.pick_qty == 0.0
                           for line in rec.request_line_ids):
                        raise UserError(
                            _("You cannot pick 0 qty for raw materials!!!"))
                    for line in rec.request_line_ids:
                        move_ids = self.env['stock.move'].create({
                            'date':
                            rec.request_date,
                            'origin':
                            rec.name,
                            'product_id':
                            line.product_id.id,
                            'product_uom_qty':
                            line.pick_qty,
                            'product_uom':
                            line.uom_id.id,
                            'picking_type_id':
                            picking_type1.id,
                            'location_dest_id':
                            picking_type1.default_location_dest_id.id,
                            'location_id':
                            rec.source_location.id,
                            'name':
                            rec.name,
                            'group_id':
                            procurement_id.id
                        })
                        move_ids.with_context({
                            'rm_route': True,
                            'product_id': rec.product_id.id
                        }).action_confirm()
                        picking = move_ids.picking_id
                    if picking:
                        picking.material_request_id = rec.id
                        picking.min_date = rec.request_date
                        picking.expected_comple_date = rec.expected_compl_date
                        picking.origin = rec.production_id.name
                        picking.ntransfer_type = 'rm_virtual'
                        rec.picking_ids = [(4, picking.id)]
                        for move in picking.move_lines:
                            if move.move_dest_id and move.move_dest_id.picking_id:
                                picking1 = move.move_dest_id.picking_id
                                break
                        rec.delivery_id = picking.id
                        rec.production_id.delivery_ids = [(4, picking.id)
                                                          ]  # MO

                    if picking1:
                        picking1.material_request_id = rec.id
                        picking1.min_date = rec.request_date
                        picking.expected_comple_date = rec.expected_compl_date

                        picking1.production_id = rec.production_id.id
                        picking1.origin = rec.name
                        picking1.next_prev_picking_id = [(4, picking.id)]
                        picking1.ntransfer_type = 'rm_production'
                        rec.production_id.delivery_ids = [(4, picking1.id)
                                                          ]  # MO
#			else:
#				error_print = "Routes are not set for Raw Material products, Please go to setting and set Injection or Film"
#				raise

                rec.state = 'approve'
                for line in rec.request_line_ids:
                    line.reserve_status = 'approve'

#		   if rec.request_type in ('extra','normal'):
#			   temp_id = self.env.ref('api_raw_material.email_template_extra_raw_material_approve')
#			   if temp_id:
#			       user_obj = self.env['res.users'].browse(self.env.uid)
#			       base_url = self.env['ir.config_parameter'].get_param('web.base.url')
#			       query = {'db': self._cr.dbname}
#			       fragment = {
#				    'model': 'mrp.production',
#				     'view_type': 'form',
#				     'id': rec.production_id.id,
#				      }
#			       url = urljoin(base_url, "/web?%s#%s" % (urlencode(query), urlencode(fragment)))
#			       text_link = _("""<a href="%s">%s</a> """) % (url,rec.production_id.name)
#			       body_html = """<div>
#				<p> <strong>Raw Material Request Approved</strong><br/><br/>
#				 <b>Dear: %s,</b><br/>
#				 <b>Production Number :</b>%s ,<br/>
#				  <b>Customer Name :</b>%s ,<br/>
#				  <b>Product Name :</b>%s ,<br/>
#				  <b>Allowed Wastage :</b>%s %s,<br/>
#				  <b>  Wastage Qty : %s %s</b><br/>
#				  <b>  Required Qty : %s %s</b><br/>
#				  <b>  Reason : </b>%s<br/>
#				  <b>  Production Remark : </b>%s<br/>
#				  <b>  Manager Remark : </b>%s
#				</p>
#				</div>#"""%(rec.production_id.user_id.name, text_link or '',rec.production_id.partner_id.name,
#				    rec.product_id.name, rec.wastage_allow,
#				   rec.allow_wastage_uom_id.name,
#				  rec.wastage_qty, rec.wastage_uom_id.name, rec.required_qty,
#				 rec.required_uom_id.name,rec.reason, rec.note, rec.note_mgnr)
#			       body_html +="<table class='table' style='width:50%; height: 50%;font-family:arial; text-align:left;'><tr><th>Material Name </th><th> qty</th></tr>"
#			       for line in rec.request_line_ids:
#				   body_html +="<tr><td>%s</td><td>%s %s</td></tr>"%(str(line.product_id.name), str(line.qty), str(line.uom_id.name))
#			       body_html +="</table>"
#			       body_html = self.pool['mail.template'].render_template(self._cr, self._uid, body_html, 'mrp.raw.material.request',rec.id, context=self._context)
#			       n_emails=str(rec.production_id.user_id.login)
#			       temp_id.write({'body_html': body_html, 'email_to' : n_emails, 'email_from': str(rec.production_id.user_id.login)})
#			       temp_id.send_mail(rec.id)
        except Exception as err:
            raise UserError(
                "Exception in Approval of raw Material Request -: {} ".format(
                    error_print if error_print else err))
        return True

    @api.multi
    def reject_rm_request(self):
        cofirm_form = self.env.ref('api_account.pay_cancel_wizard_view_form',
                                   False)
        if cofirm_form:
            return {
                'name': 'RM Reject Wizard',
                'type': 'ir.actions.act_window',
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'cancel.pay.reason.wizard',
                'views': [(cofirm_form.id, 'form')],
                'view_id': cofirm_form.id,
                'target': 'new'
            }

    @api.multi
    def reject_state(self):
        error_print = ''
        try:
            for rec in self:
                rec.state = 'reject'
                for line in rec.request_line_ids:
                    line.reserve_status = 'reject'
                rec.production_id.write({'state': 'rmr'})

                if rec.request_type == 'extra':
                    if not rec.note_mgnr:
                        error_print = "Pleas fill the Manager Remark...."
                        raise


#			temp_id = self.env.ref('api_raw_material.email_template_extra_raw_material_reject')
#			if temp_id:
#			       user_obj = self.env['res.users'].browse(self.env.uid)
#			       base_url = self.env['ir.config_parameter'].get_param('web.base.url')
#			       query = {'db': self._cr.dbname}
#			       fragment = {
#				    'model': 'mrp.production',
#				     'view_type': 'form',
#				     'id': rec.production_id.id,
#				      }
#			       url = urljoin(base_url, "/web?%s#%s" % (urlencode(query), urlencode(fragment)))
#			       text_link = _("""<a href="%s">%s</a> """) % (url,rec.production_id.name)
#			       body_html = """<div>
#				<p> <strong>Extra Raw Material Request Rejected</strong><br/><br/>
#				 <b>Dear: %s,</b><br/>
#				 <b>Production Number :</b>%s ,<br/>
#				 <b>Customer Name :</b>%s ,<br/>
#				  <b>Product Name :</b>%s ,<br/>
#				  <b>Allowed Wastage :</b>%s %s,<br/>
#				  <b>  Wastage Qty : %s %s</b><br/>
#				  <b>  Required Qty : %s %s</b><br/>
#				  <b>  Reason : </b>%s<br/>
#				  <b>  Production Remark : </b>%s<br/>
#				  <b>  Manager Remark : </b>%s
#				</p>
#				</div>#"""%(rec.production_id.user_id.name, text_link or '',rec.production_id.partner_id.name,
#				    rec.product_id.name, rec.wastage_allow,
#				   rec.allow_wastage_uom_id.name,
#				  rec.wastage_qty, rec.wastage_uom_id.name, rec.required_qty,
#				 rec.required_uom_id.name,rec.reason, rec.note, rec.note_mgnr)
#			       body_html +="<table class='table' style='width:50%; height: 50%;font-family:arial; text-align:left;'><tr><th>Material Name </th><th> qty</th></tr>"
#			       for line in rec.request_line_ids:
#				   body_html +="<tr><td>%s</td><td>%s %s</td></tr>"%(str(line.product_id.name), str(line.qty), str(line.uom_id.name))
#			       body_html +="</table>"
#			       body_html = self.pool['mail.template'].render_template(self._cr, self._uid, body_html, 'mrp.raw.material.request',rec.id, context=self._context)
#			       n_emails=str(rec.production_id.user_id.login)
#
#			       temp_id.write({'body_html': body_html, 'email_to' : n_emails, 'email_from': str(rec.production_id.user_id.login)})
#			       temp_id.send_mail(rec.id)
        except Exception as err:
            raise UserError("{} ".format(error_print if error_print else err))

        return True
예제 #28
0
class MrpProductionExtraRM(models.Model):
    _name = 'mrp.extra.raw.material'

    production_id = fields.Many2one('mrp.production', string='Production No.')
    wastage_qty = fields.Float('Wastage Qty')
    required_qty = fields.Float('Required Qty')
    wastage_uom_id = fields.Many2one('product.uom')
    required_uom_id = fields.Many2one('product.uom')
    extra_product_ids = fields.One2many('mrp.extra.raw.material.line',
                                        'line_id',
                                        string='Required Product')
    note = fields.Text('Remark')
    document = fields.Binary('Document')
    reason = fields.Selection([('wastage', 'Wastage'),
                               ('extra production', 'Extra Production')],
                              string='Reason')
    used_raw_matrial_ids = fields.One2many('mrp.extra.raw.material.line',
                                           'use_line_id',
                                           string='Required Product')
    remain_qty = fields.Float('Remain Qty', compute='_get_remain_qty')

    @api.constrains('wastage_qty')
    def _check_qty(self):
        for record in self:
            if record.used_raw_matrial_ids:
                sm = sum(line.qty for line in record.used_raw_matrial_ids)
                if record.wastage_qty < sm:
                    raise ValidationError(
                        "Total Used Wastage Qty is not greater than Wastage Qty."
                    )

    @api.multi
    @api.depends('used_raw_matrial_ids.qty')
    def _get_remain_qty(self):
        for record in self:
            qty = 0
            for line in record.used_raw_matrial_ids:
                qty = sum(line.qty for line in record.used_raw_matrial_ids)
            if qty:
                record.remain_qty = record.wastage_qty - qty
            else:
                record.remain_qty = record.wastage_qty

    @api.multi
    @api.onchange('required_qty')
    def required_rmqty(self):
        for record in self:
            if record.extra_product_ids:
                pcs_qty = (record.required_qty /
                           record.production_id.product_id.weight)
                lst = []
                for ln in record.extra_product_ids:
                    qty = self.env['mrp.bom.line'].search(
                        [('product_id', '=', ln.product_id.id), '|',
                         ('bom_packaging_id', '=',
                          record.production_id.bom_id.id),
                         ('bom_id', '=', record.production_id.bom_id.id)],
                        limit=1)
                    ln.qty = (pcs_qty * qty.product_qty)

    @api.multi
    def extra_rawmaterials(self):
        for rec in self:
            print "use_rawuse_raw", self._context
            if self._context.get('use_raw'):
                print 'TEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE'
                for record in rec.used_raw_matrial_ids:
                    product_id = 0
                    if record.used_type == 'grinding':
                        if not rec.production_id.product_id.check_grinding:
                            raise UserError(
                                _('Please Select Grinding product in Manufacturing Product.'
                                  ))
                        else:
                            product_id = rec.production_id.product_id.grinding_product_id.id
                    else:
                        if not rec.production_id.product_id.check_scrap:
                            raise UserError(
                                _('Please Select Scrap product in Manufacturing Product.'
                                  ))
                        else:
                            product_id = rec.production_id.product_id.scrap_product_id.id
                    batch = self.env['mrp.order.batch.number'].sudo().create({
                        'name':
                        str(record.used_type) + '-' +
                        str(rec.production_id.name) + '-' +
                        str(rec.production_id.product_id.default_code),
                        'production_id':
                        rec.production_id.id,
                        'uom_id':
                        record.uom_id.id,
                        'product_qty':
                        record.qty,
                        'wastage_product':
                        product_id,
                        #'wastage_allow':record.production_id.wastage_allow,
                        # 'wastage_qty':rec.production_id.total_wastage_qty,
                        'used_type':
                        record.used_type
                    })
                    print "batch--------------------------", batch
                rec.production_id.requested_wastage_qty += sum(
                    line.qty for line in rec.used_raw_matrial_ids)

            else:
                print "jkkkkkkkkkkkkkkkkkkkkkk"
                request = self.env['mrp.raw.material.request'].create({
                    'production_id':
                    rec.production_id.id,
                    'wastage_qty':
                    rec.wastage_qty,
                    'required_qty':
                    rec.required_qty,
                    'wastage_uom_id':
                    rec.wastage_uom_id.id,
                    'required_uom_id':
                    rec.required_uom_id.id,
                    'product_id':
                    rec.production_id.product_id.id,
                    'request_type':
                    'extra',
                    'wastage_allow':
                    rec.production_id.wastage_allow,
                    'request_date':
                    time.strftime('%Y-%m-%d %H:%M:%S'),
                    'allow_wastage_uom_id':
                    rec.production_id.allow_wastage_uom_id.id,
                    'note':
                    rec.note,
                    'document':
                    rec.document,
                    'reason':
                    rec.reason
                })

                for line in rec.extra_product_ids:
                    request_line = self.env[
                        'mrp.raw.material.request.line'].create({
                            'material_request_id':
                            request.id,
                            'product_id':
                            line.product_id.id,
                            'qty':
                            line.qty,
                            'uom_id':
                            line.uom_id.id
                        })
                    for product in rec.production_id.product_lines:
                        if product.product_id.id == line.product_id.id:
                            product.product_qty += line.qty

                temp_id = self.env.ref(
                    'api_raw_material.email_template_extra_raw_material')
                if temp_id:
                    user_obj = self.env['res.users'].browse(self.env.uid)
                    base_url = self.env['ir.config_parameter'].get_param(
                        'web.base.url')
                    query = {'db': self._cr.dbname}
                    fragment = {
                        'model': 'mrp.production',
                        'view_type': 'form',
                        'id': rec.production_id.id,
                    }
                    url = urljoin(
                        base_url,
                        "/web?%s#%s" % (urlencode(query), urlencode(fragment)))
                    text_link = _("""<a href="%s">%s</a> """) % (
                        url, rec.production_id.name)
                    body_html = """<div> 
					<p> <strong>Extra Raw Material Request</strong><br/>
					 <b>Dear: %s,</b><br/>
					 <b>Production Number :</b>%s ,<br/> 
					 <b>Customer Name :</b>%s ,<br/>
					  <b>Product Name :</b>%s ,<br/>
					  <b>Allowed Wastage :</b>%s %s,<br/>
					  <b>  Wastage Qty : %s %s</b><br/>
					  <b>  Required Qty : %s %s</b><br/>
					  <b>  Reason : </b>%s<br/>
					  <b>  Remark : </b>%s
					</p>
					</div>""" % (rec.production_id.user_id.name, text_link
                    or '', rec.production_id.partner_id.name,
                    rec.production_id.product_id.name,
                    round(rec.production_id.wastage_allow,
                        2), rec.production_id.allow_wastage_uom_id.name,
                    round(rec.wastage_qty,
                        2), rec.wastage_uom_id.name, rec.required_qty,
                    rec.required_uom_id.name, rec.reason, rec.note)
                    body_html += "<table class='table' style='width:80%; height: 50%;font-family:arial; text-align:left;'><tr><th>Material Name </th><th> qty</th></tr>"
                    for line in rec.extra_product_ids:
                        body_html += "<tr><td>%s</td><td>%s %s</td></tr>" % (
                            str(line.product_id.name), round(
                                line.qty, 2), str(line.uom_id.name))
                    body_html += "</table>"
                    body_html = self.pool['mail.template'].render_template(
                        self._cr,
                        self._uid,
                        body_html,
                        'mrp.production',
                        rec.production_id.id,
                        context=self._context)
                    n_emails = str(rec.production_id.user_id.login)
                    temp_id.write({
                        'body_html':
                        body_html,
                        'email_to':
                        n_emails,
                        'email_from':
                        str(rec.production_id.user_id.login)
                    })
                    temp_id.send_mail(rec.production_id.id)
예제 #29
0
class dym_report_intercompany(models.TransientModel):
    _name = 'dym.report.intercompany'

    period_id = fields.Many2one('account.period',
                                'Period',
                                domain=[('company_id.code', '=', 'CON')],
                                required=True)
    journal_state = fields.Selection([('all', 'All State'),
                                      ('posted', 'Posted')],
                                     'Journal State',
                                     required=True)
    name = fields.Char('File Name')
    data_file = fields.Binary('File')

    @api.multi
    def eksport_excel(self):
        data_left = []
        data_right = []
        uniq_list = []
        obj_consol = self.env['account.move.consol']
        obj_intercom = self.env['dym.intercompany.ref']
        book = xlwt.Workbook()
        sheet = book.add_sheet("Intercompany Report")
        now = datetime.now()
        style = xlwt.easyxf('font: bold 1;')
        style_header = xlwt.easyxf(
            'font: bold 1, name Calibri, height 210; pattern: pattern solid, fore_colour yellow;'
        )

        header = [
            'Source', 'Date', 'Transaction 1', 'Branch 1', 'Transaction 2',
            'Branch 2', 'Ref Intercompany', 'Account 1', 'Debit', 'Account 2',
            'Credit'
        ]
        account_left_list = [
            x.account_left_id.id
            for x in self.period_id.company_id.account_report_intercom_line
        ]
        account_right_list = [
            x.account_right_id.id
            for x in self.period_id.company_id.account_report_intercom_line
        ]
        if self.journal_state == 'posted':
            consol_search = obj_consol.search([
                ('period_id', '=', self.period_id.id),
                ('state', '=', 'posted'),
                ('journal_id', '=', self.period_id.company_id.
                 journal_consolidate_multi_company_id.id)
            ])
        else:
            consol_search = obj_consol.search([
                ('period_id', '=', self.period_id.id),
                ('journal_id', '=', self.period_id.company_id.
                 journal_consolidate_multi_company_id.id)
            ])

        if consol_search:
            for consol in consol_search:
                for line in consol.line_id:
                    if line.account_id.id in account_left_list:
                        intercom = line._get_intercom_ref_id()
                        data_left.append({
                            'Origin':
                            line.move_id.name,
                            'Transaction 1':
                            line.consol_entry.ref or line.name,
                            'Ref Intercompany':
                            intercom or line.intercom_ref or '',
                            'Debit':
                            line.debit,
                            'Credit':
                            line.credit,
                            'Date':
                            line.date,
                            'Branch 1':
                            line.branch_id.name,
                            'Account 1':
                            line.account_id.code + ' ' + line.account_id.name,
                            'account_id':
                            line.account_id.id,
                            'analytic_account_id':
                            line.analytic_account_id.id,
                        })

                    if line.account_id.id in account_right_list:
                        intercom = line._get_intercom_ref_id()
                        data_right.append({
                            'Origin':
                            line.move_id.name,
                            'Transaction 2':
                            line.consol_entry.ref or line.name,
                            'Ref Intercompany':
                            intercom or line.intercom_ref or '',
                            'Debit':
                            line.debit,
                            'Credit':
                            line.credit,
                            'Date':
                            line.date,
                            'Branch 2':
                            line.branch_id.name,
                            'Account 2':
                            line.account_id.code + ' ' + line.account_id.name,
                            'account_id':
                            line.account_id.id,
                            'analytic_account_id':
                            line.analytic_account_id.id,
                        })

        for line in data_left:
            uniq_list.append(line)

        for left in data_left:
            for right in data_right:
                if left['Ref Intercompany'] == right['Ref Intercompany']:
                    if left['Ref Intercompany'] and right['Ref Intercompany']:
                        data_left[data_left.index(
                            left)]['Transaction 2'] = right['Transaction 2']
                        data_left[data_left.index(
                            left)]['Branch 2'] = right['Branch 2']
                        data_left[data_left.index(
                            left)]['Account 2'] = right['Account 2']
                        if not left['Debit']:
                            data_left[data_left.index(
                                left)]['Debit'] = right['Debit']
                        if not left['Credit']:
                            data_left[data_left.index(
                                left)]['Credit'] = right['Credit']
                else:
                    if right not in uniq_list:
                        uniq_list.append(right)

        no = 0
        max_len = {}
        for line in uniq_list:
            no += 1
            col = -1
            for i in header:
                col += 1
                if i in line:
                    sheet.write(no, col, line[i])
                    if col not in max_len:
                        max_len[col] = len(str(line[i]))
                    else:
                        if max_len[col] < len(str(line[i])):
                            max_len[col] = len(str(line[i]))
                    sheet.col(col).width = (max_len[col]) * 320

        colh = -1
        for x in header:
            colh += 1
            sheet.write(0, colh, x)

        filename = 'Intercompany_Report_on_%s.xls' % (
            now.strftime("%Y-%m-%d %H:%M:%S"))
        file_data = StringIO.StringIO()
        book.save(file_data)
        out = base64.encodestring(file_data.getvalue())
        self.write({'data_file': out, 'name': filename})

        view_rec = self.env['ir.model.data'].get_object_reference(
            'dym_journal_elimination', 'view_report_intercompany_wizard')
        view_id = view_rec[1] or False

        return {
            'view_type': 'form',
            'view_id': [view_id],
            'view_mode': 'form',
            'res_id': self.id,
            'res_model': 'dym.report.intercompany',
            'type': 'ir.actions.act_window',
            'target': 'new',
        }
예제 #30
0
class timepass(models.Model):
    _name = 'timepass'

    name = fields.Binary('Name:')
    models_id = fields.Many2one('ir.model','Search From Models:')



    # @api.multi
    # def download(self):
    #     return {
    #             'type': 'ir.actions.act_url',
    #             'url': '/web/binary/download_document?model=ir.attachment&field=datas&id=%s&filename=%s&download=true' %(self.id),
    #             'target': 'self',
    #     }
    #



    # @api.multi
    # def download(self):
    #     url = "http://samarth32.blogspot.in/"
    #     # values = {'q':'java'}
    #     # data = urllib.urlencode(values)
    #     # data = data.encode('utf-8')
    #     req = urllib.urlopen(url)
    #     print "File Done"
    #     return {
    #         'res_model': 'ir.actions.act_url',
    #         'type': 'ir.actions.act_url',
    #         'target' : 'new',
    #         'url' : req,
    #     }

        # req = requests.Request(url,data)
        # resp = requests.urlopen(req)
        # respData = resp.read()
        # print "File Done"


        # print ("downloading with urllib")
        # return urllib.urlretrieve(url,"myimage.png")

        # r = requests.get("https://google.com")

        # url = "https://google.com/"
        # print ("File Reading Done...!!!!")
        # return{
        #     'res_model': 'ir.actions.act_url',
        #     'type': 'ir.actions.act_url',
        #     'target' : 'new',
        #     'url' : r,
        # }



    @api.multi
    def download(self):
        context = dict(self._context or {})
        # print 'hello'
        # active_ids = context.get('active_ids', False)
        a = self.models_id
        b = ""
        c = ""
        print "a++++++++++++++++++++++++",a
        print "Name+++++++++++++++++++++",a.name
        res = self.env['ir.attachment'].search([('res_model','=',self.models_id.model)])
        # for each in res:
        #     # url = '/web/content?model=ir.attachment&field=datas&id=%s&filename=%s&download=true' % (each.id,each.name)
        #     b = each.id
        #     c = each.name
        #     print each.id
        #     print each.name

        with ZipFile('/home/bista/Downloads/all-attachments.zip', 'w') as myzip:
            for each in res:
                file_datas = base64.b64decode(each.datas)
                each_file = open(each.name, "w")
                each_file.write(file_datas)
                each_file.close()
                # print file.name
                myzip.write(str(each_file.name))
            file_open = open('/home/bista/Downloads/all-attachments.zip', "rb+")
            encode_zip = base64.encodestring(file_open.read())
            id = self.create({'name': encode_zip})
            b = id.id
            c = id.name
            print "id================",id
            print "Name===========",id.name

        return {
            'type': 'ir.actions.act_url',
            'url': '/web/content?model=timepass&field=%s&id=%s&filename=all-attachments.zip&download=true' % (c,b) ,
            'target': 'self',
            }