Ejemplo n.º 1
0
class ResPartner(models.Model):
    _inherit = 'res.partner'

    @api.onchange('student_id')
    @api.depends('student_id')
    def _onchange_student_id(self):
        for rc in self:
            if rc.student_id:
                if rc.student_id.recruit_id:
                    rc.is_recruit = True
                elif rc.student_id.industi_id:
                    rc.is_industrial = True
                else:
                    rc.is_recruit = False
                    rc.is_industrial = False

    line_ids = fields.One2many('school.student.line',
                               'name',
                               string='Students')
    is_recruit = fields.Boolean(string='Is a Recruitment Agent')
    is_industrial = fields.Boolean(string='Is an Industrial Partner')
    con_from = fields.Date(string='Contract Period')
    con_to = fields.Date(string='Contract Period To')
    student_id = fields.Many2one('school.student', string='Student Name')
    std_idd = fields.Char(string='Student ID',
                          size=256,
                          related='student_id.std_idd')
    course_id = fields.Many2many('school.school', string='Course')
    intake_id = fields.Many2many('school.class', string='Intake')
Ejemplo n.º 2
0
class res_partner_category(models.Model):
    _inherit = 'res.partner.category'

    sale_tag_id = fields.Many2many('sale.order', string='Partner Tags')
    stk_tag_id = fields.Many2many('stock.picking', string='Partner Tags')
    pro_tag_id = fields.Many2many('procurement.order', string='Partner Tags')
    inv_tag_id = fields.Many2many('account.invoice', string='Partner Tags')
Ejemplo n.º 3
0
class StockPicking(models.Model):
    _inherit = 'stock.picking'

    ntransfer_type = fields.Selection(
        selection_add=[('rm_virtual',
                        'Raw at Virtual'), ('rm_production',
                                            'RM at Produciton')])

    material_request_id = fields.Many2one('mrp.raw.material.request',
                                          'Request No.')
    rm_picking_ids = fields.Many2many('mrp.production.workcenter.line',
                                      'wo_raw_material_picking_rel',
                                      'picking_id',
                                      'wo_id',
                                      'Delivery No.',
                                      help="Receive Raw Material Delivery no.")
    next_prev_picking_id = fields.Many2many(
        'stock.picking',
        'next_previous_rm_picking_rel',
        'next_id',
        'prev_id',
        'Delivery No.',
        help="Shows next and previous delivery number")
    rm_received_emp = fields.Many2one('hr.employee', 'Received By')
    '''@api.multi
Ejemplo n.º 4
0
class Discussion(models.Model):
    _name = 'test_new_api.discussion'

    name = fields.Char(
        string='Title',
        required=True,
        help="General description of what this discussion is about.")
    moderator = fields.Many2one('res.users')
    categories = fields.Many2many('test_new_api.category',
                                  'test_new_api_discussion_category',
                                  'discussion', 'category')
    participants = fields.Many2many('res.users')
    messages = fields.One2many('test_new_api.message', 'discussion')
    message_concat = fields.Text(string='Message concatenate')
    important_messages = fields.One2many('test_new_api.message',
                                         'discussion',
                                         domain=[('important', '=', True)])

    @api.onchange('moderator')
    def _onchange_moderator(self):
        self.participants |= self.moderator

    @api.onchange('messages')
    def _onchange_messages(self):
        self.message_concat = "\n".join(
            ["%s:%s" % (m.name, m.body) for m in self.messages])
Ejemplo n.º 5
0
class Discussion(models.Model):
    _name = 'test_new_api.discussion'

    name = fields.Char(
        string='Title',
        required=True,
        help="General description of what this discussion is about.")
    moderator = fields.Many2one('res.users')
    categories = fields.Many2many('test_new_api.category',
                                  'test_new_api_discussion_category',
                                  'discussion', 'category')
    participants = fields.Many2many('res.users')
    messages = fields.One2many('test_new_api.message', 'discussion')
    message_changes = fields.Integer(string='Message changes')
    important_messages = fields.One2many('test_new_api.message',
                                         'discussion',
                                         domain=[('important', '=', True)])
    emails = fields.One2many('test_new_api.emailmessage', 'discussion')
    important_emails = fields.One2many('test_new_api.emailmessage',
                                       'discussion',
                                       domain=[('important', '=', True)])

    @api.onchange('moderator')
    def _onchange_moderator(self):
        self.participants |= self.moderator

    @api.onchange('messages')
    def _onchange_messages(self):
        self.message_changes = len(self.messages)
Ejemplo n.º 6
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)
Ejemplo n.º 7
0
class SchoolStudentLine(models.Model):
    _name = 'school.student.line'

    student_id = fields.Many2one('school.student', string='Student Name')
    std_idd = fields.Char(string='Student ID',
                          size=256,
                          related='student_id.std_idd')
    course_id = fields.Many2many('school.school', string='Course')
    intake_id = fields.Many2many('school.class', string='Intake')
    con_from = fields.Date(string='Contract Period')
    con_to = fields.Date(string='Contract Period To')
    name = fields.Many2one('res.partner', string='Customer')
Ejemplo n.º 8
0
class account_journal_cobro(models.Model):
    _inherit = "account.journal"

    @api.constrains('detalle_journal')
    def _accesos_usuarios_1(self):
        for l in self:
            lista_usuario = []
            if len(l.detalle_journal) != 0:
                for m in l.detalle_journal:
                    lista_usuario.append(m.user_id.id)

                l.usuarios_ids = lista_usuario
            else:
                l.usuarios_ids = None

            # l.write({
            #     'usuarios_ids':lista_usuario
            #     })
            # l.update({
            #     'usuarios_ids':lista_usuario
            #     })

    caja = fields.Boolean(string="Caja")
    exigir_doc_banco = fields.Boolean(string="Exigir datos bancarios en pago")
    detalle_journal = fields.One2many('account.journal.user',
                                      'journal_cabecera_id',
                                      string="Relacion Detalle")
    usuarios_ids = fields.Many2many('res.users', string="Accesos de Usuarios")
Ejemplo n.º 9
0
class stock_picking(models.Model):
    _inherit = 'stock.picking'

    category_id = fields.Many2many('res.partner.category',
                                   string='Partner Tags')

    @api.model
    def create(self, vals):
        partner_id = vals.get('partner_id', '')
        origin = vals.get('origin', False)
        if origin:
            sale_order = self.env['sale.order'].search([('name', '=', origin)])
            if sale_order:
                if sale_order.category_id.ids:
                    vals.update(
                        {'category_id': [(6, 0, sale_order.category_id.ids)]})
        return super(stock_picking, self).create(vals)

    @api.model
    def _create_invoice_from_picking(self, picking, vals):
        if 'partner_id' in vals and vals.get('partner_id', False):
            partner_id = vals.get('partner_id')
            partner = self.env['res.partner'].browse(partner_id)
            partner_tag = partner.category_id.ids or False
            if partner_tag:
                vals.update({'category_id': [(6, 0, partner_tag)]})
            else:
                vals.update({'category_id': []})
        return super(stock_picking,
                     self)._create_invoice_from_picking(picking, vals)
Ejemplo n.º 10
0
class subject(models.Model):
    _name = 'subject'

    name = fields.Char('Name', required=1)
    lectures_required = fields.Integer('Lectures Required')
    teacher_ids = fields.Many2many('teacher', 'teacher_subject_rel',
                                   'subject_id', 'teacher_id', 'Teachers')
Ejemplo n.º 11
0
class tools_helpdesk_contexto_nivel1(models.Model):
    """Estructura de Dependencias Administrativas"""
    _name = 'tools.helpdesk.contexto_nivel1'
    _rec_name = 'nombre'

    codigo = fields.Char(string="Código",
                         size=20,
                         help='Código de la Aplicación')
    nombre = fields.Char(string="Nombre",
                         size=60,
                         help='Nombre de la Aplicación')
    descripcion = fields.Text(string="Descripción",
                              help='Descripción de la Aplicación')
    res_partner_ids = fields.Many2many(
        'res.partner',
        'respartner_aplicacion_rel',
        'contexto_nivel1_id',
        'res_partner_id',
        string="Organización",
        help='Organización que implementa esta aplicación')
    contexto_nivel2_ids = fields.One2many(
        'tools.helpdesk.contexto_nivel2',
        'contexto_nivel1_id',
        string="Módulo",
        help='Módulos que pertenecen a esta Aplicación')
Ejemplo n.º 12
0
class res_users(models.Model):
    _inherit = 'res.users'

    business_area_ids = fields.Many2many('business.area',
                                         'business_area_user_rel',
                                         'user_id',
                                         'business_area_id',
                                         string='Business Areas')
Ejemplo n.º 13
0
class Discussion(models.Model):
    _name = 'test_new_api.discussion'

    name = fields.Char(
        string='Title',
        required=True,
        help="General description of what this discussion is about.")
    moderator = fields.Many2one('res.users')
    categories = fields.Many2many('test_new_api.category',
                                  'test_new_api_discussion_category',
                                  'discussion', 'category')
    participants = fields.Many2many('res.users')
    messages = fields.One2many('test_new_api.message', 'discussion')

    @api.onchange('moderator')
    def _onchange_moderator(self):
        self.participants |= self.moderator
Ejemplo n.º 14
0
class born_shop_template(models.Model):
    _name = 'born.shop.template'

    name = fields.Char(u'模版名')
    poistion_ids = fields.Many2many('born.shop.position', string=u'位置')
    color = fields.Selection([('blue', u'蓝色'), ('red', u'红色'),
                              ('black', u'黑色'), ('green', u'绿色')],
                             default='blue',
                             string=u'颜色主题',
                             help=u'颜色主题')
Ejemplo n.º 15
0
class result_wizard(models.TransientModel):
    _name = 'result.wizard'
    _description = 'New Description'

    name = fields.Char('Name')
    standard = fields.Selection([('first', '1st'), ('second', '2nd'), ('third', '3rd'), ('fourth', '4th'), ('fifth', '5th'), ('sixth', '6th'), ('seventh', '7th'), ('eight', '8th'), ('ninth', '9th'), ('tenth', '10th')], 'Standard.')
    division = fields.Selection([('a', 'A'), ('b', 'B'), ('c', 'C')], 'Division.')
    roll_no = fields.Integer('Roll No')
    birth_date = fields.Date('Date Of Birth')
    fees_amt = fields.Float('Fees')
    subject_ids = fields.Many2many('subject.records', 'student_subject_rel', 'subject_id', 'student_id', 'Subjects')
Ejemplo n.º 16
0
class born_shop_model(models.Model):
    _name = 'born.shop.model'

    name = fields.Char(u'模块名')
    type = fields.Selection([('url', u'幻灯片'), ('product_ids', u'文章'),
                             ('category_ids', u'产品'), ('content_ids', u'分类'),
                             ('function_ids', u'功能')],
                            default='url',
                            string=u'类型',
                            help=u'类型')
    category_ids = fields.Many2many('born.shop.category', string=u'内容')
Ejemplo n.º 17
0
class Category(models.Model):
    _name = 'test_new_api.category'

    name = fields.Char(required=True)
    color = fields.Integer('Color Index')
    parent = fields.Many2one('test_new_api.category')
    root_categ = fields.Many2one(_name, compute='_compute_root_categ')
    display_name = fields.Char(compute='_compute_display_name',
                               inverse='_inverse_display_name')
    dummy = fields.Char(store=False)
    discussions = fields.Many2many('test_new_api.discussion',
                                   'test_new_api_discussion_category',
                                   'category', 'discussion')

    @api.one
    @api.depends('name', 'parent.display_name')  # this definition is recursive
    def _compute_display_name(self):
        if self.parent:
            self.display_name = self.parent.display_name + ' / ' + self.name
        else:
            self.display_name = self.name

    @api.depends('parent')
    def _compute_root_categ(self):
        for cat in self:
            current = cat
            while current.parent:
                current = current.parent
            cat.root_categ = current

    @api.one
    def _inverse_display_name(self):
        names = self.display_name.split('/')
        # determine sequence of categories
        categories = []
        for name in names[:-1]:
            category = self.search([('name', 'ilike', name.strip())])
            categories.append(category[0])
        categories.append(self)
        # assign parents following sequence
        for parent, child in zip(categories, categories[1:]):
            if parent and child:
                child.parent = parent
        # assign name of last category, and reassign display_name (to normalize it)
        self.name = names[-1].strip()

    @api.multi
    def read(self, fields=None, load='_classic_read'):
        if self.search_count([('id', 'in', self._ids),
                              ('name', '=', 'NOACCESS')]):
            raise AccessError('Sorry')
        return super(Category, self).read(fields=fields, load=load)
Ejemplo n.º 18
0
class Discussion(models.Model):
    _name = 'test_new_api.discussion'

    name = fields.Char(
        string='Title',
        required=True,
        help="General description of what this discussion is about.")
    moderator = fields.Many2one('res.users')
    categories = fields.Many2many('test_new_api.category',
                                  'test_new_api_discussion_category',
                                  'discussion', 'category')
    participants = fields.Many2many('res.users')
    messages = fields.One2many('test_new_api.message', 'discussion')
    message_concat = fields.Text(string='Message concatenate')
    important_messages = fields.One2many('test_new_api.message',
                                         'discussion',
                                         domain=[('important', '=', True)])
    very_important_messages = fields.One2many(
        'test_new_api.message',
        'discussion',
        domain=lambda self: self._domain_very_important())
    emails = fields.One2many('test_new_api.emailmessage', 'discussion')
    important_emails = fields.One2many('test_new_api.emailmessage',
                                       'discussion',
                                       domain=[('important', '=', True)])

    def _domain_very_important(self):
        """Ensure computed O2M domains work as expected."""
        return [("important", "=", True)]

    @api.onchange('moderator')
    def _onchange_moderator(self):
        self.participants |= self.moderator

    @api.onchange('messages')
    def _onchange_messages(self):
        self.message_concat = "\n".join(
            ["%s:%s" % (m.name, m.body) for m in self.messages])
Ejemplo n.º 19
0
class od_hr_employee_dependents_line(models.Model):
    _name = 'od.hr.employee.dependents.line'
    _description = "od.hr.employee.dependents.line"
    employee_id = fields.Many2one('hr.employee', string='Employee')
    contacts = fields.Many2one(
        'res.partner',
        string='Contacts',
    )
    od_benefits_ids = fields.Many2many('od.hr.employee.benefits',
                                       'employee_id',
                                       'benefits_id',
                                       string='Benefits')
    relation_id = fields.Many2one(
        'od.employee.relation',
        string='Relation',
    )
Ejemplo n.º 20
0
class dym_program_subsidi(models.Model):
    _inherit = 'dym.program.subsidi'

    @api.one
    @api.depends('program_subsidi_line.product_template_id',
                 'program_subsidi_line.product_template_id.product_variant_ids'
                 )
    def _get_product_ids(self):
        product_ids = []
        for line in self.program_subsidi_line:
            product_ids += line.product_template_id.product_variant_ids.ids
        self.product_ids = product_ids

    product_ids = fields.Many2many('product.product',
                                   string='Products',
                                   compute='_get_product_ids',
                                   store=True)
Ejemplo n.º 21
0
class vetclinic_animal(models.Model):
    _name = 'vetclinic.animal'

    name = fields.Char('Name:', size=34)
    birthdate = fields.Date('BirthDate:')
    classification_id = fields.Many2one('vetclinic.classification',
                                        'Classification:')
    breed_id = fields.Many2one('vetclinic.breed', 'Breed:')
    labels_ids = fields.Many2many('vetclinic.labels',
                                  'rel_animal_labels',
                                  'animal_id',
                                  'labels_id',
                                  string='Labels:')
    history = fields.Text('History :')
    res_partner_id = fields.Many2one('res.partner', 'Owner:')
    animalvaccinations_id = fields.One2many('vetclinic.animalvaccination',
                                            'animal_id', 'Vaccinations:')
    animal_breed = fields.One2many('vetclinic.breed',
                                   'classification_id_of_breed', 'EXECUTE')

    @api.multi
    def myfunction(self):
        print "==========================", self._context
        animal_id = self._context.get('params')['id']
        print "b================", animal_id
        # a = self._context.get('params')['id']
        # print "a=====================",a

        # ac = self.env['ir.model.data'].xmlid_to_res_id('boatcompany.vetclinic_animal_form', raise_if_not_found=True)
        # ac = self.env['']
        # v_a = False
        # for o in self:
        #     v_a = o.id
        result = {
            'name': '2nd Animal',
            'view_type': 'form',
            'res_model': 'vetclinic.classification',
            'context': {
                'default_name': animal_id
            },
            'type': 'ir.actions.act_window',
            'view_mode': 'form'
        }
        return result
Ejemplo n.º 22
0
class sale_order(models.Model):
    _inherit = 'sale.order'

    category_id = fields.Many2many('res.partner.category',
                                   string='Partner Tags')

    def onchange_partner_id(self, cr, uid, ids, part, context=None):
        res = super(sale_order,
                    self).onchange_partner_id(cr, uid, ids, part, context)
        if not context:
            context = {}
        partner = self.pool.get('res.partner').browse(cr,
                                                      uid,
                                                      part,
                                                      context=context)
        partner_tag = partner.category_id.ids or False
        val = res.get('value', False)
        if partner_tag:
            val.update({'category_id': [(6, 0, partner_tag)]})
        else:
            val.update({'category_id': []})
        return res

    def action_invoice_create(self,
                              cr,
                              uid,
                              ids,
                              grouped=False,
                              states=None,
                              date_invoice=False,
                              context=None):
        if not context:
            context = {}
        res = super(sale_order,
                    self).action_invoice_create(cr, uid, ids, grouped, states,
                                                date_invoice, context)
        invoice_obj = self.pool.get('account.invoice')
        category_id = self.browse(cr, uid, ids,
                                  context=context).category_id.ids
        if category_id:
            invoice_obj.write(cr, uid, res,
                              {'category_id': [(6, 0, category_id)]}, context)
        return res
Ejemplo n.º 23
0
class teacher(models.Model):
    _name = 'teacher'

    name = fields.Char('Name', required=1)
    address = fields.Text('Address')
    pincode = fields.Char('Pincode')
    telephone = fields.Char('Telephone')
    birthdate = fields.Date('Birthdate')
    joindate = fields.Datetime('Join Date')
    subject_ids = fields.Many2many('subject','teacher_subject_rel','teacher_id','subject_id','Subjects')
    active = fields.Boolean('Active', default=1)

    @api.multi
    def active_action(self):
        if self.active:
            self.write({'active': False})
        elif not self.active:
            self.write({'active': True})
        else:
            self.write({'active': True})
        print "Is Active", self.active
Ejemplo n.º 24
0
class MrpWorkorderBatchNo(models.Model):
    _inherit = 'mrp.order.batch.number'

    quality_line_id = fields.Many2one('quality.checking.line', 'Quality Line')
    check_type = fields.Selection(
        [('approve', 'Approve'), ('reject', 'Reject')],
        "Inspect",
    )
    reject_resion = fields.Many2many('quality.reject.reason',
                                     'mrp_batch_reject_resion_rel',
                                     'batch_id',
                                     'resion_id',
                                     string='Reject Reason')

    approve_qty = fields.Float("Approve Quantity", default=0)
    reject_qty = fields.Float("Reject Quantity", default=0)
    scrapt_qty = fields.Float("Scrap Quantity", default=0)
    qty_unit_id = fields.Many2one(
        "product.uom",
        'Unit',
        help='Units of Approve Reject and Scrap Quantity')
    available_qty = fields.Float("Approve Quantity",
                                 compute="_get_available_qty",
                                 store=True)

    @api.multi
    @api.depends('approve_qty', 'reject_qty', 'scrapt_qty', 'product_qty',
                 'lot_id')
    def _get_available_qty(self):
        for rec in self:
            qty = rec.product_qty
            if rec.lot_id and rec.lot_id.product_uom_id and rec.lot_id.product_uom_id.id != rec.uom_id.id:
                if rec.lot_id.product_uom_id.name.upper() == 'PCS':
                    qty = rec.product_qty / rec.product_id.weight
                if rec.lot_id.product_uom_id.name.upper() == 'KG':
                    qty = rec.product_qty * rec.product_id.weight
            qty -= rec.approve_qty
            qty -= rec.reject_qty
            qty -= rec.scrapt_qty
            rec.available_qty = qty
Ejemplo n.º 25
0
class QualityScrapbatches(models.Model):
    """This table is used to select approved and reject batches in Manufacturing Scrap."""
    _name = 'quality.scrap.batches'

    history_id = fields.Many2one('quality.checking.line.history',string='Scrap')
    line_id = fields.Many2one('quality.checking.line',string='Scrap')
    quality_id=fields.Many2one('quality.checking', string='Quality No.')
    inspection_id=fields.Many2one('quality.inspection','Inspection No')
    state = fields.Selection([('draft', 'Draft'),('done', 'Done')], string='State',default='draft', readonly=True)
    history_line=fields.One2many('quality.checking.line.history.line','quality_batch_id','History Line') 
    
    lot_id=fields.Many2one('stock.production.lot', string='Transfer No.') 
    main_batches=fields.Many2one('mrp.order.batch.number', string='Batch No.')
    quantity=fields.Float('Quanitity')
    avail_quantity=fields.Float('Quantity')
    uom_id=fields.Many2one('product.uom', string='Unit')
    
    approve_quantity =fields.Float('Send to Quality')
    reject_quantity =fields.Float('Send TO Scrap')
    ntype = fields.Selection([('reject','Reject'),('approve','Approved')],string='Type')
    reject_resion=fields.Many2many('quality.reject.reason','quality_batch_reject_resion_rel','quality_id',
        			   'resion_id',string='Reject Reason',help="Rejected resign from quality checking.")
Ejemplo n.º 26
0
class account_invoice(models.Model):
    _inherit = 'account.invoice'

    category_id = fields.Many2many('res.partner.category',
                                   string='Partner Tags')

    @api.multi
    def onchange_partner_id(self,
                            type,
                            partner_id,
                            date_invoice=False,
                            payment_term=False,
                            partner_bank_id=False,
                            company_id=False):
        result = super(account_invoice,
                       self).onchange_partner_id(type, partner_id)
        if partner_id:
            partner = self.env['res.partner'].browse(partner_id)
            partner_tag = partner.category_id.ids or False
            if partner_tag:
                result['value'].update({'category_id': [(6, 0, partner_tag)]})
            else:
                result['value'].update({'category_id': []})
        return result
Ejemplo n.º 27
0
class born_shop_config(models.Model):
    _name = 'born.shop.config'

    name = fields.Char(u'名称')
    template_id = fields.Many2one('born.shop.template', u'模版')
    position_model = fields.Many2many('position.model', string=u'模块位置')
Ejemplo n.º 28
0
class ProductPriceList(osv.osv):
    _name = "product.pricelist"
    _inherit = "product.pricelist"

    user_link_ids = fields.Many2many('res.users',
                                     'pricelist_partner_rel',
                                     'pricelist_id',
                                     'user_id',
                                     required=True)

    def _price_rule_get_multi(self,
                              cr,
                              uid,
                              pricelist,
                              products_by_qty_by_partner,
                              context=None):
        context = context or {}
        date = context.get('date') or time.strftime('%Y-%m-%d')
        date = date[0:10]

        products = map(lambda x: x[0], products_by_qty_by_partner)
        currency_obj = self.pool.get('res.currency')
        product_obj = self.pool.get('product.template')
        product_uom_obj = self.pool.get('product.uom')
        price_type_obj = self.pool.get('product.price.type')

        if not products:
            return {}

        version = False
        for v in pricelist.version_id:
            if ((v.date_start is False) or
                (v.date_start <= date)) and ((v.date_end is False) or
                                             (v.date_end >= date)):
                version = v
                break
        if not version:
            raise osv.except_osv(
                _('Warning!'),
                _("At least one pricelist has no active version !\nPlease create or activate one."
                  ))
        brand_id = {}
        categ_ids = {}
        for p in products:
            categ = p.categ_id
            # BRAND
            if p.product_brand_id:
                brand_id = [p.product_brand_id.id]

            while categ:
                categ_ids[categ.id] = True
                categ = categ.parent_id
        categ_ids = categ_ids.keys()

        is_product_template = products[0]._name == "product.template"
        if is_product_template:
            prod_tmpl_ids = [tmpl.id for tmpl in products]
            # all variants of all products
            prod_ids = [
                p.id for p in list(
                    chain.from_iterable(
                        [t.product_variant_ids for t in products]))
            ]

        else:
            prod_ids = [product.id for product in products]
            prod_tmpl_ids = [
                product.product_tmpl_id.id for product in products
            ]

        # Load all rules. Added brand_id in selection.
        cr.execute(
            'SELECT i.id '
            'FROM product_pricelist_item AS i '
            'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = any(%s)) '
            'AND (product_id IS NULL OR (product_id = any(%s))) '
            'AND ((categ_id IS NULL) OR (categ_id = any(%s))) '
            'AND ((brand_id IS NULL) OR (brand_id = any(%s))) '
            'AND (price_version_id = %s) '
            'ORDER BY sequence, min_quantity desc',
            (prod_tmpl_ids, prod_ids, categ_ids, brand_id, version.id))

        item_ids = [x[0] for x in cr.fetchall()]
        items = self.pool.get('product.pricelist.item').browse(cr,
                                                               uid,
                                                               item_ids,
                                                               context=context)

        price_types = {}

        results = {}
        for product, qty, partner in products_by_qty_by_partner:
            results[product.id] = 0.0
            rule_id = False
            price = False

            # Final unit price is computed according to `qty` in the `qty_uom_id` UoM.
            # An intermediary unit price may be computed according to a different UoM, in
            # which case the price_uom_id contains that UoM.
            # The final price will be converted to match `qty_uom_id`.
            qty_uom_id = context.get('uom') or product.uom_id.id
            price_uom_id = product.uom_id.id
            qty_in_product_uom = qty
            if qty_uom_id != product.uom_id.id:
                try:
                    qty_in_product_uom = product_uom_obj._compute_qty(
                        cr, uid, context['uom'], qty, product.uom_id.id
                        or product.uos_id.id)
                except except_orm:
                    # Ignored - incompatible UoM in context, use default product UoM
                    pass

            for rule in items:

                if rule.brand_id.id and product.product_brand_id.id != rule.brand_id.id:
                    continue

                if rule.min_quantity and qty_in_product_uom < rule.min_quantity:
                    continue
                if is_product_template:
                    if rule.product_tmpl_id and product.id != rule.product_tmpl_id.id:
                        continue
                    if rule.product_id and not (
                            product.product_variant_count == 1
                            and product.product_variant_ids[0].id
                            == rule.product_id.id):
                        # product rule acceptable on template if has only one variant
                        continue
                else:
                    if rule.product_tmpl_id and product.product_tmpl_id.id != rule.product_tmpl_id.id:
                        continue
                    if rule.product_id and product.id != rule.product_id.id:
                        continue

                if rule.categ_id:
                    cat = product.categ_id
                    while cat:
                        if cat.id == rule.categ_id.id:
                            break
                        cat = cat.parent_id
                    if not cat:
                        continue

                if rule.base == -1:
                    if rule.base_pricelist_id:
                        price_tmp = self._price_get_multi(
                            cr,
                            uid,
                            rule.base_pricelist_id, [(product, qty, partner)],
                            context=context)[product.id]
                        ptype_src = rule.base_pricelist_id.currency_id.id
                        price_uom_id = qty_uom_id
                        price = currency_obj.compute(cr,
                                                     uid,
                                                     ptype_src,
                                                     pricelist.currency_id.id,
                                                     price_tmp,
                                                     round=False,
                                                     context=context)
                elif rule.base == -2:
                    seller = False
                    for seller_id in product.seller_ids:
                        if (not partner) or (seller_id.name.id != partner):
                            continue
                        seller = seller_id
                    if not seller:
                        if pricelist.type == 'purchase':
                            continue
                        elif product.seller_ids:
                            seller = product.seller_ids[0]
                    if seller:
                        qty_in_seller_uom = qty
                        seller_uom = seller.product_uom.id
                        if qty_uom_id != seller_uom:
                            qty_in_seller_uom = product_uom_obj._compute_qty(
                                cr, uid, qty_uom_id, qty, to_uom_id=seller_uom)
                        price_uom_id = seller_uom
                        for line in seller.pricelist_ids:
                            if line.min_quantity <= qty_in_seller_uom:
                                price = line.price

                else:
                    if rule.base not in price_types:
                        price_types[rule.base] = price_type_obj.browse(
                            cr, uid, int(rule.base))
                    price_type = price_types[rule.base]

                    # price_get returns the price in the context UoM, i.e. qty_uom_id
                    price_uom_id = qty_uom_id
                    price = currency_obj.compute(
                        cr,
                        uid,
                        price_type.currency_id.id,
                        pricelist.currency_id.id,
                        product_obj._price_get(cr,
                                               uid, [product],
                                               price_type.field,
                                               context=context)[product.id],
                        round=False,
                        context=context)

                if price is not False:
                    price_limit = price
                    price = price * (1.0 + (rule.price_discount or 0.0))
                    if rule.price_round:
                        price = tools.float_round(
                            price, precision_rounding=rule.price_round)

                    convert_to_price_uom = (
                        lambda price: product_uom_obj._compute_price(
                            cr, uid, product.uom_id.id, price, price_uom_id))
                    if rule.price_surcharge:
                        price_surcharge = convert_to_price_uom(
                            rule.price_surcharge)
                        price += price_surcharge

                    if rule.price_min_margin:
                        price_min_margin = convert_to_price_uom(
                            rule.price_min_margin)
                        price = max(price, price_limit + price_min_margin)

                    if rule.price_max_margin:
                        price_max_margin = convert_to_price_uom(
                            rule.price_max_margin)
                        price = min(price, price_limit + price_max_margin)

                    rule_id = rule.id
                    break

            # Final price conversion to target UoM
            price = product_uom_obj._compute_price(cr, uid, price_uom_id,
                                                   price, qty_uom_id)

            results[product.id] = (price, rule_id)

        return results
Ejemplo n.º 29
0
class ResUsers(models.Model):
    _inherit = 'res.users'

    pricelist_ids = fields.Many2many('product.pricelist',
                                     'pricelist_partner_rel', 'user_id',
                                     'pricelist_id')
Ejemplo n.º 30
0
class wiz_accommodation_employee_report(models.TransientModel):
    
    _name = 'wiz.accommodation.employee.report'
    
    accommodation_ids = fields.Many2many('accommodation.accommodation', 'wiz_accommodation_rel', 'accommodation_id', 'wizard_id', 'Accommodation')
    
    @api.multi
    def print_report(self):
        
        cr, uid, context = self.env.args
        context = dict(context)
        
        fl = StringIO()
        workbook = xlwt.Workbook()
        worksheet = workbook.add_sheet('Sheet 1')
        font = xlwt.Font()
        font.bold = True
        header1 = xlwt.easyxf('font: bold on, height 200;borders : top thin, bottom thin, left thin, right thin;align: wrap off , vert centre, horiz left;')
        head_bck_yellow = xlwt.easyxf('font: bold on, height 220;borders : top thin, bottom thin, left thin, right thin;pattern: pattern solid, fore_colour light_yellow;align: wrap on , vert centre, horiz center;')
        header2 = xlwt.easyxf('font: height 180;borders : top thin, bottom thin, left thin, right thin;align: wrap on , vert centre, horiz left;')
        
        wiz_rec = self.browse(self._ids[0])
        comp_obj = self.env['res.company']
        acc_obj = self.env['accommodation.accommodation']
        bed_obj = self.env['beds.beds']
        companies = {}
        dict_val = {}
        company_ids = comp_obj.search([('tenant', '=', True)])
        for comp in company_ids:
            companies.update(dict([(comp.id, comp.code)]))
        new_lst = []
        for accom in wiz_rec.accommodation_ids:
            accommodation = False
            accom_dict = {'sr_no' : accom.name,
                    'acc_name' : '',
                    'country':'',
                    'tenant':'',
                    'max':'',
                    'occupied':'',
                    'available':'',
                    'accom' : 1,
                    'room' : 0}
            count = 0
            for room in accom.room_ids:
                count += 1
                visa_dict = {}
                
                for visa in room.visa_quota_ids:
                    company_dict = {}
                    country_comp_total = 0
                    for company_id in company_ids:
                        visa_nat_id = visa.nationality_id.id
                        bed_ids_filled = bed_obj.search([
                            ('room_id', '=', room.id),
                            ('employee_id', '!=', False),
                            ('employee_id.company_id', '=', company_id.id),
                            ('employee_id.emp_country_id', '=', visa_nat_id)
                        ])
                        country_comp_total += len(bed_ids_filled)
                        company_dict[companies.get(company_id.id)] = len(bed_ids_filled)
                    company_dict['total'] = country_comp_total
                    visa_dict[visa.nationality_id.name] = company_dict
                new_dict = {
                    'sr_no' : count,
                    'acc_name' : room.name,
                    'landlord':'',
                    'tenant':accom.paying_comp_id.code,
                    'max':len(room.bed_ids),
                    'occupied':len(room.bed_ids) - room.available_beds,
                    'available':room.available_beds,
                    'accom' : 0,
                    'room' : 1
                    }
                flag = 0
                for key, val in visa_dict.iteritems():
                    if not accommodation:
                        new_lst.append(accom_dict)
                        accommodation = True
                    if not flag:
                        new_dict['country'] = key
                        new_dict.update(val)
                        flag = True
                        new_lst.append(new_dict)
                    else:
                        country_dict = {}
                        country_dict['country'] = key
                        country_dict.update(val)
                        country_dict.update(
                                {'sr_no' : '',
                                'acc_name' : '',
                                'landlord':'',
                                'tenant':'',
                                'max':'',
                                'occupied':'',
                                'available':'',
                                'accom' : 0,
                                'room' : 0
                                })
                        new_lst.append(country_dict)
                country_lst_len = len(new_lst)
        datas = {
            'form': new_lst,
            }
    
        row = 0
        worksheet.col(3).width = 5000
        
        worksheet.write_merge(row, row + 1, 0, 0, 'S.No', head_bck_yellow)
        worksheet.write_merge(row, row + 1, 1, 1, 'COM', head_bck_yellow)
        worksheet.write_merge(row, row + 1, 2, 2, 'Location / Address', head_bck_yellow)
        worksheet.write_merge(row, row + 1, 3, 3, 'Nationality', head_bck_yellow)
        worksheet.write_merge(row, row , 4, 9, 'Occupant (Company Wise)', head_bck_yellow)
        worksheet.write(row + 1, 4, 'CM', head_bck_yellow)
        worksheet.write(row + 1, 5, 'DV', head_bck_yellow)
        worksheet.write(row + 1, 6, 'SME', head_bck_yellow)
        worksheet.write(row + 1, 7, 'UM', head_bck_yellow)
        worksheet.write(row + 1, 8, 'SBT', head_bck_yellow)
        worksheet.write(row + 1, 9, 'TOTAL', head_bck_yellow)
        worksheet.write_merge(row, row + 1, 10, 10, 'Stay Men', head_bck_yellow)
        worksheet.write_merge(row, row + 1, 11, 11, 'Max. Capacity', head_bck_yellow)
        worksheet.write_merge(row, row + 1, 12, 12, 'Vacancies', head_bck_yellow)
    
        row += 2
        for lst in new_lst:
            if lst['accom'] == True:
                worksheet.write_merge(row, row + 1, 0, 12, lst['sr_no'], header1)
                row += 2
                if lst['room'] == True:
                    worksheet.write(row, 0, lst['sr_no'] , header2)
                    worksheet.write(row, 1, lst['tenant'] , header2)
                    worksheet.write(row, 2, lst['acc_name'] , header2)
                    worksheet.write(row, 3, lst['country'] , header2)
                    worksheet.write(row, 4, lst.get('CM') , header2)
                    worksheet.write(row, 5, lst.get('DV') , header2)
                    worksheet.write(row, 6, lst.get('SME') , header2)
                    worksheet.write(row, 7, lst.get('UM') , header2)
                    worksheet.write(row, 8, lst.get('SBT') , header2)
                    worksheet.write(row, 9, lst.get('total') , header2)
                    worksheet.write(row, 10, lst['occupied'] , header2)
                    worksheet.write(row, 11, lst['max'] , header2)
                    worksheet.write(row, 12, lst['available'] , header2)
                    
                    row += 1
                
            if lst['accom'] == False:
                worksheet.write(row, 0, lst['sr_no'] , header2)
                worksheet.write(row, 1, lst['tenant'] , header2)
                worksheet.write(row, 2, lst['acc_name'] , header2)
                worksheet.write(row, 3, lst['country'] , header2)
                worksheet.write(row, 4, lst.get('CM') , header2)
                worksheet.write(row, 5, lst.get('DV') , header2)
                worksheet.write(row, 6, lst.get('SME') , header2)
                worksheet.write(row, 7, lst.get('UM') , header2)
                worksheet.write(row, 8, lst.get('SBT') , header2)
                worksheet.write(row, 9, lst.get('total') , header2)
                worksheet.write(row, 10, lst['occupied'] , header2)
                worksheet.write(row, 11, lst['max'] , header2)
                worksheet.write(row, 12, lst['available'] , header2)
                
                row += 1
                
        workbook.save(fl)
        fl.seek(0)
        buf = base64.encodestring(fl.read())
        ctx = dict(context)
        ctx.update({'file': buf})
        
        return {
                'type': 'ir.actions.act_window',
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'acco.location.report',
                'target': 'new',
                'context': ctx,
                }