delete = cr.execute('delete from shop_prod_rel where prod_id=%s and shop_id=%s',(each_list_product,ids[0]))
              list_message = _("%s product relisted successfully on ebay") % product_name
              self.log(cr, uid,increment, list_message)
        return
    def onchange_listing_type(self,cr,uid,ids,type):
        result = {}
        if type:
            search_duration = self.pool.get('duration.time').search(cr,uid,[('type','=',type)])
            if search_duration:
                result['list_durtn'] = search_duration[0]
        return{'value':result}
    _rec_name = 'shop_id'
    _columns = {
#        'name' :fields.char('Name',size=64),
       'shop_id' : fields.many2one('sale.shop','Ebay Shop',required=True,help="Shop on which products to be relisted"),
       'rel_prod' : fields.many2many('product.product','shop_prod_rel','shop_id','prod_id','List of Expired Products'),
       'schedule_time':fields.datetime('Schedule Time'),
       'list_durtn' : fields.many2one('duration.time','Duration',required=True,help="Duration Of the Product on Ebay"),
       'template_id': fields.many2one('ebayerp.template','Template',required=True,help="Selected Template Configuration will be applied to the Listing Products"),
       'ebay_current_time':fields.datetime('Ebay Current Time'),
       'type': fields.selection([('Chinese','Auction'),('FixedPriceItem','Fixed Price'),('LeadGeneration','Classified Ad')],'Type',required=True,help="Type in which Products to be listed"),
       'start_price':fields.many2one('product.pricelist','Start Price',help="Selected Pricelist will be applied to the Listing Products"),
       'reserve_price':fields.many2one('product.pricelist','Reserve Price',help="Selected Pricelist will be applied to the Listing Products"),
       'buy_it_nw':fields.many2one('product.pricelist','Buy It Now Price',help="Selected Pricelist will be applied to the Listing Products"),
       'condtn':fields.selection([('1000','New'),('1500','New other (see details)'),('2000','Manufacturer refurbished'),('2500','Seller refurbished'),('3000','Used'),('7000','For parts or not working')],'Condition'),
       'inst_list_chk' : fields.boolean('Start listing immediately',help="Will Active Product Immediately on Ebay"),
    }
    _defaults = {
        'type': 'Chinese',
        'inst_list_chk':True,
        'start_price':1,
class wizard_registro_iva(osv.osv_memory):
    def _get_period(self, cr, uid, context=None):
        ctx = dict(context or {}, account_period_prefer_normal=True)
        period_ids = self.pool.get('account.period').find(cr, uid, context=ctx)
        return period_ids

    _name = "wizard.registro.iva"
    _columns = {
        'period_ids':
        fields.many2many(
            'account.period',
            'registro_iva_periods_rel',
            'period_id',
            'registro_id',
            'Periods',
            help='Select periods you want retrieve documents from',
            required=True),
        'type':
        fields.selection([
            ('customer', 'Customer Invoices'),
            ('supplier', 'Supplier Invoices'),
            ('corrispettivi', 'Corrispettivi'),
        ],
                         'Layout',
                         required=True),
        'journal_ids':
        fields.many2many(
            'account.journal',
            'registro_iva_journals_rel',
            'journal_id',
            'registro_id',
            'Journals',
            help='Select journals you want retrieve documents from',
            required=True),
        'tax_sign':
        fields.float(
            'Tax amount sign',
            help=
            "Use -1 you have negative tax amounts and you want to print them prositive"
        ),
        'message':
        fields.char('Message', size=64, readonly=True),
        'fiscal_page_base':
        fields.integer('Last printed page', required=True),
    }
    _defaults = {
        'type': 'customer',
        'period_ids': _get_period,
        'tax_sign': 1.0,
        'fiscal_page_base': 0,
    }

    def print_registro(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        wizard = self.browse(cr, uid, ids)[0]
        move_obj = self.pool.get('account.move')
        obj_model_data = self.pool.get('ir.model.data')
        move_ids = move_obj.search(
            cr,
            uid, [
                ('journal_id', 'in', [j.id for j in wizard.journal_ids]),
                ('period_id', 'in', [p.id for p in wizard.period_ids]),
                ('state', '=', 'posted'),
            ],
            order='date, name')
        if not move_ids:
            self.write(
                cr, uid, ids,
                {'message': _('No documents found in the current selection')})
            model_data_ids = obj_model_data.search(
                cr, uid, [('model', '=', 'ir.ui.view'),
                          ('name', '=', 'wizard_registro_iva')])
            resource_id = obj_model_data.read(cr,
                                              uid,
                                              model_data_ids,
                                              fields=['res_id'])[0]['res_id']
            return {
                'name': _('No documents'),
                'res_id': ids[0],
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'wizard.registro.iva',
                'views': [(resource_id, 'form')],
                'context': context,
                'type': 'ir.actions.act_window',
                'target': 'new',
            }
        datas = {'ids': move_ids}
        datas['model'] = 'account.move'
        datas['fiscal_page_base'] = wizard.fiscal_page_base
        datas['period_ids'] = [p.id for p in wizard.period_ids]
        datas['layout'] = wizard['type']
        datas['tax_sign'] = wizard['tax_sign']
        res = {
            'type': 'ir.actions.report.xml',
            'datas': datas,
        }
        if wizard['type'] == 'customer':
            res['report_name'] = 'registro_iva_vendite'
        elif wizard['type'] == 'supplier':
            res['report_name'] = 'registro_iva_acquisti'
        elif wizard['type'] == 'corrispettivi':
            res['report_name'] = 'registro_iva_corrispettivi'
        return res

    def on_type_changed(self, cr, uid, ids, j_type, context=None):
        res = {}
        if j_type:
            if j_type == 'supplier':
                res['value'] = {'tax_sign': -1}
            else:
                res['value'] = {'tax_sign': 1}
        return res
Esempio n. 3
0
class hotel_reservation(osv.osv):
    _name = "hotel.reservation"
    _rec_name = "reservation_no"
    _description = "Reservation"
    _columns = {
                
                'reservation_no': fields.char('Reservation No', size=64, required=True, select=True),
                'date_order':fields.datetime('Date Ordered', required=True, readonly=True, states={'draft':[('readonly',False)]}),
                'shop_id':fields.many2one('sale.shop', 'Shop', required=True, readonly=True, states={'draft':[('readonly',False)]}),      
                'partner_id':fields.many2one('res.partner', 'Guest Name', required=True,readonly=True, states={'draft':[('readonly',False)]}),
                'pricelist_id':fields.many2one('product.pricelist', 'Pricelist', required=True,readonly=True, states={'draft':[('readonly',False)]}),
                'partner_invoice_id':fields.many2one('res.partner.address', 'Invoice Address', readonly=True, required=True, states={'draft':[('readonly',False)]}),
                'partner_order_id':fields.many2one('res.partner.address', 'Ordering Contact', readonly=True, required=True, states={'draft':[('readonly',False)]}, help="The name and address of the contact that requested the order or quotation."),
                'partner_shipping_id':fields.many2one('res.partner.address', 'Shipping Address', readonly=True, required=True, states={'draft':[('readonly',False)]}),
                'checkin': fields.datetime('Expected-Date-Arrival',required=True,readonly=True, states={'draft':[('readonly',False)]}),
                'checkout': fields.datetime('Expected-Date-Departure',required=True, readonly=True, states={'draft':[('readonly',False)]}),
                'adults':fields.integer('Adults',size=64,readonly=True, states={'draft':[('readonly',False)]}),
                'childs':fields.integer('Children',size=64,readonly=True, states={'draft':[('readonly',False)]}),             
                'reservation_line':fields.one2many('hotel_reservation.line','line_id','Reservation Line'),
                'state': fields.selection([('draft', 'Draft'),('confirm','Confirm'),('cancle','Cancle'),('done','Done')], 'State',readonly=True),
                'folio_id': fields.many2many('hotel.folio', 'hotel_folio_reservation_rel', 'order_id', 'invoice_id', 'Folio'),
                'dummy': fields.datetime('Dummy'),
               
        }
    _defaults = {
       
        'reservation_no': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid,'hotel.reservation'),
        'state': lambda *a: 'draft', 
        'date_order': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'), 
         
       }
    def on_change_checkout(self,cr, uid, ids, checkin_date=time.strftime('%Y-%m-%d %H:%M:%S'),checkout_date=time.strftime('%Y-%m-%d %H:%M:%S'),context=None):
        delta = datetime.timedelta(days=1)
        addDays = datetime.datetime(*time.strptime(checkout_date,'%Y-%m-%d %H:%M:%S')[:5]) + delta
        val = {'value':{'dummy':addDays.strftime('%Y-%m-%d %H:%M:%S')}}
        return val
        
    def onchange_partner_id(self, cr, uid, ids, part):
        if not part:
            return {'value':{'partner_invoice_id': False, 'partner_shipping_id':False, 'partner_order_id':False}}
        addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['delivery','invoice','contact'])
        pricelist = self.pool.get('res.partner').browse(cr, uid, part).property_product_pricelist.id
        return {'value':{'partner_invoice_id': addr['invoice'], 'partner_order_id':addr['contact'], 'partner_shipping_id':addr['delivery'], 'pricelist_id': pricelist}}
    
     
    def confirmed_reservation(self,cr,uid,ids):
         
         for reservation in self.browse(cr, uid, ids):
             cr.execute("select count(*) from hotel_reservation as hr " \
                        "inner join hotel_reservation_line as hrl on hrl.line_id = hr.id " \
                        "inner join hotel_reservation_line_room_rel as hrlrr on hrlrr.room_id = hrl.id " \
                        "where (checkin,checkout) overlaps ( timestamp %s , timestamp %s ) " \
                        "and hr.id <> cast(%s as integer) " \
                        "and hr.state = 'confirm' " \
                        "and hrlrr.hotel_reservation_line_id in (" \
                        "select hrlrr.hotel_reservation_line_id from hotel_reservation as hr " \
                        "inner join hotel_reservation_line as hrl on hrl.line_id = hr.id " \
                        "inner join hotel_reservation_line_room_rel as hrlrr on hrlrr.room_id = hrl.id " \
                        "where hr.id = cast(%s as integer) )" \
                        ,(reservation.checkin,reservation.checkout,str(reservation.id),str(reservation.id))
                        )
             res = cr.fetchone()
             roomcount =  res and res[0] or 0.0
             if roomcount:
                 raise osv.except_osv('Warning', 'You tried to confirm reservation with room those already reserved in this reservation period')
             else:
                 
                 self.write(cr, uid, ids, {'state':'confirm'})
             return True
    
    def _create_folio(self,cr,uid,ids):
        for reservation in self.browse(cr,uid,ids):
            for line in reservation.reservation_line:
                 for r in line.reserve:
                    folio=self.pool.get('hotel.folio').create(cr,uid,{
                                                                      'date_order':reservation.date_order,
                                                                      'shop_id':reservation.shop_id.id,
                                                                      'partner_id':reservation.partner_id.id,
                                                                      'pricelist_id':reservation.pricelist_id.id,
                                                                      'partner_invoice_id':reservation.partner_invoice_id.id,
                                                                      'partner_order_id':reservation.partner_order_id.id,
                                                                      'partner_shipping_id':reservation.partner_shipping_id.id,
                                                                      'checkin_date': reservation.checkin,
                                                                      'checkout_date': reservation.checkout,
                                                                      'room_lines': [(0,0,{'folio_id':line['id'],
                                                                                           'checkin_date':reservation['checkin'],
                                                                                           'checkout_date':reservation['checkout'],
                                                                                           'product_id':r['id'], 
                                                                                           'name':reservation['reservation_no'],
                                                                                           'product_uom':r['uom_id'].id,
                                                                                           'price_unit':r['lst_price'],
                                                                                           'product_uom_qty':(datetime.datetime(*time.strptime(reservation['checkout'],'%Y-%m-%d %H:%M:%S')[:5]) - datetime.datetime(*time.strptime(reservation['checkin'],'%Y-%m-%d %H:%M:%S')[:5])).days   
                                                                                           
                                                                                           })],
                                                                     'service_lines':reservation['folio_id']     
                                                                       })
            cr.execute('insert into hotel_folio_reservation_rel (order_id,invoice_id) values (%s,%s)', (reservation.id, folio))
            self.write(cr, uid, ids, {'state':'done'})
        return True
class account_bank_statement_line(osv.osv):
    def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
        obj_partner = self.pool.get('res.partner')
        if context is None:
            context = {}
        if not partner_id:
            return {}
        part = obj_partner.browse(cr, uid, partner_id, context=context)
        if not part.supplier and not part.customer:
            type = 'general'
        elif part.supplier and part.customer:
            type = 'general'
        else:
            if part.supplier == True:
                type = 'supplier'
            if part.customer == True:
                type = 'customer'
        res_type = self.onchange_type(cr,
                                      uid,
                                      ids,
                                      partner_id=partner_id,
                                      type=type,
                                      context=context)
        if res_type['value'] and res_type['value'].get('account_id', False):
            return {
                'value': {
                    'type': type,
                    'account_id': res_type['value']['account_id']
                }
            }
        return {'value': {'type': type}}

    def onchange_type(self, cr, uid, line_id, partner_id, type, context=None):
        res = {'value': {}}
        obj_partner = self.pool.get('res.partner')
        if context is None:
            context = {}
        if not partner_id:
            return res
        account_id = False
        line = self.browse(cr, uid, line_id, context=context)
        if not line or (line and not line[0].account_id):
            part = obj_partner.browse(cr, uid, partner_id, context=context)
            if type == 'supplier':
                account_id = part.property_account_payable.id
            else:
                account_id = part.property_account_receivable.id
            res['value']['account_id'] = account_id
        return res

    def _get_running_balance(self, cr, uid, ids, name, args, context):
        res = {}
        for line in self.browse(cr, uid, ids, context=context):
            res[line.id] = 0
            statement = line.statement_id
            running_balance = statement.balance_start
            for st_line in statement.line_ids:
                running_balance += st_line.amount
                if st_line.id == line.id:
                    res[line.id] = running_balance
                    break
        return res

    _name = "account.bank.statement.line"
    _description = "Bank Statement Line"
    _columns = {
        'name':
        fields.char('Communication', size=64, required=True),
        'date':
        fields.date('Date', required=True),
        'amount':
        fields.float('Amount', digits_compute=dp.get_precision('Account')),
        'type':
        fields.selection([('supplier', 'Supplier'), ('customer', 'Customer'),
                          ('general', 'General')],
                         'Type',
                         required=True),
        'partner_id':
        fields.many2one('res.partner', 'Partner'),
        'account_id':
        fields.many2one('account.account', 'Account', required=True),
        'statement_id':
        fields.many2one('account.bank.statement',
                        'Statement',
                        select=True,
                        required=True,
                        ondelete='cascade'),
        'analytic_account_id':
        fields.many2one('account.analytic.account', 'Analytic Account'),
        'move_ids':
        fields.many2many('account.move',
                         'account_bank_statement_line_move_rel',
                         'statement_line_id', 'move_id', 'Moves'),
        'ref':
        fields.char('Reference', size=32),
        'note':
        fields.text('Notes'),
        'running_balance':
        fields.function(_get_running_balance,
                        method=True,
                        string="Running Balance"),
        'sequence':
        fields.integer(
            'Sequence',
            select=True,
            help=
            "Gives the sequence order when displaying a list of bank statement lines."
        ),
        'company_id':
        fields.related('statement_id',
                       'company_id',
                       type='many2one',
                       relation='res.company',
                       string='Company',
                       store=True,
                       readonly=True),
    }
    _defaults = {
        #        'name': lambda self,cr,uid,context={}: self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement.line'),
        'name': '/',
        'date': lambda self, cr, uid, context={}: context.get(
            'date', fields.date.context_today(self, cr, uid, context=context)),
        'type': 'general',
    }

    _order = "statement_id desc, date, id"
class gate_pass_register_wiz(osv.osv_memory):

    _name = 'gate.pass.register.wiz'
    _columns = {
        'dep_id':
        fields.many2many('kg.depmaster', 'gate_pass_reg', 'wiz_id', 'dep_id',
                         'Department Name'),
        'filter':
        fields.selection([('filter_no', 'No Filters'),
                          ('filter_date', 'Date')],
                         "Filter by",
                         required=True),
        'product_type':
        fields.selection([('consu', 'Consumable Items'),
                          ('cap', 'Capital Goods'),
                          ('service', 'Service Items')], 'Product Type'),
        'date_from':
        fields.date("Start Date"),
        'date_to':
        fields.date("End Date"),
        'product':
        fields.many2many('product.product', 'gate_pass_reg_product',
                         'product_wiz_id', 'product_dep_id', 'Product'),
        'company_id':
        fields.many2one('res.company', 'Company Name'),
        'print_date':
        fields.datetime('Creation Date', readonly=True),
        'printed_by':
        fields.many2one('res.users', 'Printed By', readonly=True),
        'status':
        fields.selection([('delivered', 'Delivered'),
                          ('cancelled', 'Cancelled')], "Status"),
    }

    _defaults = {
        'filter':
        'filter_date',
        'date_from':
        time.strftime('%Y-%m-%d'),
        'date_to':
        time.strftime('%Y-%m-%d'),
        'print_date':
        fields.datetime.now,
        'printed_by':
        lambda obj, cr, uid, context: uid,
        'company_id':
        lambda self, cr, uid, c: self.pool.get('res.company').
        _company_default_get(cr, uid, 'gate.pass.register.wiz', context=c),
    }

    def _date_validation_check(self, cr, uid, ids, context=None):
        for val_date in self.browse(cr, uid, ids, context=context):
            if val_date.date_from <= val_date.date_to:
                return True
        return False

    _constraints = [
        (_date_validation_check,
         'You must select an correct Start Date and End Date !!',
         ['Valid_date']),
    ]

    def _build_contexts(self, cr, uid, ids, data, context=None):
        print "_build_contexts data ^^^^^^^^^^^^^^^^^^^^^^^^", data
        if context is None:
            context = {}
        result = {}
        result['date_from'] = 'date_from' in data['form'] and data['form'][
            'date_from'] or False
        result['date_to'] = 'date_to' in data['form'] and data['form'][
            'date_to'] or False
        if data['form']['filter'] == 'filter_date':
            result['date_from'] = data['form']['date_from']
            result['date_to'] = data['form']['date_to']
        return result

    def date_indian_format(self, date_pyformat):
        date_contents = date_pyformat.split("-")
        date_indian = date_contents[2] + "/" + date_contents[
            1] + "/" + date_contents[0]
        return date_indian

    def check_report(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        data = {}
        data['ids'] = context.get('active_ids', [])
        data['model'] = context.get('active_model', 'ir.ui.menu')
        data['form'] = self.read(cr, uid, ids, [])[0]
        used_context = self._build_contexts(cr,
                                            uid,
                                            ids,
                                            data,
                                            context=context)
        data['form']['used_context'] = used_context
        return self._print_report(cr, uid, ids, data, context=context)

    def pre_print_report(self, cr, uid, ids, data, context=None):
        if context is None:
            context = {}
        data['form'].update(self.read(cr, uid, ids, [], context=context)[0])
        return data

    def _print_report(self, cr, uid, ids, data, context=None):
        rec = self.browse(cr, uid, ids[0])
        if context is None:
            context = {}
        data = self.pre_print_report(cr, uid, ids, data, context=context)
        print "data..................,,,,,,,,,,,,,,", data
        data['form'].update(self.read(cr, uid, ids[0]))
        if data['form']:
            date_from = str(data['form']['date_from'])
            date_to = str(data['form']['date_to'])
            data['form']['date_from_ind'] = self.date_indian_format(date_from)
            data['form']['date_to_ind'] = self.date_indian_format(date_to)

            company_id = data['form']['company_id'][0]
            com_rec = self.pool.get('res.company').browse(cr, uid, company_id)
            data['form']['company'] = com_rec.name
            data['form']['printed_by'] = rec.printed_by.name

            if data['form']['status'] == 'delivered':
                data['form']['status_name'] = 'Delivered'

            elif data['form']['status'] == 'cancelled':
                data['form']['status_name'] = 'Cancelled'
            else:
                data['form']['status_name'] = 'Delivered'

            cr_date = datetime.strptime(rec.print_date, '%Y-%m-%d %H:%M:%S')
            date = cr_date.strftime('%d/%m/%Y %H:%M:%S')
            data['form']['print_date'] = date
            return {
                'type': 'ir.actions.report.xml',
                'report_name': 'gate.pass.register',
                'datas': data,
                'name': 'Gate Pass Register'
            }
 'pem_cc':fields.char(
                 ' CC',
                 size=250),
 'pem_bcc':fields.char(
                 ' BCC',
                 size=250),
 'pem_subject':fields.char(
                 ' Subject',
                 size=200,),
 'pem_body_text':fields.text(
                 'Standard Body (Text)'),
 'pem_body_html':fields.text(
                 'Body (Text-Web Client Only)'),
 'pem_attachments_ids':fields.many2many(
                 'ir.attachment',
                 'mail_attachments_rel',
                 'mail_id',
                 'att_id',
                 'Attachments'),
 'pem_account_id' :fields.many2one(
                 'poweremail.core_accounts',
                 'User account',
                 required=True),
 'pem_user':fields.related(
                 'pem_account_id',
                 'user',
                 type="many2one",
                 relation="res.users",
                 string="User"),
 'server_ref':fields.integer(
                 'Server Reference of mail',
                 help="Applicable for inward items only."),
Esempio n. 7
0
class hr_employee(osv.osv):
    _name = "hr.employee"
    _description = "Employee"
    _inherits = {'resource.resource': "resource_id"}
    _columns = {
        'country_id':
        fields.many2one('res.country', 'Nationality'),
        'birthday':
        fields.date("Date of Birth"),
        'ssnid':
        fields.char('SSN No', size=32, help='Social Security Number'),
        'sinid':
        fields.char('SIN No', size=32, help="Social Insurance Number"),
        'identification_id':
        fields.char('Identification No', size=32),
        'gender':
        fields.selection([('male', 'Male'), ('female', 'Female')], 'Gender'),
        'marital':
        fields.many2one('hr.employee.marital.status', 'Marital Status'),
        'department_id':
        fields.many2one('hr.department', 'Department'),
        'address_id':
        fields.many2one('res.partner.address', 'Working Address'),
        'address_home_id':
        fields.many2one('res.partner.address', 'Home Address'),
        'partner_id':
        fields.related(
            'address_home_id',
            'partner_id',
            type='many2one',
            relation='res.partner',
            readonly=True,
            help=
            "Partner that is related to the current employee. Accounting transaction will be written on this partner belongs to employee."
        ),
        'bank_account_id':
        fields.many2one('res.partner.bank',
                        'Bank Account Number',
                        domain="[('partner_id','=',partner_id)]",
                        help="Employee bank salary account"),
        'work_phone':
        fields.char('Work Phone', size=32, readonly=False),
        'mobile_phone':
        fields.char('Mobile', size=32, readonly=False),
        'work_email':
        fields.char('Work E-mail', size=240),
        'work_location':
        fields.char('Office Location', size=32),
        'notes':
        fields.text('Notes'),
        'parent_id':
        fields.related('department_id',
                       'manager_id',
                       relation='hr.employee',
                       string='Manager',
                       type='many2one',
                       store=True,
                       select=True,
                       readonly=True,
                       help="It is linked with manager of Department"),
        'category_ids':
        fields.many2many('hr.employee.category', 'employee_category_rel',
                         'category_id', 'emp_id', 'Category'),
        'child_ids':
        fields.one2many('hr.employee', 'parent_id', 'Subordinates'),
        'resource_id':
        fields.many2one('resource.resource',
                        'Resource',
                        ondelete='cascade',
                        required=True),
        'coach_id':
        fields.many2one('hr.employee', 'Coach'),
        'job_id':
        fields.many2one('hr.job', 'Job'),
        'photo':
        fields.binary('Photo'),
        'passport_id':
        fields.char('Passport No', size=64)
    }

    def onchange_address_id(self, cr, uid, ids, address, context=None):
        if address:
            address = self.pool.get('res.partner.address').browse(
                cr, uid, address, context=context)
            return {
                'value': {
                    'work_email': address.email,
                    'work_phone': address.phone
                }
            }
        return {'value': {}}

    def onchange_company(self, cr, uid, ids, company, context=None):
        address_id = False
        if company:
            company_id = self.pool.get('res.company').browse(cr,
                                                             uid,
                                                             company,
                                                             context=context)
            address = self.pool.get('res.partner').address_get(
                cr, uid, [company_id.partner_id.id], ['default'])
            address_id = address and address['default'] or False
        return {'value': {'address_id': address_id}}

    def onchange_user(self, cr, uid, ids, user_id, context=None):
        work_email = False
        if user_id:
            work_email = self.pool.get('res.users').browse(
                cr, uid, user_id, context=context).user_email
        return {'value': {'work_email': work_email}}

    def _get_photo(self, cr, uid, context=None):
        photo_path = addons.get_module_resource('hr', 'images', 'photo.png')
        return open(photo_path, 'rb').read().encode('base64')

    _defaults = {
        'active':
        1,
        'photo':
        _get_photo,
        'address_id':
        lambda self, cr, uid, c: self.pool.get('res.partner.address').browse(
            cr, uid, uid, c).partner_id.id
    }

    def _check_recursion(self, cr, uid, ids, context=None):
        level = 100
        while len(ids):
            cr.execute(
                'SELECT DISTINCT parent_id FROM hr_employee WHERE id IN %s AND parent_id!=id',
                (tuple(ids), ))
            ids = filter(None, map(lambda x: x[0], cr.fetchall()))
            if not level:
                return False
            level -= 1
        return True

    def _check_department_id(self, cr, uid, ids, context=None):
        for emp in self.browse(cr, uid, ids, context=context):
            if emp.department_id.manager_id and emp.id == emp.department_id.manager_id.id:
                return False
        return True

    _constraints = [
        (_check_recursion,
         'Error ! You cannot create recursive Hierarchy of Employees.',
         ['parent_id']),
        (_check_department_id,
         'Error ! You cannot select a department for which the employee is the manager.',
         ['department_id']),
    ]
class res_partner(osv.osv):
    _description = 'Partner'
    _name = "res.partner"
    _order = "name"
    _columns = {
        'name':
        fields.char('Name', size=128, required=True, select=True),
        'date':
        fields.date('Date', select=1),
        'title':
        fields.many2one('res.partner.title', 'Partner Firm'),
        'parent_id':
        fields.many2one('res.partner', 'Parent Partner'),
        'child_ids':
        fields.one2many('res.partner', 'parent_id', 'Partner Ref.'),
        'ref':
        fields.char('Reference', size=64, select=1),
        'lang':
        fields.selection(
            _lang_get,
            'Language',
            help=
            "If the selected language is loaded in the system, all documents related to this partner will be printed in this language. If not, it will be english."
        ),
        'user_id':
        fields.many2one(
            'res.users',
            'Salesman',
            help=
            'The internal user that is in charge of communicating with this partner if any.'
        ),
        'vat':
        fields.char(
            'VAT',
            size=32,
            help=
            "Value Added Tax number. Check the box if the partner is subjected to the VAT. Used by the VAT legal statement."
        ),
        'bank_ids':
        fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
        'website':
        fields.char('Website', size=64, help="Website of Partner."),
        'comment':
        fields.text('Notes'),
        'address':
        fields.one2many('res.partner.address', 'partner_id', 'Contacts'),
        'category_id':
        fields.many2many('res.partner.category', 'res_partner_category_rel',
                         'partner_id', 'category_id', 'Categories'),
        'events':
        fields.one2many('res.partner.event', 'partner_id', 'Events'),
        'credit_limit':
        fields.float(string='Credit Limit'),
        'ean13':
        fields.char('EAN13', size=13),
        'active':
        fields.boolean('Active'),
        'customer':
        fields.boolean('Customer',
                       help="Check this box if the partner is a customer."),
        'supplier':
        fields.boolean(
            'Supplier',
            help=
            "Check this box if the partner is a supplier. If it's not checked, purchase people will not see it when encoding a purchase order."
        ),
        'city':
        fields.related('address', 'city', type='char', string='City'),
        'function':
        fields.related('address', 'function', type='char', string='function'),
        'subname':
        fields.related('address', 'name', type='char', string='Contact Name'),
        'phone':
        fields.related('address', 'phone', type='char', string='Phone'),
        'mobile':
        fields.related('address', 'mobile', type='char', string='Mobile'),
        'country':
        fields.related('address',
                       'country_id',
                       type='many2one',
                       relation='res.country',
                       string='Country'),
        'employee':
        fields.boolean('Employee',
                       help="Check this box if the partner is an Employee."),
        'email':
        fields.related('address',
                       'email',
                       type='char',
                       size=240,
                       string='E-mail'),
        'company_id':
        fields.many2one('res.company', 'Company', select=1),
        'color':
        fields.integer('Color Index'),
    }

    def _default_category(self, cr, uid, context=None):
        if context is None:
            context = {}
        if 'category_id' in context and context['category_id']:
            return [context['category_id']]
        return []

    _defaults = {
        'active':
        lambda *a: 1,
        'customer':
        lambda *a: 1,
        'category_id':
        _default_category,
        'company_id':
        lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(
            cr, uid, 'res.partner', context=c),
        'color':
        0,
    }

    def copy(self, cr, uid, id, default=None, context=None):
        if default is None:
            default = {}
        name = self.read(cr, uid, [id], ['name'], context)[0]['name']
        default.update({'name': name + _(' (copy)'), 'events': []})
        return super(res_partner, self).copy(cr, uid, id, default, context)

    def do_share(self, cr, uid, ids, *args):
        return True

    def _check_ean_key(self, cr, uid, ids, context=None):
        for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(
                cr, uid, ids, [
                    'ean13',
                ]):
            thisean = partner_o['ean13']
            if thisean and thisean != '':
                if len(thisean) != 13:
                    return False
                sum = 0
                for i in range(12):
                    if not (i % 2):
                        sum += int(thisean[i])
                    else:
                        sum += 3 * int(thisean[i])
                if math.ceil(sum / 10.0) * 10 - sum != int(thisean[12]):
                    return False
        return True


#   _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]

    def name_get(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        if not len(ids):
            return []
        if context.get('show_ref'):
            rec_name = 'ref'
        else:
            rec_name = 'name'

        res = [(r['id'], r[rec_name])
               for r in self.read(cr, uid, ids, [rec_name], context)]
        return res

    def name_search(self,
                    cr,
                    uid,
                    name,
                    args=None,
                    operator='ilike',
                    context=None,
                    limit=100):
        if not args:
            args = []
        # short-circuit ref match when possible
        if name and operator in ('=', 'ilike', '=ilike', 'like'):
            ids = self.search(cr,
                              uid, [('ref', '=', name)] + args,
                              limit=limit,
                              context=context)
            if ids:
                return self.name_get(cr, uid, ids, context)
        return super(res_partner, self).name_search(cr,
                                                    uid,
                                                    name,
                                                    args,
                                                    operator=operator,
                                                    context=context,
                                                    limit=limit)

    def _email_send(self,
                    cr,
                    uid,
                    ids,
                    email_from,
                    subject,
                    body,
                    on_error=None):
        partners = self.browse(cr, uid, ids)
        for partner in partners:
            if len(partner.address):
                if partner.address[0].email:
                    tools.email_send(email_from, [partner.address[0].email],
                                     subject, body, on_error)
        return True

    def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
        while len(ids):
            self.pool.get('ir.cron').create(
                cr,
                uid,
                {
                    'name': 'Send Partner Emails',
                    'user_id': uid,
                    #               'nextcall': False,
                    'model': 'res.partner',
                    'function': '_email_send',
                    'args': repr(
                        [ids[:16], email_from, subject, body, on_error])
                })
            ids = ids[16:]
        return True

    def address_get(self, cr, uid, ids, adr_pref=None):
        if adr_pref is None:
            adr_pref = ['default']
        address_obj = self.pool.get('res.partner.address')
        address_ids = address_obj.search(cr, uid, [('partner_id', 'in', ids)])
        address_rec = address_obj.read(cr, uid, address_ids, ['type'])
        res = list((addr['type'], addr['id']) for addr in address_rec)
        adr = dict(res)
        # get the id of the (first) default address if there is one,
        # otherwise get the id of the first address in the list
        if res:
            default_address = adr.get('default', res[0][1])
        else:
            default_address = False
        result = {}
        for a in adr_pref:
            result[a] = adr.get(a, default_address)
        return result

    def gen_next_ref(self, cr, uid, ids):
        if len(ids) != 1:
            return True

        # compute the next number ref
        cr.execute(
            "select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1"
        )
        res = cr.dictfetchall()
        ref = res and res[0]['ref'] or '0'
        try:
            nextref = int(ref) + 1
        except:
            raise osv.except_osv(
                _('Warning'),
                _("Couldn't generate the next id because some partners have an alphabetic id !"
                  ))

        # update the current partner
        cr.execute("update res_partner set ref=%s where id=%s",
                   (nextref, ids[0]))
        return True

    def view_header_get(self, cr, uid, view_id, view_type, context):
        res = super(res_partner, self).view_header_get(cr, uid, view_id,
                                                       view_type, context)
        if res: return res
        if (not context.get('category_id', False)):
            return False
        return _('Partners: ') + self.pool.get('res.partner.category').browse(
            cr, uid, context['category_id'], context).name

    def main_partner(self, cr, uid):
        ''' Return the id of the main partner
        '''
        model_data = self.pool.get('ir.model.data')
        return model_data.browse(
            cr,
            uid,
            model_data.search(cr, uid, [('module', '=', 'base'),
                                        ('name', '=', 'main_partner')])[0],
        ).res_id
class res_partner_category(osv.osv):
    def name_get(self, cr, uid, ids, context=None):
        """Return the categories' display name, including their direct
           parent by default.

        :param dict context: the ``partner_category_display`` key can be
                             used to select the short version of the
                             category name (without the direct parent),
                             when set to ``'short'``. The default is
                             the long version."""
        if context is None:
            context = {}
        if context.get('partner_category_display') == 'short':
            return super(res_partner_category, self).name_get(cr,
                                                              uid,
                                                              ids,
                                                              context=context)
        reads = self.read(cr, uid, ids, ['name', 'parent_id'], context=context)
        res = []
        for record in reads:
            name = record['name']
            if record['parent_id']:
                name = record['parent_id'][1] + ' / ' + name
            res.append((record['id'], name))
        return res

    def name_search(self,
                    cr,
                    uid,
                    name,
                    args=None,
                    operator='ilike',
                    context=None,
                    limit=100):
        if not args:
            args = []
        if not context:
            context = {}
        if name:
            # Be sure name_search is symetric to name_get
            name = name.split(' / ')[-1]
            ids = self.search(cr,
                              uid, [('name', operator, name)] + args,
                              limit=limit,
                              context=context)
        else:
            ids = self.search(cr, uid, args, limit=limit, context=context)
        return self.name_get(cr, uid, ids, context)

    def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
        res = self.name_get(cr, uid, ids, context=context)
        return dict(res)

    _description = 'Partner Categories'
    _name = 'res.partner.category'
    _columns = {
        'name':
        fields.char('Category Name', required=True, size=64, translate=True),
        'parent_id':
        fields.many2one('res.partner.category',
                        'Parent Category',
                        select=True,
                        ondelete='cascade'),
        'complete_name':
        fields.function(_name_get_fnc, type="char", string='Full Name'),
        'child_ids':
        fields.one2many('res.partner.category', 'parent_id',
                        'Child Categories'),
        'active':
        fields.boolean(
            'Active',
            help=
            "The active field allows you to hide the category without removing it."
        ),
        'parent_left':
        fields.integer('Left parent', select=True),
        'parent_right':
        fields.integer('Right parent', select=True),
        'partner_ids':
        fields.many2many('res.partner', 'res_partner_category_rel',
                         'category_id', 'partner_id', 'Partners'),
    }
    _constraints = [
        (osv.osv._check_recursion,
         'Error ! You can not create recursive categories.', ['parent_id'])
    ]
    _defaults = {
        'active': lambda *a: 1,
    }
    _parent_store = True
    _parent_order = 'name'
    _order = 'parent_left'
Esempio n. 10
0
class document_file(osv.osv):
    _inherit = 'ir.attachment'

    def _data_get(self, cr, uid, ids, name, arg, context):
        result = {}
        cr.execute(
            'select id,store_method,datas,store_fname,link from ir_attachment where id in ('
            + ','.join(map(str, ids)) + ')')
        for id, m, d, r, l in cr.fetchall():
            if m == 'db':
                result[id] = d
            elif m == 'fs':
                path = os.path.join(os.getcwd(), 'filestore')
                value = file(os.path.join(path, r), 'rb').read()
                result[id] = base64.encodestring(value)
            else:
                result[id] = ''
        return result

    #
    # This code can be improved
    #
    def _data_set(self, cr, obj, id, name, value, uid=None, context={}):
        if not value:
            return True
        if (not context) or context.get('store_method', 'fs') == 'fs':
            path = os.path.join(os.getcwd(), "filestore")
            if not os.path.isdir(path):
                os.mkdir(path)
            flag = None
            for dirs in os.listdir(path):
                if os.path.isdir(os.path.join(path, dirs)) and len(
                        os.listdir(os.path.join(path, dirs))) < 4000:
                    flag = dirs
                    break
            flag = flag or create_directory(path)
            filename = random_name()
            fname = os.path.join(path, flag, filename)
            fp = file(fname, 'wb')
            fp.write(base64.decodestring(value))
            filesize = os.stat(fname).st_size
            cr.execute(
                'update ir_attachment set store_fname=%s,store_method=%s,file_size=%d where id=%d',
                (os.path.join(flag, filename), 'fs', filesize, id))
        else:
            cr.execute(
                'update ir_attachment set datas=%s,store_method=%s where id=%d',
                (psycopg.Binary(value), 'db', id))
        return True

    _columns = {
        'user_id':
        fields.many2one('res.users', 'Owner', select=1),
        'group_ids':
        fields.many2many('res.groups', 'document_directory_group_rel',
                         'item_id', 'group_id', 'Groups'),
        'parent_id':
        fields.many2one('document.directory', 'Directory', select=1),
        'file_size':
        fields.integer('File Size', required=True),
        'file_type':
        fields.char('Content Type', size=32),
        'index_content':
        fields.text('Indexed Content'),
        'write_date':
        fields.datetime('Date Modified', readonly=True),
        'write_uid':
        fields.many2one('res.users', 'Last Modification User', readonly=True),
        'create_date':
        fields.datetime('Date Created', readonly=True),
        'create_uid':
        fields.many2one('res.users', 'Creator', readonly=True),
        'store_method':
        fields.selection([('db', 'Database'), ('fs', 'Filesystem'),
                          ('link', 'Link')], "Storing Method"),
        'datas':
        fields.function(_data_get,
                        method=True,
                        store=True,
                        fnct_inv=_data_set,
                        string='File Content',
                        type="binary"),
        'store_fname':
        fields.char('Stored Filename', size=200),
        'res_model':
        fields.char('Attached Model', size=64),  #res_model
        'res_id':
        fields.integer('Attached ID'),  #res_id
        'partner_id':
        fields.many2one('res.partner', 'Partner', select=1),
        'title':
        fields.char('Resource Title', size=64),
    }

    _defaults = {
        'user_id': lambda self, cr, uid, ctx: uid,
        'file_size': lambda self, cr, uid, ctx: 0,
        'store_method': lambda *args: 'db'
    }

    def write(self, cr, uid, ids, vals, context=None):
        result = super(document_file, self).write(cr,
                                                  uid,
                                                  ids,
                                                  vals,
                                                  context=context)
        try:
            for f in self.browse(cr, uid, ids, context=context):
                if 'datas' not in vals:
                    vals['datas'] = f.datas
                res = content_index(base64.decodestring(vals['datas']),
                                    f.datas_fname, f.file_type or None)
                super(document_file, self).write(cr, uid, ids,
                                                 {'index_content': res})
        except:
            pass
        return result

    def create(self, cr, uid, vals, context={}):
        vals['title'] = vals['name']
        if vals.get('res_id', False) and vals.get('res_model', False):
            obj_model = self.pool.get(vals['res_model'])
            result = obj_model.browse(cr,
                                      uid, [vals['res_id']],
                                      context=context)
            if len(result):
                vals['title'] = (result[0].name or '')[:60]
                if obj_model._name == 'res.partner':
                    vals['partner_id'] = result[0].id
                elif 'address_id' in result[0]:
                    vals['partner_id'] = result[
                        0].address_id.partner_id.id or False
                else:
                    vals['partner_id'] = 'partner_id' in result[0] and result[
                        0].partner_id.id or False

            if 'parent_id' not in vals:
                obj_directory = self.pool.get('document.directory')
                directory_ids = obj_directory.search(
                    cr, uid, [('ressource_type_id', '=', vals['res_model'])])
                dirs = obj_directory.browse(cr, uid, directory_ids)
                for dir in dirs:
                    if dir.domain:
                        object_ids = obj_model.search(cr, uid,
                                                      eval(dir.domain))
                        if vals['res_id'] in object_ids:
                            vals['parent_id'] = dir.id
        datas = None
        if 'datas' not in vals:
            import urllib
            datas = base64.encodestring(urllib.urlopen(vals['link']).read())
        else:
            datas = vals['datas']
        vals['file_size'] = len(datas)
        result = super(document_file, self).create(cr, uid, vals, context)
        cr.commit()
        try:
            res = content_index(base64.decodestring(datas),
                                vals['datas_fname'],
                                vals.get('content_type', None))
            super(document_file, self).write(cr, uid, [result], {
                'index_content': res,
            })
        except:
            pass
        return result

    def unlink(self, cr, uid, ids, context={}):
        for f in self.browse(cr, uid, ids, context):
            if f.store_method == 'fs':
                path = os.path.join(os.getcwd(), 'filestore', f.store_fname)
                os.unlink(path)
        return super(document_file, self).unlink(cr, uid, ids, context)
Esempio n. 11
0
class ir_model_fields(osv.osv):
    _name = 'ir.model.fields'
    _description = "Fields"
    _columns = {
        'name':
        fields.char('Name', required=True, size=64, select=1),
        'model':
        fields.char('Object Name', size=64, required=True, select=1),
        'relation':
        fields.char('Object Relation', size=64),
        'relation_field':
        fields.char('Relation Field', size=64),
        'model_id':
        fields.many2one('ir.model',
                        'Object ID',
                        required=True,
                        select=True,
                        ondelete='cascade'),
        'field_description':
        fields.char('Field Label', required=True, size=256),
        'ttype':
        fields.selection(_get_fields_type,
                         'Field Type',
                         size=64,
                         required=True),
        'selection':
        fields.char('Field Selection', size=128),
        'required':
        fields.boolean('Required'),
        'readonly':
        fields.boolean('Readonly'),
        'select_level':
        fields.selection([('0', 'Not Searchable'), ('1', 'Always Searchable'),
                          ('2', 'Advanced Search')],
                         'Searchable',
                         required=True),
        'translate':
        fields.boolean('Translate'),
        'size':
        fields.integer('Size'),
        'state':
        fields.selection([('manual', 'Custom Field'), ('base', 'Base Field')],
                         'Manually Created',
                         required=True,
                         readonly=True,
                         select=1),
        'on_delete':
        fields.selection([('cascade', 'Cascade'), ('set null', 'Set NULL')],
                         'On delete',
                         help='On delete property for many2one fields'),
        'domain':
        fields.char('Domain', size=256),
        'groups':
        fields.many2many('res.groups', 'ir_model_fields_group_rel', 'field_id',
                         'group_id', 'Groups'),
        'view_load':
        fields.boolean('View Auto-Load'),
        'selectable':
        fields.boolean('Selectable'),
    }
    _rec_name = 'field_description'
    _defaults = {
        'view_load': lambda *a: 0,
        'selection': lambda *a: "[]",
        'domain': lambda *a: "[]",
        'name': lambda *a: 'x_',
        'state': lambda self, cr, uid, ctx={}:
        (ctx and ctx.get('manual', False)) and 'manual' or 'base',
        'on_delete': lambda *a: 'set null',
        'select_level': lambda *a: '0',
        'size': lambda *a: 64,
        'field_description': lambda *a: '',
        'selectable': lambda *a: 1,
    }
    _order = "id"
    _sql_constraints = [
        ('size_gt_zero', 'CHECK (size>0)',
         'Size of the field can never be less than 1 !'),
    ]

    def unlink(self, cr, user, ids, context=None):
        for field in self.browse(cr, user, ids, context):
            if field.state <> 'manual':
                raise except_orm(
                    _('Error'),
                    _("You cannot remove the field '%s' !") % (field.name, ))
        #
        # MAY BE ADD A ALTER TABLE DROP ?
        #
        #Removing _columns entry for that table
            self.pool.get(field.model)._columns.pop(field.name, None)
        return super(ir_model_fields, self).unlink(cr, user, ids, context)

    def create(self, cr, user, vals, context=None):
        if 'model_id' in vals:
            model_data = self.pool.get('ir.model').browse(
                cr, user, vals['model_id'])
            vals['model'] = model_data.model
        if context is None:
            context = {}
        if context and context.get('manual', False):
            vals['state'] = 'manual'
        res = super(ir_model_fields, self).create(cr, user, vals, context)
        if vals.get('state', 'base') == 'manual':
            if not vals['name'].startswith('x_'):
                raise except_orm(
                    _('Error'),
                    _("Custom fields must have a name that starts with 'x_' !")
                )

            if vals.get('relation',
                        False) and not self.pool.get('ir.model').search(
                            cr, user, [('model', '=', vals['relation'])]):
                raise except_orm(
                    _('Error'),
                    _("Model %s Does not Exist !" % vals['relation']))

            if self.pool.get(vals['model']):
                self.pool.get(vals['model']).__init__(self.pool, cr)
                #Added context to _auto_init for special treatment to custom field for select_level
                ctx = context.copy()
                ctx.update({
                    'field_name': vals['name'],
                    'field_state': 'manual',
                    'select': vals.get('select_level', '0'),
                    'update_custom_fields': True
                })
                self.pool.get(vals['model'])._auto_init(cr, ctx)

        return res
Esempio n. 12
0
class document_directory(osv.osv):
    _name = 'document.directory'
    _description = 'Document directory'
    _columns = {
        'name':
        fields.char('Name', size=64, required=True, select=1),
        'write_date':
        fields.datetime('Date Modified', readonly=True),
        'write_uid':
        fields.many2one('res.users', 'Last Modification User', readonly=True),
        'create_date':
        fields.datetime('Date Created', readonly=True),
        'create_uid':
        fields.many2one('res.users', 'Creator', readonly=True),
        'file_type':
        fields.char('Content Type', size=32),
        'domain':
        fields.char('Domain', size=128),
        'user_id':
        fields.many2one('res.users', 'Owner'),
        'group_ids':
        fields.many2many('res.groups', 'document_directory_group_rel',
                         'item_id', 'group_id', 'Groups'),
        'parent_id':
        fields.many2one('document.directory', 'Parent Item'),
        'child_ids':
        fields.one2many('document.directory', 'parent_id', 'Children'),
        'file_ids':
        fields.one2many('ir.attachment', 'parent_id', 'Files'),
        'content_ids':
        fields.one2many('document.directory.content', 'directory_id',
                        'Virtual Files'),
        'type':
        fields.selection([('directory', 'Static Directory'),
                          ('ressource', 'Other Ressources')],
                         'Type',
                         required=True),
        'ressource_type_id':
        fields.many2one('ir.model', 'Ressource Model'),
        'ressource_id':
        fields.integer('Ressource ID'),
        'ressource_tree':
        fields.boolean('Tree Structure'),
    }
    _defaults = {
        'user_id': lambda self, cr, uid, ctx: uid,
        'domain': lambda self, cr, uid, ctx: '[]',
        'type': lambda *args: 'directory',
    }
    _sql_constraints = [
        ('filename_uniq', 'unique (name,parent_id,ressource_id)',
         'The directory name must be unique !')
    ]

    def _check_recursion(self, cr, uid, ids):
        level = 100
        while len(ids):
            cr.execute(
                'select distinct parent_id from document_directory where id in ('
                + ','.join(map(str, ids)) + ')')
            ids = filter(None, map(lambda x: x[0], cr.fetchall()))
            if not level:
                return False
            level -= 1
        return True

    _constraints = [
        (_check_recursion, 'Error! You can not create recursive Directories.',
         ['parent_id'])
    ]

    def __init__(self, *args, **kwargs):
        res = super(document_directory, self).__init__(*args, **kwargs)
        self._cache = {}
        return res

    def onchange_content_id(self, cr, uid, ids, ressource_type_id):
        return {}

    def _get_childs(self, cr, uid, node, nodename=False, context={}):
        where = []
        if nodename:
            where.append(('name', '=', nodename))
        if object:
            where.append(('parent_id', '=', object.id))
        ids = self.search(cr, uid, where, context)
        return self.browse(cr, uid, ids, context), False

    """
		PRE:
			uri: of the form "Sales Order/SO001"
		PORT:
			uri
			object: the object.directory or object.directory.content
			object2: the other object linked (if object.directory.content)
	"""

    def get_object(self, cr, uid, uri, context={}):
        if not uri:
            return None
        turi = tuple(uri)
        if (turi in self._cache):
            print '*' * 50
            (path, oo, oo2, content, type, root) = self._cache[turi]
            if oo:
                object = self.pool.get(oo[0]).browse(cr, uid, oo[1], context)
            else:
                object = False
            if oo2:
                object2 = self.pool.get(oo2[0]).browse(cr, uid, oo2[1],
                                                       context)
            else:
                object2 = False
            node = node_class(cr, uid, path, object, object2, context, content,
                              type, root)
            return node

        node = node_class(cr, uid, uri[0], False, type='database')
        for path in uri[1:]:
            if path:
                node = node.child(path)
        oo = node.object and (node.object._name, node.object.id) or False
        oo2 = node.object2 and (node.object2._name, node.object2.id) or False
        self._cache[turi] = (node.path, oo, oo2, node.content, node.type,
                             node.root)
        return node

    def get_childs(self, cr, uid, uri, context={}):
        node = self.get_object(cr, uid, uri, context)
        if uri:
            children = node.children()
        else:
            children = [node]
        result = map(lambda node: node.path_get(), children)
        #childs,object2 = self._get_childs(cr, uid, object, False, context)
        #result = map(lambda x: urlparse.urljoin(path+'/',x.name), childs)
        return result

    def create(self, cr, uid, vals, context=None):
        if vals.get('name', False) and (vals.get('name').find('/') + 1
                                        or vals.get('name').find('@') + 1
                                        or vals.get('name').find('$') + 1
                                        or vals.get('name').find('#') + 1):
            raise webdav.DAV.errors.DAV_NotFound(
                'Directory name must not contain special character...')
        return super(document_directory, self).create(cr, uid, vals, context)
class account_financial_report(osv.osv):
    _name = "afr"

    _columns = {
        'name':
        fields.char('Name', size=128, required=True),
        'company_id':
        fields.many2one('res.company', 'Company', required=True),
        'currency_id':
        fields.many2one(
            'res.currency',
            'Currency',
            help=
            "Currency at which this report will be expressed. If not selected will be used the one set in the company"
        ),
        'inf_type':
        fields.selection([('BS', 'Balance Sheet'), ('IS', 'Income Statement')],
                         'Type',
                         required=True),
        'columns':
        fields.selection([('one', 'End. Balance'), ('two', 'Debit | Credit'),
                          ('four', 'Initial | Debit | Credit | YTD'),
                          ('five', 'Initial | Debit | Credit | Period | YTD'),
                          ('qtr', "4 QTR's | YTD"),
                          ('thirteen', '12 Months | YTD')],
                         'Columns',
                         required=True),
        'display_account':
        fields.selection([('all', 'All Accounts'), ('bal', 'With Balance'),
                          ('mov', 'With movements'),
                          ('bal_mov', 'With Balance / Movements')],
                         'Display accounts'),
        'display_account_level':
        fields.integer(
            'Up to level',
            help='Display accounts up to this level (0 to show all)'),
        'account_ids':
        fields.many2many('account.account',
                         'afr_account_rel',
                         'afr_id',
                         'account_id',
                         'Root accounts',
                         required=True),
        'fiscalyear_id':
        fields.many2one('account.fiscalyear',
                        'Fiscal year',
                        help='Fiscal Year for this report',
                        required=True),
        'period_ids':
        fields.many2many('account.period',
                         'afr_period_rel',
                         'afr_id',
                         'period_id',
                         'Periods',
                         help='All periods in the fiscal year if empty'),
        'analytic_ledger':
        fields.boolean(
            'Analytic Ledger',
            help=
            "Allows to Generate an Analytic Ledger for accounts with moves. Available when Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"
        ),
        'tot_check':
        fields.boolean(
            'Summarize?',
            help=
            'Checking will add a new line at the end of the Report which will Summarize Columns in Report'
        ),
        'lab_str':
        fields.char('Description',
                    help='Description for the Summary',
                    size=128),

        #~ Deprecated fields
        'filter':
        fields.selection([('bydate', 'By Date'), ('byperiod', 'By Period'),
                          ('all', 'By Date and Period'),
                          ('none', 'No Filter')], 'Date/Period Filter'),
        'date_to':
        fields.date('End date'),
        'date_from':
        fields.date('Start date'),
    }

    _defaults = {
        'display_account_level':
        lambda *a: 0,
        'inf_type':
        lambda *a: 'BS',
        'company_id':
        lambda self, cr, uid, c: self.pool.get('res.company').
        _company_default_get(cr, uid, 'account.invoice', context=c),
        'fiscalyear_id':
        lambda self, cr, uid, c: self.pool.get('account.fiscalyear').find(
            cr, uid),
        'display_account':
        lambda *a: 'bal_mov',
        'columns':
        lambda *a: 'five',
        'date_from':
        lambda *a: time.strftime('%Y-%m-%d'),
        'date_to':
        lambda *a: time.strftime('%Y-%m-%d'),
        'filter':
        lambda *a: 'byperiod',
    }

    def copy(self, cr, uid, id, defaults, context=None):
        if context is None:
            context = {}
        previous_name = self.browse(cr, uid, id, context=context).name
        new_name = _('Copy of %s') % previous_name
        lst = self.search(cr,
                          uid, [('name', 'like', new_name)],
                          context=context)
        if lst:
            new_name = '%s (%s)' % (new_name, len(lst) + 1)
        defaults['name'] = new_name
        return super(account_financial_report, self).copy(cr,
                                                          uid,
                                                          id,
                                                          defaults,
                                                          context=context)

    def onchange_inf_type(self, cr, uid, ids, inf_type, context=None):
        if context is None:
            context = {}
        res = {'value': {}}

        if inf_type != 'BS':
            res['value'].update({'analytic_ledger': False})

        return res

    def onchange_columns(self,
                         cr,
                         uid,
                         ids,
                         columns,
                         fiscalyear_id,
                         period_ids,
                         context=None):
        if context is None:
            context = {}
        res = {'value': {}}

        if columns != 'four':
            res['value'].update({'analytic_ledger': False})

        if columns in ('qtr', 'thirteen'):
            p_obj = self.pool.get("account.period")
            period_ids = p_obj.search(cr,
                                      uid,
                                      [('fiscalyear_id', '=', fiscalyear_id),
                                       ('special', '=', False)],
                                      context=context)
            res['value'].update({'period_ids': period_ids})
        else:
            res['value'].update({'period_ids': []})
        return res

    def onchange_analytic_ledger(self,
                                 cr,
                                 uid,
                                 ids,
                                 company_id,
                                 analytic_ledger,
                                 context=None):
        if context is None:
            context = {}
        context['company_id'] = company_id
        res = {'value': {}}
        cur_id = self.pool.get('res.company').browse(
            cr, uid, company_id, context=context).currency_id.id
        res['value'].update({'currency_id': cur_id})
        return res

    def onchange_company_id(self, cr, uid, ids, company_id, context=None):
        if context is None:
            context = {}
        context['company_id'] = company_id
        res = {'value': {}}

        if not company_id:
            return res

        cur_id = self.pool.get('res.company').browse(
            cr, uid, company_id, context=context).currency_id.id
        fy_id = self.pool.get('account.fiscalyear').find(cr,
                                                         uid,
                                                         context=context)
        res['value'].update({'fiscalyear_id': fy_id})
        res['value'].update({'currency_id': cur_id})
        res['value'].update({'account_ids': []})
        res['value'].update({'period_ids': []})
        return res
class set_invoice_ref_in_moves(osv.osv_memory):
    """
    Set Invoice Reference in Moves

    Searchs for account moves associated with invoices that do not have the
    right reference (the reference from a supplier invoice or the number from
    a customer invoice) and lets the user fix them.
    """
    _name = "account_admin_tools.set_invoice_ref_in_moves"
    _description = "Set Invoice Reference in Moves"

    _columns = {
        'state': fields.selection([('new', 'New'), ('ready', 'Ready'), ('done', 'Done')], 'Status', readonly=True),
        'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True),
        'period_ids': fields.many2many('account.period', 'set_invoice_ref_in_moves_period_rel', 'wizard_id', 'period_id', "Periods"),
        'move_ids': fields.many2many('account.move', 'set_invoice_ref_in_move_move_rel', 'wizard_id', 'move_id', 'Moves'),
    }

    _defaults = {
        'company_id': lambda self, cr, uid, context: self.pool.get('res.users').browse(cr, uid, uid, context).company_id.id,
        'move_ids': lambda self, cr, uid, context: context and context.get('move_ids', None),
        'period_ids': lambda self, cr, uid, context: context and context.get('period_ids', None),
        'state': lambda self, cr, uid, context: context and context.get('state', 'new'),
    }

    def _next_view(self, cr, uid, ids, view_name, args=None, context=None):
        """
        Return the next wizard view
        """
        if context is None:
            context = {}
        if args is None:
            args = {}
        ctx = context.copy()
        ctx.update(args)

        model_data_ids = self.pool.get('ir.model.data').search(cr, uid, [
            ('model', '=', 'ir.ui.view'),
            ('module', '=', 'account_admin_tools'),
            ('name', '=', view_name)
        ])
        resource_id = self.pool.get('ir.model.data').read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
        return {
            'name': _("Set Invoice Reference in Moves"),
            'type': 'ir.actions.act_window',
            'res_model': 'account_admin_tools.set_invoice_ref_in_moves',
            'view_type': 'form',
            'view_mode': 'form',
            'views': [(resource_id, 'form')],
            'domain': "[('id', 'in', %s)]" % ids,
            'context': ctx,
            'target': 'new',
        }

    def _get_reference(self, cr, uid, invoice, context=None):
        """
        Get's the reference for an account move given the related invoice.
        """
        if invoice.type in ('in_invoice', 'in_refund'):
            return invoice.reference

    def _is_valid_reference(self, cr, uid, reference, invoice, context=None):
        """
        Checks that the given reference matches the invoice reference or number.
        """
        if reference == invoice.reference:
            return True
        else:
            return False

    def action_skip_new(self, cr, uid, ids, context=None):
        """
        Action that just skips the to the ready state
        """
        return self._next_view(cr, uid, ids, 'view_set_invoice_ref_in_moves_ready_form', {'state': 'ready'}, context)

    def action_find_moves_with_wrong_invoice_ref(self, cr, uid, ids, context=None):
        """
        Action that searchs for account moves associated with invoices,
        that do not have the right reference.
        """
        wiz = self.browse(cr, uid, ids[0], context)

        # FIXME: The next block of code is a workaround to the lp:586252 bug of the 6.0 client.
        #        (https://bugs.launchpad.net/openobject-client/+bug/586252)
        if wiz.period_ids:
            period_ids = [period.id for period in wiz.period_ids]
        else:
            period_ids = context and context.get('period_ids')

        #
        # Find the invoices (on the given periods)
        #
        args = []
        if period_ids:
            args = [('period_id', 'in', period_ids)]
        invoice_ids = self.pool.get(
            'account.invoice').search(cr, uid, args, context=context)

        #
        # Get the moves with references not matching the desired ones
        #
        move_ids = []
        for invoice in self.pool.get('account.invoice').browse(cr, uid, invoice_ids, context=context):
            if invoice.move_id:
                if not self._is_valid_reference(cr, uid, invoice.move_id.ref, invoice, context=context):
                    reference = self._get_reference(
                        cr, uid, invoice, context=context)
                    if reference:
                        move_ids.append(invoice.move_id.id)

        #
        # Return the next view: Show 'ready' view
        #
        args = {
            'move_ids': move_ids,
            'state': 'ready',
        }
        return self._next_view(cr, uid, ids, 'view_set_invoice_ref_in_moves_ready_form', args, context)

    def action_set_invoice_ref_in_moves(self, cr, uid, ids, context=None):
        """
        Action that sets the invoice reference or number as the account move
        reference for the selected moves.
        """
        wiz = self.browse(cr, uid, ids[0], context)

        # FIXME: The next block of code is a workaround to the lp:586252 bug of the 6.0 client.
        #        (https://bugs.launchpad.net/openobject-client/+bug/586252)
        if wiz.move_ids:
            move_ids = [line.id for line in wiz.move_ids]
        else:
            move_ids = context and context.get('move_ids')

        #
        # Find the invoices of the moves
        #
        args = [('move_id', 'in', move_ids)]
        invoice_ids = self.pool.get(
            'account.invoice').search(cr, uid, args, context=context)

        #
        # Update the moves with the reference of the invoice.
        #
        for invoice in self.pool.get('account.invoice').browse(cr, uid, invoice_ids, context=context):
            if invoice.move_id:
                reference = self._get_reference(
                    cr, uid, invoice, context=context)
                if reference and invoice.move_id.ref != reference:
                    self.pool.get('account.move').write(cr, uid, [invoice.move_id.id], {'ref': reference}, context=context)

                    #
                    # Update the move line references too
                    # (if they where equal to the move reference)
                    #
                    for line in invoice.move_id.line_id:
                        if line.ref == invoice.move_id.ref:
                            self.pool.get('account.move.line').write(cr, uid, [line.id], {'ref': reference}, context=context)

        #
        # Return the next view: Show 'done' view
        #
        args = {
            'move_ids': move_ids,
            'state': 'done',
        }
        return self._next_view(cr, uid, ids, 'view_set_invoice_ref_in_moves_done_form', args, context)
Esempio n. 15
0
                {"history": (history or "") + "\n" + time.strftime("%Y-%m-%d %H:%M:%S") + ": " + tools.ustr(message)},
                context,
            )

    _columns = {
        "email_from": fields.char("From", size=64),
        "email_to": fields.char("Recipient (To)", size=250),
        "email_cc": fields.char("CC", size=250),
        "email_bcc": fields.char("BCC", size=250),
        "reply_to": fields.char("Reply-To", size=250),
        "message_id": fields.char("Message-ID", size=250),
        "subject": fields.char("Subject", size=200),
        "body_text": fields.text("Standard Body (Text)"),
        "body_html": fields.text("Body (Rich Text Clients Only)"),
        "attachments_ids": fields.many2many(
            "ir.attachment", "mail_attachments_rel", "mail_id", "att_id", "Attachments"
        ),
        "account_id": fields.many2one("email_template.account", "User account", required=True),
        "user": fields.related("account_id", "user", type="many2one", relation="res.users", string="User"),
        "server_ref": fields.integer("Server Reference of mail", help="Applicable for inward items only"),
        "mail_type": fields.selection(
            [
                ("multipart/mixed", "Has Attachments"),
                ("multipart/alternative", "Plain Text & HTML with no attachments"),
                ("multipart/related", "Intermixed content"),
                ("text/plain", "Plain Text"),
                ("text/html", "HTML Body"),
            ],
            "Mail Contents",
        ),
        # I like GMAIL which allows putting same mail in many folders
Esempio n. 16
0
class product_product(osv.osv):
    _inherit = 'product.product'

    def _get_cost_pub(self, cr, uid, ids, context={}):
        if not len(ids):
            return []
        reads = self.read(cr, uid, ids, ['publ_price'], context)
        res = []
        for record in reads:
            res.append((record['id'], record['publ_price']))
        return res

    def _get_porc(self, cr, uid, ids, field, context={}):
        if not len(ids):
            return []
        reads = self.read(cr, uid, ids, [field], context)
        res = []
        for record in reads:
            res.append((record['id'], record[field]))
        return res

    def _compute_price_disc(self, price, disc):
        return price * (1.0 - (disc or 0.0))

    def _get_supplier_cost(self,
                           cr,
                           uid,
                           ids,
                           product_id,
                           partner_id,
                           context={}):
        product = self.browse(cr, uid, [product_id], context)[0]
        for supinfo in product.seller_ids:
            if not partner_id:
                return {'adv_cos': supinfo.name.adv_cos}
            if supinfo.name.id == partner_id:
                return {'adv_cos': supinfo.name.adv_cos}
        return {'adv_cos': False}

    def _compute_price_incr(self, price, incr):
        if incr == 1:
            return price
        return price * (1 / (1.0 - (incr or 0.0)))

    def _get_std_price(self, cr, uid, ids, name, args, context={}):
        res = {}
        for id in ids:
            res.setdefault(id, 0.0)
            prec_publ = self._get_cost_pub(cr, uid, [id], context)[0][1]
            porc_d_pro = self._get_porc(cr, uid, [id], 'supp_disc',
                                        context)[0][1] / 100
            res[id] = self._compute_price_disc(prec_publ, porc_d_pro)
            porc_i_adv = self._get_porc(cr, uid, [id], 'adv_marg',
                                        context)[0][1] / 100
            if porc_i_adv:
                price_st = res[id] * porc_i_adv
                res[id] = res[id] + price_st
            #has_cos=self._get_supplier_cost(cr, uid, [], id, context.get('partner_id', None), context)
            #if has_cos['adv_cos']:
            #	porc_i_adv=self._get_porc(cr, uid, [id], 'adv_marg', context)[0][1]/100
            #	res[id]=self._compute_price_incr(res[id],porc_i_adv)
        return res

    def _get_supp_price(self, cr, uid, ids, name, args, context):
        res = {}
        for id in ids:
            res.setdefault(id, 0.0)
            prec_publ = self._get_cost_pub(cr, uid, [id], context)[0][1]
            porc_d_pro = self._get_porc(cr, uid, [id], 'supp_disc',
                                        context)[0][1] / 100
            res[id] = self._compute_price_disc(prec_publ, porc_d_pro)
            self.pool.get('product.template').write(
                cr, uid, [id], {'standard_price': res[id]})
        return res

    def _get_invo_price(self, cr, uid, ids, name, args, context):
        res = {}
        for id in ids:
            res.setdefault(id, 0.0)
            prec_publ = self._get_cost_pub(cr, uid, [id], context)[0][1]
            porc_d_pro = self._get_porc(cr, uid, [id], 'supp_disc',
                                        context)[0][1] / 100
            res[id] = self._compute_price_disc(prec_publ, porc_d_pro)
            porc_i_adv = self._get_porc(cr, uid, [id], 'adv_marg',
                                        context)[0][1] / 100
            if porc_i_adv:
                price_st = res[id] * porc_i_adv
                res[id] = res[id] + price_st
            marg_ventas = self._get_porc(cr, uid, [id], 'adv_disc',
                                         context)[0][1] / 100
            if marg_ventas:
                price_venta = res[id] * marg_ventas
                res[id] = res[id] + price_venta
            #res[id]=self._compute_price_incr(res[id],porc_i_adv)
            #has_cos=self._get_supplier_cost(cr, uid, [], id, context.get('partner_id', None), context)
            #if has_cos['adv_cos']:
            #	porc_d_adv=self._get_porc(cr, uid, [id], 'adv_disc', context)[0][1]/100
            #	res[id]=self._compute_price_incr(res[id],porc_d_adv)
            self.pool.get('product.template').write(cr, uid, [id],
                                                    {'list_price': res[id]})
        return res

    def _product_dispo(self, cr, uid, ids, name, arg, context={}):
        res = {}
        out = self._product_outgoing_qty(cr, uid, ids, name, arg, context)
        now = self._product_qty_available(cr, uid, ids, name, arg, context)
        for p_id in ids:
            res[p_id] = now[p_id] + out[p_id]
        return res

    def _check_ean_key(self, cr, uid, ids):
        return True

    _columns = {
        'publ_price':
        fields.float('Public Price',
                     digits=(16, int(config['price_accuracy']))),
        'supp_disc':
        fields.float('Supplier Discount', digits=(6, 3)),
        'adv_marg':
        fields.float('ADV Margin', digits=(6, 3)),
        'adv_disc':
        fields.float('ADV. Discount', digits=(6, 3)),
        'supp_price':
        fields.function(_get_supp_price,
                        digits=(16, int(config['price_accuracy'])),
                        method=True,
                        string='Supplier Price'),
        'invo_price':
        fields.function(_get_invo_price,
                        digits=(16, int(config['price_accuracy'])),
                        method=True,
                        string='Invoice Price'),
        'cost_price':
        fields.function(_get_std_price,
                        digits=(16, int(config['price_accuracy'])),
                        method=True,
                        string='Cost Std. Price'),
        'pat_id':
        fields.many2many('product.category', 'pat_category_rel', 'product_id',
                         'pate_id', 'Patentes'),
        'group_id':
        fields.many2many('product.category', 'group_category_rel',
                         'product_id', 'grp_id', 'Group'),
        'qty_dispo':
        fields.function(
            _product_dispo,
            method=True,
            type='float',
            string='Stock available',
            help=
            "Cantidad disponible para este Producto segun la ubicacion selecionada o todas las internas si no se ha seleccionado ninguna. Calculado como: Stock Real - Saliente."
        ),
        'pick_val':
        fields.boolean('Picking valorado'),
        'qty':
        fields.float('Quantity by Package'),
        'categ_salesman_id':
        fields.many2one('product.category.salesman',
                        'Product Category Salesman'),
        'account_reserv_id':
        fields.many2one('account.account', 'Account Reserva'),
        'promocion':
        fields.boolean('Promocion'),
    }
    _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
    _defaults = {
        'promocion': lambda *a: False,
    }

    def set_price_history(self, cr, uid, ids, dval, value, context):
        lst_seller = []
        lst_price = []
        data_price = {}
        dic_seller = {}
        dic_price = {}

        data_price = {
            'price': value['publ_price'],
            'sup_price': value['supp_price'],
            'inv_price': value['invo_price'],
            'cos_price': value['cost_price'],
            'date_ope': time.strftime('%Y-%m-%d %H:%M:%S'),
            'min_quantity': 1.0,
            'name': value['supp_price'],
        }

        lst_price.append((0, 0, data_price))
        if dval['seller_ids']:
            lst_seller = dval['seller_ids']
            tup_seller = lst_seller[0]
            dic_price = tup_seller[2]
            dic_price['pricelist_ids'] = lst_price
            tup_seller2 = (tup_seller[0], tup_seller[1], dic_price)
            lst_seller2 = [tup_seller2]
            dic_seller['seller_ids'] = lst_seller2
        if value['seller_ids']:
            dic_price['pricelist_ids'] = lst_price
            dic_seller['seller_ids'] = [(1, value['seller_ids'][0], dic_price)]
        return dic_seller

    def create(self, cr, uid, vals, context=None):
        camp_list = ['publ_price', 'supp_disc', 'adv_marg', 'adv_disc']
        for camp in camp_list:
            if camp in vals:
                del vals[camp]
        return super(product_product, self).create(cr,
                                                   uid,
                                                   vals,
                                                   context=context)

    def write(self, cr, uid, ids, vals, context=None):
        camp_list = ['publ_price', 'supp_disc', 'adv_marg', 'adv_disc']
        field_list = [
            'publ_price', 'supp_price', 'invo_price', 'cost_price',
            'seller_ids'
        ]
        chang = False

        data = self.read(cr, uid, ids, fields=field_list, context=context)[0]
        if vals.has_key('seller_ids') and not vals['seller_ids'] and not data[
                'seller_ids']:
            raise osv.except_osv('ERROR	', '¡Producto sin Proveedor!')

        for camp in camp_list:
            if camp in vals:
                chang = True
                break
        if chang:
            vals.update(
                self.set_price_history(cr, uid, ids, vals, data, context))
        return super(product_product, self).write(cr,
                                                  uid,
                                                  ids,
                                                  vals,
                                                  context=context)
Esempio n. 17
0
                act.args=str(args)
            self._callback(cr, uid, act.model.model, act.name, act.args)
        ###################################
        warning = self.make_warning_message()
        res_text = '\n'
        for i in sorted(self.imported_records):
            res_text+=i+': '+str(len(self.imported_records[i]))+'\n'
        self.imported_records.clear()
        self.warning_text = []
        self.write(cr, uid, self_id, {'log':warning+res_text,'state':'done'})
        return

    _columns = {
        'name':fields.char('Name', size=64),
        'date': fields.date('Date', required=True),
        'import_model_ids':fields.many2many('migration.import_models', 'schedule_models_rel', 'schedule_id', 'import_model_id', 'Import Models'),
        'actions_ids': fields.many2many('migration.model_actions', 'schedule_actions_rel', 'schedule_id', 'action_id', 'Actions'),
        'state':fields.selection([('ready','Ready'),('running','Running'),('error','Error'),('done','Done'),('stop','Stopped')], 'State'),
        'log': fields.text('Log'),
        'print_log':fields.boolean('Print Log to Console'),
        'cron_id':fields.many2one('ir.cron', 'Scheduler', readonly=True),
                
    }
    _defaults = {
        'date': lambda *a: time.strftime('%Y-%m-%d'),
        'state': lambda *a: 'ready',
    }

    def set_start(self, cr, uid, ids, context={}):
        self.write(cr, uid, ids, {'state':'ready'})
        cron_id = self.browse(cr, uid, ids[0], {}).cron_id.id
Esempio n. 18
0
class vehicle_report_wiz(osv.osv_memory):
    """ To manage enrich report wizard """
    _name = "vehicle.report.wiz"

    _description = "Vehicle Report Wizard"

    def _selection_year(self, cr, uid, context=None):
        """
        Select car manufacturing year between 1970 and Current year.

        @return: list of years 
        """
        return [(str(years), str(years))
                for years in range(int(datetime.now().year) + 1, 1970, -1)]

    _columns = {
        #'date_from': fields.date('Date From'),
        #'date_to': fields.date('Date To'),
        'group_by':
        fields.selection(
            [
                ('status', 'Vehicle Status'),
                ('category', 'Vehicle type'),
                ('model', 'Vehicle Model'),
                ('year', 'Vehicle Year'),
                ('degree', 'Degree'),
                ('ownership', 'Vehicle Ownership'),
                ('use', 'Vehicle Use'),
                ('department', 'Vehicle Department'),
                #('department_custody','Vehicles That Were and Still Under Department Custody'),
                #('employee_custody','Vehicles That Were and Still Under Employee Custody')
            ],
            'Group By',
        ),
        'departments_ids':
        fields.many2many('hr.department',
                         'departments_vehicle_report_rel',
                         string='Departments'),
        'models_ids':
        fields.many2many('fleet.vehicle.model',
                         'models_vehicle_report_rel',
                         string='Vehicle Models'),
        'categories_ids':
        fields.many2many('vehicle.category',
                         'categories_vehicle_report_rel',
                         string='Vehicle Categories'),
        'ownerships_ids':
        fields.many2many('fleet.vehicle.ownership',
                         'ownerships_vehicle_report_rel',
                         string='Vehicle Ownerships'),
        'uses_ids':
        fields.many2many('fleet.vehicle.use',
                         'uses_vehicle_report_rel',
                         string='Vehicle Uses'),
        'degree_ids':
        fields.many2many('hr.salary.degree',
                         'degree_vehicle_report_rel',
                         string='Degrees'),
        'department_id':
        fields.many2one('hr.department', string='Department'),
        'model_id':
        fields.many2one('fleet.vehicle.model', string='Vehicle Model'),
        'brand_id':
        fields.many2one('fleet.vehicle.model.brand',
                        string='Model Brand Of Vehicle'),
        'category_id':
        fields.many2one('vehicle.category', string='Vehicle Category'),
        'ownership_id':
        fields.many2one('fleet.vehicle.ownership', string='Vehicle Ownership'),
        'use_id':
        fields.many2one('fleet.vehicle.use', string='Vehicle Use'),
        'degree_id':
        fields.many2one('hr.salary.degree', string='Degree'),
        'vehicle_id':
        fields.many2one('fleet.vehicle', string='Vehicle'),
        'employee_id':
        fields.many2one('hr.employee', string='Employee'),
        #'employees_ids': fields.many2many('hr.employee','employee_vehicle_report_rel',string='Employees'),
        'vehicle_status':
        fields.selection([('operation', 'Operational Use'),
                          ('internal', 'Internal Use'),
                          ('supply_custody', 'Supply Custody'),
                          ('disabled', 'Disabled'), ('off', 'Off'),
                          ('custody', 'Custody'), ('sold', 'Sold'),
                          ('for_sale', 'For Sale'), ('removal', 'Removal'),
                          ('missing', 'Missing')], 'Vehicle Status'),
        'year':
        fields.selection(_selection_year, 'Model'),
        'company_id':
        fields.many2one('res.company', 'Company'),
        'total_report':
        fields.boolean('Total Vehicle Report'),
        'included_department':
        fields.boolean('Includes sub-departments'),
        'status':
        fields.selection([('active', 'Active'), ('inactive', 'InActive')],
                         'vehicle Activation'),
        'old_system_driver':
        fields.char('Driver In Old System'),
        'report_type':
        fields.selection([('normal_report', 'Vehicles Report'),
                          ('total_report', 'Total Report'),
                          ('total_report_out', 'Total Out Report'),
                          ('total_number_report', 'Total Number Report')],
                         'vehicle Activation'),
        'vehicle_type':
        fields.selection([('state', 'State'), ('non-state', 'Non-state')],
                         'vehicle Type'),
        'place_id':
        fields.many2one('vehicle.place', string='Vehicle Place'),
        #out vehicles
        'out_driver':
        fields.char('Driver'),
        'out_department':
        fields.many2one('vehicle.out.department', 'External Department'),
    }

    _defaults = {
        'company_id':
        lambda self, cr, uid, c: self.pool.get('res.users').browse(
            cr, uid, uid, context=c).company_id.id,
        'total_report':
        False,
        'included_department':
        False,
        'report_type':
        'normal_report',
    }
    '''def check_date(self, cr, uid, ids, context=None):
        """ 
        Constrain method to check if there is a place with the same name

        @return: boolean True or False
        """
        
        for rec in self.browse(cr, uid, ids, context=context):
            if rec.date_from > rec.date_to:
                raise osv.except_osv(_('ERROR'), _('The Start Date Must Be Before or Equal To the End Date'))
            
        return True

    _constraints = [
         (check_date, '', []),
    ]'''

    def onchange_brand(self, cr, uid, ids, brand_id, context={}):
        """
        """
        vals = {}
        if brand_id:
            vals['model_id'] = False

        return {'value': vals}

    def print_report(self, cr, uid, ids, context=None):
        """
        To print the report.

        @return: print the report
        """
        datas = {}
        if context is None:
            context = {}

        data = self.read(cr, uid, ids)[0]
        data['employee_name'] = False
        data['employee_degree'] = False
        if 'employee_id' in data and data['employee_id']:
            emp = self.pool.get('hr.employee').browse(cr, uid,
                                                      data['employee_id'][0])
            data['employee_name'] = emp.name.encode('utf-8')
            data['employee_degree'] = emp.degree_id.name.encode('utf-8')

        datas = {
            'ids': context.get('active_ids', []),
            'model': 'fleet.vehicle',
            'form': data
        }

        #if data['total_report'] == True:
        if data['report_type'] in ['total_report']:
            return {
                'type': 'ir.actions.report.xml',
                'report_name': 'total_vehicle_report',
                'datas': datas,
            }
        elif data['report_type'] in ['total_report_out']:
            return {
                'type': 'ir.actions.report.xml',
                'report_name': 'total_out_vehicle_report',
                'datas': datas,
            }
        elif data['report_type'] in ['total_number_report']:
            return {
                'type': 'ir.actions.report.xml',
                'report_name': 'total_vehicle_number_report',
                'datas': datas,
            }
        else:
            return {
                'type': 'ir.actions.report.xml',
                'report_name': 'vehicle_report',
                'datas': datas,
            }
 _description = "maintenance modules"
 _columns = {
     "name": fields.char("Name", size=128, required=True, readonly=False),
     "version": fields.char("Versions", size=64, readonly=False),
     "certificate": fields.char("Certificate Code", size=42, required=False, readonly=False),
     "path": fields.function(_get_module_path, method=True, string="Path", type="char", size=512, readonly=True),
     "technical_certificate": fields.selection(
         [("not_started", "Not Started"), ("failed", "Failed"), ("succeeded", "Succeeded"), ("skipped", "Skipped")],
         "Technical Certification",
     ),
     "functional_certificate": fields.selection(
         [("not_started", "Not Started"), ("failed", "Failed"), ("succeeded", "Succeeded"), ("skipped", "Skipped")],
         "Functional Certification",
     ),
     "sale_ids": fields.many2many(
         "sale.order", "maintenance_module_sale_rel", "module_id", "sale_id", "Sale orders"
     ),
     "nbr_source_line": fields.integer(
         "Source Line of Code", help="number of source line of code of uploaded module"
     ),
     "module_zip": fields.binary("Module Zip File"),
     "state": fields.selection(
         [("draft", "Draft"), ("open", "Open"), ("failed", "Failed"), ("done", "Done"), ("cancel", "Cancel")],
         "State",
         readonly=True,
     ),
     "test_ids": fields.one2many("test", "module_id", "Tests"),
     "test_tech_ids": one2many_mod_advert("test", "id", "Tests"),
     "test_func_ids": one2many_mod_advert("test", "id", "Tests"),
     "tech_certificate": fields.boolean("Technicle certificate", help="tick if you want technicle certificate"),
     "func_certificate": fields.boolean("Functional certificate", help="tick if you want functional certificate"),
Esempio n. 20
0
class res_partner(osv.osv):
    _inherit = 'res.partner'

    _order = "ref,name"

    _columns = {
        'vendor_number':
        fields.char('Zeeva vendor number',
                    size=64,
                    help="Zeeva vendor number in this partner."),
        'supplier_rating':
        fields.selection([('1', 'Tier 1'), ('2', 'Tier 2'), ('3', 'Tier 3')],
                         'Zeeva supplier rating'),
        'department':
        fields.selection([('sales', 'Sales'), ('artwork', 'Artwork'),
                          ('shipping', 'Shipping'), ('finance', 'Finance')],
                         'Department'),
        'is_sub_company':
        fields.boolean('Is a Sub-company'),
        'subcompany_name':
        fields.char('Subcompany Name', size=128),
        'prod_categ_ids':
        fields.many2many('product.category',
                         'res_partner_product_category_rel', 'partner_id',
                         'product_category_id', 'Product categories'),

        # predef fields for orders
        'port_of_discharge':
        fields.many2one('stock.port', 'Port of Discharge'),
        'port_of_loading':
        fields.many2one('stock.port', 'Port of Loading'),
        'incoterm':
        fields.many2one(
            'stock.incoterms',
            'Incoterm',
            help=
            "International Commercial Terms are a series of predefined commercial terms used in international transactions."
        ),
        #'payment_term': fields.many2one('account.payment.term', 'Payment Term'),

        #'template_ids': fields.one2many('task.template', 'customer_id', 'Templates'),
        'creation_user':
        fields.many2one('res.users', 'Created by'),
        'creation_date':
        fields.date('Created on'),
        'input_status':
        fields.selection([('draft', 'Draft'), ('modif', 'Modification'),
                          ('submited', 'Submitted'), ('approved', 'Approved')],
                         'Input status',
                         track_visibility='onchange'),
    }

    _defaults = {
        'is_company': False,
        'user_id': lambda obj, cr, uid, context: uid,
        'date': fields.date.context_today,
        'ref': '/',
        'opt_out': True,
        'input_status': 'draft',
    }

    def name_get(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
        res = []
        for record in self.browse(cr, uid, ids, context=context):
            name = record.name
            if record.parent_id and not record.is_company:
                if record.is_sub_company:
                    name = "%s [%s]" % (name, record.subcompany_name)
                else:
                    name = "%s [%s]" % (name, record.parent_id.name)
            if context.get('show_address'):
                name = name + "\n" + self._display_address(
                    cr, uid, record, without_company=True, context=context)
                name = name.replace('\n\n', '\n')
                name = name.replace('\n\n', '\n')
            if context.get('show_email') and record.email:
                name = "%s <%s>" % (name, record.email)
            res.append((record.id, name))
        return res

    def create(self, cr, user, vals, context=None):

        if ('is_company' in vals) and vals['is_company'] and (
            ('ref' not in vals) or (vals.get('ref') == '/')):
            tmp = ""  #format is CCNNN0
            code = ""

            if ('customer' in vals) and (vals.get('customer') == True):
                #2letters for country code
                if vals['country_id']:
                    country_obj = self.pool.get('res.country').browse(
                        cr, user, vals['country_id'], context=None)
                    tmp += country_obj.code
                else:
                    tmp += "--"

                #3letters for the begining of the customer name
                if vals['name']:
                    tmp += vals['name'].replace(" ", "")[0:3].upper()
                else:
                    tmp += "---"

                #1digit to avoid double
                partner_pool = self.pool.get('res.partner')
                for i in range(1, 1000):
                    code = tmp + str(i)
                    partner_object = partner_pool.search(
                        cr, user, [('ref', '=', code)])

                    if not partner_object:
                        break

                    #print "searchID: ", partner_pool.browse(cr,user,partner_object[0]).id
                    #print "IDS: ", ids

                    #if partner_pool.browse(cr,user,partner_object[0]).id in ids:
                    #break

                vals['ref'] = code

            else:
                tmp = "SUP"

                #3digits to avoid double
                partner_pool = self.pool.get('res.partner')
                for i in range(1, 10000):
                    code = tmp + "%03d" % i
                    partner_object = partner_pool.search(
                        cr, user, [('ref', '=', code)])

                    if not partner_object:
                        break

                    #if partner_pool.browse(cr,user,partner_object[0]).id in ids:
                    #break

                vals['ref'] = code

        else:
            vals['ref'] = ''

        vals['creation_user'] = user
        vals['creation_date'] = fields.date.context_today(self,
                                                          cr,
                                                          user,
                                                          context=context)

        return super(res_partner, self).create(cr, user, vals, context)

    # Customer input temp approval
    def input_request(self, cr, uid, ids, context=None):
        for customer in self.browse(cr, uid, ids):

            # ADD bosses
            boss_ids = self.pool.get('res.users').search(
                cr, uid, [
                    '|', '|', ('login', '=', 'nitin'),
                    ('login', '=', 'akshay'), ('login', '=', 'admin')
                ])
            if boss_ids:
                self.message_subscribe_users(cr,
                                             uid, [customer.id],
                                             user_ids=boss_ids)

            # Send request for approval
            #message = _("<b>Approval requested</b> for new customer %s") % (customer.name)
            #print [m.id for m in customer.message_follower_ids]
            #self.message_post(cr, uid, ids, body = message, type='comment', subtype='mt_comment', context = context)

        return self.write(cr,
                          uid,
                          ids, {'input_status': 'submited'},
                          context=context)

    def input_modif(self, cr, uid, ids, context=None):

        return self.write(cr,
                          uid,
                          ids, {'input_status': 'modif'},
                          context=context)

    def input_approval(self, cr, uid, ids, context=None):
        for customer in self.browse(cr, uid, ids):

            # ADD the salesman
            if customer.user_id:
                self.message_subscribe_users(cr,
                                             uid, [customer.id],
                                             user_ids=[customer.user_id.id])

        return self.write(cr,
                          uid,
                          ids, {'input_status': 'approved'},
                          context=context)

    #def message_get_suggested_recipients(self, cr, uid, ids, context=None):
    #recipients = super(res_partner, self).message_get_suggested_recipients(cr, uid, ids, context=context)
    #print recipients
    ##for partner in self.browse(cr, uid, ids, context=context):
    ##self._message_add_suggested_recipient(cr, uid, recipients, partner, partner=partner, reason=_('Partner Profile'))
    #return recipients

    # OVERWRITE of the function to avoid sending wrong emails to customers & suppliers
    def message_get_suggested_recipients(self, cr, uid, ids, context=None):
        """ Returns suggested recipients for ids. Those are a list of
            tuple (partner_id, partner_name, reason), to be managed by Chatter. """
        result = dict.fromkeys(ids, list())
        if self._all_columns.get('user_id'):
            for obj in self.browse(
                    cr, SUPERUSER_ID, ids, context=context
            ):  # SUPERUSER because of a read on res.users that would crash otherwise
                if not obj.user_id or not obj.user_id.partner_id:
                    continue
                #self._message_add_suggested_recipient(cr, uid, result, obj, partner=obj.user_id.partner_id, reason=self._all_columns['user_id'].column.string, context=context)
        return result

    # OVERWRITE of the function to allow messages for partners as a thread #TODO doesn't work
    #def message_post(self, cr, uid, thread_id, **kwargs):
    #""" Override related to res.partner. In case of email message, set it as
    #private:
    #- add the target partner in the message partner_ids
    #- set thread_id as None, because this will trigger the 'private'
    #aspect of the message (model=False, res_id=False)
    #"""
    #print thread_id
    #print kwargs
    #print kwargs['context']['default_res_id']
    #mail_message = self.pool.get('mail.message')
    #message_ids = mail_message.search(cr, SUPERUSER_ID, [('id', '=', thread_id)], context=None)
    #print message_ids

    #if isinstance(thread_id, (list, tuple)):
    #thread_id = thread_id[0]
    #if kwargs.get('type') == 'email':
    #partner_ids = kwargs.get('partner_ids', [])
    #if thread_id not in [command[1] for command in partner_ids]:
    #partner_ids.append((4, thread_id))
    #kwargs['partner_ids'] = partner_ids
    #thread_id = False
    #return super(res_partner, self).message_post(cr, uid, thread_id, **kwargs)

    #ONCHANGE to remove
    def onchange_ref(self,
                     cr,
                     uid,
                     ids,
                     name,
                     country,
                     customer,
                     context=None):
        result = {}
        tmp = ""  #format is CCNNN0
        code = ""

        if customer:
            #2letters for country code
            if country:
                country_obj = self.pool.get('res.country').browse(cr,
                                                                  uid,
                                                                  country,
                                                                  context=None)
                tmp += country_obj.code
            else:
                tmp += "--"

            #3letters for the begining of the customer name
            if name:
                tmp += name[0:3].upper()
            else:
                tmp += "---"

            #1digit to avoid double
            partner_pool = self.pool.get('res.partner')
            for i in range(1, 1000):
                code = tmp + str(i)
                partner_object = partner_pool.search(cr, uid,
                                                     [('ref', '=', code)])

                if not partner_object:
                    break

                #print "searchID: ", partner_pool.browse(cr,uid,partner_object[0]).id
                #print "IDS: ", ids

                if partner_pool.browse(cr, uid, partner_object[0]).id in ids:
                    break

            result = {'value': {'ref': code}}

        else:
            tmp = "SUP"

            #3digits to avoid double
            partner_pool = self.pool.get('res.partner')
            for i in range(1, 10000):
                code = tmp + "%03d" % i
                partner_object = partner_pool.search(cr, uid,
                                                     [('ref', '=', code)])

                if not partner_object:
                    break

                if partner_pool.browse(cr, uid, partner_object[0]).id in ids:
                    break

            result = {'value': {'ref': code}}

        return result

    def onchange_email(self, cr, uid, ids, email, context=None):
        context = context or {}
        warning = {}

        if not email:
            return {}

        if not tools.email_split(email):
            warning = {
                'title':
                _('Email Format Warning!'),
                'message':
                _('The email is not well formatted, it should be [email protected]'
                  )
            }

        return {
            'warning': warning,
        }

    def _display_address(self,
                         cr,
                         uid,
                         address,
                         without_company=False,
                         context=None):
        '''
        The purpose of this function is to build and return an address formatted accordingly to the
        standards of the country where it belongs.

        :param address: browse record of the res.partner to format
        :returns: the address formatted in a display that fit its country habits (or the default ones
            if not country is specified)
        :rtype: string
        '''

        # get the information that will be injected into the display format
        # get the address format
        address_format = address.country_id and address.country_id.address_format or \
              "%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s"
        args = {
            'state_code': address.state_id and address.state_id.code or '',
            'state_name': address.state_id and address.state_id.name or '',
            'country_code': address.country_id and address.country_id.code
            or '',
            'country_name': address.country_id and address.country_id.name
            or '',
            #'company_name': address.parent_id and address.parent_id.name or '',
        }
        for field in self._address_fields(cr, uid, context=context):
            args[field] = getattr(address, field) or ''
        #if without_company:
        #args['company_name'] = ''
        #elif address.parent_id:
        #address_format = '%(company_name)s\n' + address_format
        return address_format % args
Esempio n. 21
0
class Site(OpenbaseCore):
    _name = "openstc.site"
    _inherits = {'product.product':'product_id'}
    _description = "openstc.site"

    def name_get(self, cr, uid, ids, context=None):
        if not len(ids):
            return []
        reads = self.read(cr, uid, ids, ['name','type'], context=context)
        res = []
        for record in reads:
            name = record['name']
            if record['type']:
                name =  name + ' / '+ record['type'][1]
            res.append((record['id'], name))
        return res

    def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
        res = self.name_get(cr, uid, ids, context=context)
        return dict(res)

    #return all services
    def _get_services(self, cr, uid, ids, fields, arg, context):
        res = []
        service_obj = self.pool.get('openstc.service')

        for id in ids:
            #get current team object
            site = self.browse(cr, uid, id, context=context)
            #get list of agents already belongs to team
            services = []
            for service_record in site.service_ids:
                 services.append((service_record.id, service_record.name))

            res.append((id, services))
        return dict(res)


    _actions = {
        'update': lambda self,cr,uid,record, groups_code: 'DIRE' in groups_code or 'MANA' in groups_code,
        'create': lambda self,cr,uid, record, groups_code: 'DIRE' in groups_code or 'MANA' in groups_code,
        'delete': lambda self,cr,uid, record, groups_code: 'DIRE' in groups_code,
    }


    def _get_actions(self, cr, uid, ids, myFields ,arg, context=None):
        #default value: empty string for each id
        ret = {}.fromkeys(ids,'')
        groups_code = []
        groups_code = [group.code for group in self.pool.get("res.users").browse(cr, uid, uid, context=context).groups_id if group.code]

        #evaluation of each _actions item, if test returns True, adds key to actions possible for this record
        for record in self.browse(cr, uid, ids, context=context):
            #ret.update({inter['id']:','.join([key for key,func in self._actions.items() if func(self,cr,uid,inter)])})
            ret.update({record.id:[key for key,func in self._actions.items() if func(self,cr,uid,record,groups_code)]})
        return ret

    _fields_names = {'service_names':'service_ids',
                'service_bookable_names':'service_bookable_ids',
                'partner_type_bookable_names':'partner_type_bookable_ids'}

    _columns = {

            #'name': fields.char('Name', size=128, required=True),
            'complete_name': fields.function(_name_get_fnc, type="char", string='Name', method=True, select=True, store={'openstc.site':[lambda self,cr,uid,ids,ctx={}:ids, ['name','type'], 10]}),
            'code': fields.char('Code', size=32),
            'type': fields.many2one('openstc.site.type', 'Type', required=True),
            'service_ids':fields.many2many('openstc.service', 'openstc_site_services_rel', 'site_id', 'service_id', 'Services'),
            #'service_names' : fields.function(_get_services, method=True,type='many2one', store=False),
            'site_parent_id': fields.many2one('openstc.site', 'Site parent', help='Site parent', ondelete='set null'),
            'length': fields.integer('Lenght'),
            'width': fields.integer('Width'),
            'surface': fields.integer('Surface'),
            'long': fields.float('Longitude'),
            'lat': fields.float('Latitude'),
            'actions':fields.function(_get_actions, method=True, string="Actions possibles",type="char", store=False),
            'product_id':fields.many2one('product.product', 'Produit associé', required=True, ondelete="cascade", help=''),
            #Services authorized to book site
            'service_bookable_ids':fields.many2many('openstc.service', 'openstc_site_bookable_services_rel', 'site_id', 'service_id', 'Services'),
            'internal_booking':fields.boolean('Internal Booking', help="Means that this site can be booked by internal departments"),
            #Partner types authorized to book site
            'partner_type_bookable_ids':fields.many2many('openstc.partner.type', 'openstc_site_bookable_partner_type_rel', 'site_id', 'partner_type_id', 'Services'),
            'external_booking':fields.boolean('External Booking', help="Means that this site can be booked by external partners"),

    }
    _defaults = {
        'type_prod':'site',
        'type':'service',
        }

    ## @note: Override to force qty of product to 1
    def create(self, cr, uid, vals, context=None):
        ret = super(Site, self).create(cr, uid, vals, context=context)
        site = self.read(cr, uid, ret, ['product_id'])
        prod_obj = self.pool.get('product.product')
        prod_obj.openbase_change_stock_qty(cr, uid, site['product_id'][0], 1, context=context)
        prod_obj.write(cr, uid, site['product_id'][0], {'type':'service'}, context=context)
        return ret
Esempio n. 22
0
class ir_actions_todo(osv.osv):
    """
    Configuration Wizards
    """
    _name = 'ir.actions.todo'
    _description = "Configuration Wizards"
    _columns = {
        'action_id':
        fields.many2one('ir.actions.act_window',
                        'Action',
                        select=True,
                        required=True,
                        ondelete='cascade'),
        'sequence':
        fields.integer('Sequence'),
        'state':
        fields.selection(TODO_STATES, string='State', required=True),
        'name':
        fields.char('Name', size=64),
        'type':
        fields.selection(TODO_TYPES,
                         'Type',
                         required=True,
                         help="""Manual: Launched manually.
Automatic: Runs whenever the system is reconfigured.
Launch Manually Once: after hacing been launched manually, it sets automatically to Done."""
                         ),
        'groups_id':
        fields.many2many('res.groups', 'res_groups_action_rel', 'uid', 'gid',
                         'Groups'),
        'note':
        fields.text('Text', translate=True),
        'category_id':
        fields.many2one('ir.actions.todo.category', 'Category'),
    }
    _defaults = {
        'state': 'open',
        'sequence': 10,
        'type': 'manual',
    }
    _order = "sequence,name,id"

    def action_launch(self, cr, uid, ids, context=None):
        """ Launch Action of Wizard"""
        wizard_id = ids and ids[0] or False
        wizard = self.browse(cr, uid, wizard_id, context=context)
        if wizard.type in ('automatic', 'once'):
            wizard.write({'state': 'done'})

        # Load action
        res = self.pool.get('ir.actions.act_window').read(cr,
                                                          uid,
                                                          wizard.action_id.id,
                                                          [],
                                                          context=context)
        res.setdefault('context', '{}')
        res['nodestroy'] = True

        # Open a specific record when res_id is provided in the context
        user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
        ctx = eval(res['context'], {'user': user})
        if ctx.get('res_id'):
            res.update({'res_id': ctx.pop('res_id')})

        # disable log for automatic wizards
        if wizard.type == 'automatic':
            ctx.update({'disable_log': True})
        res.update({'context': ctx})

        return res

    def action_open(self, cr, uid, ids, context=None):
        """ Sets configuration wizard in TODO state"""
        return self.write(cr, uid, ids, {'state': 'open'}, context=context)

    def progress(self, cr, uid, context=None):
        """ Returns a dict with 3 keys {todo, done, total}.

        These keys all map to integers and provide the number of todos
        marked as open, the total number of todos and the number of
        todos not open (which is basically a shortcut to total-todo)

        :rtype: dict
        """
        user_groups = set(
            map(
                lambda x: x.id,
                self.pool['res.users'].browse(cr, uid, [uid],
                                              context=context)[0].groups_id))

        def groups_match(todo):
            """ Checks if the todo's groups match those of the current user
            """
            return not todo.groups_id \
                   or bool(user_groups.intersection((
                        group.id for group in todo.groups_id)))

        done = filter(
            groups_match,
            self.browse(cr,
                        uid,
                        self.search(cr,
                                    uid, [('state', '!=', 'open')],
                                    context=context),
                        context=context))

        total = filter(
            groups_match,
            self.browse(cr,
                        uid,
                        self.search(cr, uid, [], context=context),
                        context=context))

        return {
            'done': len(done),
            'total': len(total),
            'todo': len(total) - len(done)
        }
Esempio n. 23
0
class hr_employee(osv.osv):
    _inherit = 'hr.employee'
    _columns = {
        'employee_code':
        fields.char("Employee Code", required=False, size=20),
        'carrier_level_id':
        fields.many2one('hr.carrier.level',
                        string="Carrier Level",
                        onupdate="CASCADE",
                        ondelete="RESTRICT",
                        required=False),
        'religion_id':
        fields.many2one('hr.employee.religion',
                        string="Religion",
                        required=False,
                        onupdate="CASCADE",
                        ondelete="RESTRICT"),
        'blood_type':
        fields.selection([('A', "A"), ('B', 'B'), ('O', 'O'), ('AB', 'AB')],
                         string="Blood Type"),
        'birth_place':
        fields.char('Birth Place', required=False, size=100),
        # 'last_edu_degree_id': fields.many2one('hr.recruitment.degree',required=False,string="Last Education Degree", onupdate="CASCADE", ondelete="RESTRICT"),
        'home_phone':
        fields.char('Home Phn', required=False),
        'private_mobile_no':
        fields.char('Private Mobile Phn No.'),
        # 'identity_identity_no' : fields.char('Identity Card No',required=True,size=20),
        'identity_attachment_ids':
        fields.many2many('ir.attachment',
                         'hr_employee_identity_attachment_rel', 'employee_id',
                         'attachment_id', 'Identity Attachments'),
        'identity_card_expire_date':
        fields.date('Identity Card Valid Until', required=False),
        'identity_card_image':
        fields.binary(string="ID Card Image File", required=False),
        'employment_status':
        fields.selection([('permanent', 'Permanent'), ('contract', 'Contract'),
                          ('outsource', 'Outsource')],
                         required=False,
                         string="Employment Status"),
    }

    # _defaults = {
    # 	'religion_id':1
    # }
    def action_test(self, cr, uid, ids, context=None):

        content = """<GetAttLog>
		<ArgComKey xsi:type="xsd:integer">78772</ArgComKey>
		<Arg><PIN xsi:type="xsd:integer">All</PIN></Arg></GetAttLog>"""
        header = "POST /iWsService HTTP/1.0\r\nContent-Type: text/xml\r\nContent-Length: " + str(
            len(content)) + "\r\n\r\n"
        # print body
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  #tcp socket

        s.connect(('10.36.14.229', 80))

        # s.send("POST /iWsService HTTP/1.0\r\n")
        # s.send("Content-Type: text/xml\r\n")
        # s.send("Content-Length: "+str(len(content))+"\r\n\r\n")

        # s.send(content)

        body = header + content
        s.send(body)
        datas = []
        loop = 1
        while loop:
            try:
                data = s.recv(4096)
                if data:
                    datas.append(data)
                else:
                    loop = 0
            except s.error:
                print "Socket Error"
                loop = 0
                pass
        print datas, 'aaaaaaaaaaaaaaa'
        s.close()
Esempio n. 24
0
class act_window(osv.osv):
    _name = 'ir.actions.act_window'
    _table = 'ir_act_window'
    _sequence = 'ir_actions_id_seq'
    _order = 'name'

    def _check_model(self, cr, uid, ids, context=None):
        for action in self.browse(cr, uid, ids, context):
            if not self.pool.get(action.res_model):
                return False
            if action.src_model and not self.pool.get(action.src_model):
                return False
        return True

    def _invalid_model_msg(self, cr, uid, ids, context=None):
        return _('Invalid model name in the action definition.')

    _constraints = [(_check_model, _invalid_model_msg,
                     ['res_model', 'src_model'])]

    def _views_get_fnc(self, cr, uid, ids, name, arg, context=None):
        """Returns an ordered list of the specific view modes that should be
           enabled when displaying the result of this action, along with the
           ID of the specific view to use for each mode, if any were required.

           This function hides the logic of determining the precedence between
           the view_modes string, the view_ids o2m, and the view_id m2o that can
           be set on the action.

           :rtype: dict in the form { action_id: list of pairs (tuples) }
           :return: { action_id: [(view_id, view_mode), ...], ... }, where view_mode
                    is one of the possible values for ir.ui.view.type and view_id
                    is the ID of a specific view to use for this mode, or False for
                    the default one.
        """
        res = {}
        for act in self.browse(cr, uid, ids):
            res[act.id] = [(view.view_id.id, view.view_mode)
                           for view in act.view_ids]
            view_ids_modes = [view.view_mode for view in act.view_ids]
            modes = act.view_mode.split(',')
            missing_modes = [
                mode for mode in modes if mode not in view_ids_modes
            ]
            if missing_modes:
                if act.view_id and act.view_id.type in missing_modes:
                    # reorder missing modes to put view_id first if present
                    missing_modes.remove(act.view_id.type)
                    res[act.id].append((act.view_id.id, act.view_id.type))
                res[act.id].extend([(False, mode) for mode in missing_modes])
        return res

    def _search_view(self, cr, uid, ids, name, arg, context=None):
        res = {}

        def encode(s):
            if isinstance(s, unicode):
                return s.encode('utf8')
            return s

        for act in self.browse(cr, uid, ids, context=context):
            fields_from_fields_get = self.pool.get(act.res_model).fields_get(
                cr, uid, context=context)
            search_view_id = False
            if act.search_view_id:
                search_view_id = act.search_view_id.id
            else:
                res_view = self.pool.get('ir.ui.view').search(
                    cr,
                    uid, [('model', '=', act.res_model),
                          ('type', '=', 'search'), ('inherit_id', '=', False)],
                    context=context)
                if res_view:
                    search_view_id = res_view[0]
            if search_view_id:
                field_get = self.pool.get(act.res_model).fields_view_get(
                    cr, uid, search_view_id, 'search', context)
                fields_from_fields_get.update(field_get['fields'])
                field_get['fields'] = fields_from_fields_get
                res[act.id] = str(field_get)
            else:

                def process_child(node, new_node, doc):
                    for child in node.childNodes:
                        if child.localName=='field' and child.hasAttribute('select') \
                                and child.getAttribute('select')=='1':
                            if child.childNodes:
                                fld = doc.createElement('field')
                                for attr in child.attributes.keys():
                                    fld.setAttribute(attr,
                                                     child.getAttribute(attr))
                                new_node.appendChild(fld)
                            else:
                                new_node.appendChild(child)
                        elif child.localName in ('page', 'group', 'notebook'):
                            process_child(child, new_node, doc)

                form_arch = self.pool.get(act.res_model).fields_view_get(
                    cr, uid, False, 'form', context)
                dom_arc = dom.minidom.parseString(encode(form_arch['arch']))
                new_node = copy.deepcopy(dom_arc)
                for child_node in new_node.childNodes[0].childNodes:
                    if child_node.nodeType == child_node.ELEMENT_NODE:
                        new_node.childNodes[0].removeChild(child_node)
                process_child(dom_arc.childNodes[0], new_node.childNodes[0],
                              dom_arc)

                form_arch['arch'] = new_node.toxml()
                form_arch['fields'].update(fields_from_fields_get)
                res[act.id] = str(form_arch)
        return res

    def _get_help_status(self, cr, uid, ids, name, arg, context=None):
        activate_tips = self.pool.get('res.users').browse(cr, uid,
                                                          uid).menu_tips
        return dict([(id, activate_tips) for id in ids])

    _columns = {
        'name': fields.char('Action Name', size=64, translate=True),
        'type': fields.char('Action Type', size=32, required=True),
        'view_id': fields.many2one('ir.ui.view', 'View Ref.', ondelete='cascade'),
        'domain': fields.char('Domain Value', size=250,
            help="Optional domain filtering of the destination data, as a Python expression"),
        'context': fields.char('Context Value', size=250, required=True,
            help="Context dictionary as Python expression, empty by default (Default: {})"),
        'res_model': fields.char('Object', size=64, required=True,
            help="Model name of the object to open in the view window"),
        'src_model': fields.char('Source Object', size=64,
            help="Optional model name of the objects on which this action should be visible"),
        'target': fields.selection([('current','Current Window'),('new','New Window'),('inline','Inline')], 'Target Window'),
        'view_type': fields.selection((('tree','Tree'),('form','Form')), string='View Type', required=True,
            help="View type: set to 'tree' for a hierarchical tree view, or 'form' for other views"),
        'view_mode': fields.char('View Mode', size=250, required=True,
            help="Comma-separated list of allowed view modes, such as 'form', 'tree', 'calendar', etc. (Default: tree,form)"),
        'usage': fields.char('Action Usage', size=32,
            help="Used to filter menu and home actions from the user form."),
        'view_ids': fields.one2many('ir.actions.act_window.view', 'act_window_id', 'Views'),
        'views': fields.function(_views_get_fnc, type='binary', string='Views',
               help="This function field computes the ordered list of views that should be enabled " \
                    "when displaying the result of an action, federating view mode, views and " \
                    "reference view. The result is returned as an ordered list of pairs (view_id,view_mode)."),
        'limit': fields.integer('Limit', help='Default limit for the list view'),
        'auto_refresh': fields.integer('Auto-Refresh',
            help='Add an auto-refresh on the view'),
        'groups_id': fields.many2many('res.groups', 'ir_act_window_group_rel',
            'act_id', 'gid', 'Groups'),
        'search_view_id': fields.many2one('ir.ui.view', 'Search View Ref.'),
        'filter': fields.boolean('Filter'),
        'auto_search':fields.boolean('Auto Search'),
        'search_view' : fields.function(_search_view, type='text', string='Search View'),
        'help': fields.text('Action description',
            help='Optional help text for the users with a description of the target view, such as its usage and purpose.',
            translate=True),
        'display_menu_tip':fields.function(_get_help_status, type='boolean', string='Display Menu Tips',
            help='It gives the status if the tip has to be displayed or not when a user executes an action'),
        'multi': fields.boolean('Action on Multiple Doc.', help="If set to true, the action will not be displayed on the right toolbar of a form view"),
    }

    _defaults = {
        'type': lambda *a: 'ir.actions.act_window',
        'view_type': lambda *a: 'form',
        'view_mode': lambda *a: 'tree,form',
        'context': lambda *a: '{}',
        'limit': lambda *a: 80,
        'target': lambda *a: 'current',
        'auto_refresh': lambda *a: 0,
        'auto_search': lambda *a: True,
        'multi': False,
    }

    def for_xml_id(self, cr, uid, module, xml_id, context=None):
        """ Returns the act_window object created for the provided xml_id

        :param module: the module the act_window originates in
        :param xml_id: the namespace-less id of the action (the @id
                       attribute from the XML file)
        :return: A read() view of the ir.actions.act_window
        """
        dataobj = self.pool.get('ir.model.data')
        data_id = dataobj._get_id(cr, 1, module, xml_id)
        res_id = dataobj.browse(cr, uid, data_id, context).res_id
        return self.read(cr, uid, res_id, [], context)
Esempio n. 25
0
class kg_esi_wizard(osv.osv_memory):

    _name = 'kg.esi.wizard'

    _columns = {
        'dep_id':
        fields.many2many('hr.department', 'kg_esi_dep', 'wiz_id', 'dep_id',
                         'ESI Name'),
        'filter':
        fields.selection([('filter_date', 'Date')], "Filter by",
                         required=True),
        'date_from':
        fields.date("Start Date"),
        'date_to':
        fields.date("End Date"),
        "rep_data":
        fields.binary("File", readonly=True),
        "name":
        fields.char("Filename", 16, readonly=True),
    }

    _defaults = {
        'filter': 'filter_date',
        'date_from': time.strftime('%Y-%m-%d'),
        'date_to': time.strftime('%Y-%m-%d'),
    }

    def _date_validation_check(self, cr, uid, ids, context=None):
        for val_date in self.browse(cr, uid, ids, context=context):
            if val_date.date_from <= val_date.date_to:
                return True
        return False

    _constraints = [
        (_date_validation_check,
         'You must select an correct Start Date and End Date !!',
         ['Valid_date']),
    ]

    def _build_contexts(self, cr, uid, ids, data, context=None):
        if context is None:
            context = {}
        result = {}
        result['date_from'] = 'date_from' in data['form'] and data['form'][
            'date_from'] or False
        result['date_to'] = 'date_to' in data['form'] and data['form'][
            'date_to'] or False
        if data['form']['filter'] == 'filter_date':
            result['date_from'] = data['form']['date_from']
            result['date_to'] = data['form']['date_to']
        return result

    def date_indian_format(self, date_pyformat):
        date_contents = date_pyformat.split("-")
        date_indian = date_contents[2] + "/" + date_contents[
            1] + "/" + date_contents[0]
        return date_indian

    def check_report(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        data = {}
        data['ids'] = context.get('active_ids', [])
        data['model'] = context.get('active_model', 'ir.ui.menu')
        data['form'] = self.read(cr, uid, ids, [])[0]
        used_context = self._build_contexts(cr,
                                            uid,
                                            ids,
                                            data,
                                            context=context)
        data['form']['used_context'] = used_context
        return self._print_report(cr, uid, ids, data, context=context)

    def pre_print_report(self, cr, uid, ids, data, context=None):
        if context is None:
            context = {}
        data['form'].update(self.read(cr, uid, ids, [], context=context)[0])
        return data

    def produce_xls(self, cr, uid, ids, context={}):

        import StringIO
        import base64
        try:
            import xlwt
        except:
            raise osv.except_osv(
                'Warning !',
                'Please download python xlwt module from\nhttp://pypi.python.org/packages/source/x/xlwt/xlwt-0.7.2.tar.gz\nand install it'
            )
        wiz = self.browse(cr, uid, ids[0])
        where_sql = []

        if wiz.dep_id:
            for ids1 in wiz.dep_id:
                where_sql.append("emp.department_id = %s" % (ids1))

        if where_sql:
            where_sql = ' and ' + ' and '.join(where_sql)

        else:
            where_sql = ''

        print "where_sql..................................", where_sql

        cr.execute(
            '''
		
				SELECT 				
				slip.id AS slip_id,
				emp.name_related as emp_name,
				con.esi_acc_no as esi_no,
				con.wage as basic,
				con.allowance as allo,
				dep.name as dep_name,
				att.worked as worked				
							   
				FROM  hr_payslip slip
								
				join hr_employee emp on(emp.id=slip.employee_id)
				join hr_contract con on(con.employee_id=slip.employee_id)
				join kg_monthly_attendance att on(att.id=slip.att_id)
				join hr_department dep on(dep.id=emp.department_id)
				
				where slip.date_from >=%s and slip.date_to <=%s and slip.state = 'done' '''
            + where_sql + '''
				''', (wiz.date_from, wiz.date_to))

        data = cr.dictfetchall()
        print "data <><><><><<><><><><<><><<>.........", data
        tot = 0
        record = {}
        sno = 0
        wbk = xlwt.Workbook()
        style1 = xlwt.easyxf('font: bold on,height 240,color_index 0X36;'
                             'align: horiz center;'
                             'borders: left thin, right thin, top thin')
        s1 = 0
        """adding a worksheet along with name"""

        sheet1 = wbk.add_sheet('ESI Details')
        s2 = 1
        sheet1.col(0).width = 6000
        sheet1.col(1).width = 10000
        sheet1.col(2).width = 5000
        sheet1.col(3).width = 4000
        sheet1.col(4).width = 4000
        sheet1.col(5).width = 5000
        sheet1.col(6).width = 5500
        sheet1.col(7).width = 4000
        sheet1.col(8).width = 4000
        sheet1.col(9).width = 4000
        """ writing field headings """

        sheet1.write(s1, 0, "ESI No", style1)
        sheet1.write(s1, 1, "Employee Name", style1)
        sheet1.write(s1, 2, "Basic", style1)
        sheet1.write(s1, 3, "Allowance", style1)
        sheet1.write(s1, 4, "Gross", style1)
        sheet1.write(s1, 5, "ESI Amount", style1)
        sheet1.write(s1, 6, "Deduction", style1)
        sheet1.write(s1, 7, "Net Salary", style1)
        sheet1.write(s1, 8, "No Of Working Days", style1)
        sheet1.write(s1, 9, "Department", style1)
        """writing data according to query and filteration in worksheet"""
        print "sheet1........................", sheet1
        for ele in data:
            #print "ele////////////////////////",ele
            sheet1.write(s2, 0, ele['esi_no'])
            sheet1.write(s2, 1, ele['emp_name'])
            sheet1.write(s2, 2, ele["basic"])
            sheet1.write(s2, 3, ele['allo'])
            sheet1.write(s2, 4, ele['esi_no'])
            sheet1.write(s2, 5, ele['esi_no'])
            sheet1.write(s2, 6, ele['esi_no'])
            sheet1.write(s2, 7, ele['esi_no'])
            sheet1.write(s2, 8, ele['worked'])
            sheet1.write(s2, 9, ele['dep_name'])
            s2 += 1

        sheet1.write(s2 + 1, 2, "Total", style1)
        sheet1.write(s2 + 1, 3, ele['esi_no'])
        """Parsing data as string """

        file_data = StringIO.StringIO()
        o = wbk.save(file_data)
        """string encode of data in wksheet"""
        out = base64.encodestring(file_data.getvalue())
        #print "out ;;;;;;;;;;;;;;;;;;;;;;;;;-----", out
        """returning the output xls as binary"""
        print "ids......................", ids
        return self.write(cr, uid, ids, {
            'rep_data': out,
            'name': 'Test' + '.xls'
        })
        #return {'type': 'ir.actions.report.xml','rep_data':out, 'name':'Test'+'.xls'}

    def _print_report(self, cr, uid, ids, data, context=None):
        if context is None:
            context = {}
        data = self.pre_print_report(cr, uid, ids, data, context=context)
        data['form'].update(self.read(cr, uid, ids)[0])
        if data['form']:
            date_from = str(data['form']['date_from'])
            date_to = str(data['form']['date_to'])
            data['form']['date_from_ind'] = self.date_indian_format(date_from)
            data['form']['date_to_ind'] = self.date_indian_format(date_to)
            return {
                'type': 'ir.actions.report.xml',
                'report_name': 'kg.otdays',
                'datas': data
            }
Esempio n. 26
0
class actions_server(osv.osv):
    def _select_signals(self, cr, uid, context=None):
        cr.execute(
            """SELECT distinct w.osv, t.signal FROM wkf w, wkf_activity a, wkf_transition t
                      WHERE w.id = a.wkf_id AND
                            (t.act_from = a.id OR t.act_to = a.id) AND
                            t.signal IS NOT NULL""")
        result = cr.fetchall() or []
        res = []
        for rs in result:
            if rs[0] is not None and rs[1] is not None:
                line = rs[1], "%s - (%s)" % (rs[1], rs[0])
                res.append(line)
        return res

    def _select_objects(self, cr, uid, context=None):
        model_pool = self.pool.get('ir.model')
        ids = model_pool.search(cr, uid, [('name', 'not ilike', '.')])
        res = model_pool.read(cr, uid, ids, ['model', 'name'])
        return [(r['model'], r['name']) for r in res] + [('', '')]

    def change_object(self, cr, uid, ids, copy_object, state, context=None):
        if state == 'object_copy' and copy_object:
            if context is None:
                context = {}
            model_pool = self.pool.get('ir.model')
            model = copy_object.split(',')[0]
            mid = model_pool.search(cr, uid, [('model', '=', model)])
            return {'value': {'srcmodel_id': mid[0]}, 'context': context}
        else:
            return {}

    _name = 'ir.actions.server'
    _table = 'ir_act_server'
    _sequence = 'ir_actions_id_seq'
    _order = 'sequence,name'
    _columns = {
        'name':
        fields.char('Action Name', required=True, size=64, translate=True),
        'condition':
        fields.char(
            'Condition',
            size=256,
            required=True,
            help="Condition that is tested before the action is executed, "
            "and prevent execution if it is not verified.\n"
            "Example: object.list_price > 5000\n"
            "It is a Python expression that can use the following values:\n"
            " - self: ORM model of the record on which the action is triggered\n"
            " - object or obj: browse_record of the record on which the action is triggered\n"
            " - pool: ORM model pool (i.e. self.pool)\n"
            " - time: Python time module\n"
            " - cr: database cursor\n"
            " - uid: current user id\n"
            " - context: current context"),
        'state':
        fields.selection([
            ('client_action', 'Client Action'),
            ('dummy', 'Dummy'),
            ('loop', 'Iteration'),
            ('code', 'Python Code'),
            ('trigger', 'Trigger'),
            ('email', 'Email'),
            ('sms', 'SMS'),
            ('object_create', 'Create Object'),
            ('object_copy', 'Copy Object'),
            ('object_write', 'Write Object'),
            ('other', 'Multi Actions'),
        ],
                         'Action Type',
                         required=True,
                         size=32,
                         help="Type of the Action that is to be executed"),
        'code':
        fields.text(
            'Python Code',
            help="Python code to be executed if condition is met.\n"
            "It is a Python block that can use the same values as for the condition field"
        ),
        'sequence':
        fields.integer(
            'Sequence',
            help=
            "Important when you deal with multiple actions, the execution order will be decided based on this, low number is higher priority."
        ),
        'model_id':
        fields.many2one(
            'ir.model',
            'Object',
            required=True,
            help=
            "Select the object on which the action will work (read, write, create)."
        ),
        'action_id':
        fields.many2one(
            'ir.actions.actions',
            'Client Action',
            help="Select the Action Window, Report, Wizard to be executed."),
        'trigger_name':
        fields.selection(_select_signals,
                         string='Trigger Signal',
                         size=128,
                         help="The workflow signal to trigger"),
        'wkf_model_id':
        fields.many2one(
            'ir.model',
            'Target Object',
            help=
            "The object that should receive the workflow signal (must have an associated workflow)"
        ),
        'trigger_obj_id':
        fields.many2one(
            'ir.model.fields',
            'Relation Field',
            help=
            "The field on the current object that links to the target object record (must be a many2one, or an integer field with the record ID)"
        ),
        'email':
        fields.char(
            'Email Address',
            size=512,
            help=
            "Expression that returns the email address to send to. Can be based on the same values as for the condition field.\n"
            "Example: object.invoice_address_id.email, or '*****@*****.**'"),
        'subject':
        fields.char(
            'Subject',
            size=1024,
            translate=True,
            help=
            "Email subject, may contain expressions enclosed in double brackets based on the same values as those "
            "available in the condition field, e.g. `Hello [[ object.partner_id.name ]]`"
        ),
        'message':
        fields.text(
            'Message',
            translate=True,
            help=
            "Email contents, may contain expressions enclosed in double brackets based on the same values as those "
            "available in the condition field, e.g. `Dear [[ object.partner_id.name ]]`"
        ),
        'mobile':
        fields.char(
            'Mobile No',
            size=512,
            help=
            "Provides fields that be used to fetch the mobile number, e.g. you select the invoice, then `object.invoice_address_id.mobile` is the field which gives the correct mobile number"
        ),
        'sms':
        fields.char('SMS', size=160, translate=True),
        'child_ids':
        fields.many2many('ir.actions.server', 'rel_server_actions',
                         'server_id', 'action_id', 'Other Actions'),
        'usage':
        fields.char('Action Usage', size=32),
        'type':
        fields.char('Action Type', size=32, required=True),
        'srcmodel_id':
        fields.many2one(
            'ir.model',
            'Model',
            help=
            "Object in which you want to create / write the object. If it is empty then refer to the Object field."
        ),
        'fields_lines':
        fields.one2many('ir.server.object.lines', 'server_id',
                        'Field Mappings.'),
        'record_id':
        fields.many2one(
            'ir.model.fields',
            'Create Id',
            help=
            "Provide the field name where the record id is stored after the create operations. If it is empty, you can not track the new record."
        ),
        'write_id':
        fields.char(
            'Write Id',
            size=256,
            help=
            "Provide the field name that the record id refers to for the write operation. If it is empty it will refer to the active id of the object."
        ),
        'loop_action':
        fields.many2one(
            'ir.actions.server',
            'Loop Action',
            help=
            "Select the action that will be executed. Loop action will not be avaliable inside loop."
        ),
        'expression':
        fields.char(
            'Loop Expression',
            size=512,
            help=
            "Enter the field/expression that will return the list. E.g. select the sale order in Object, and you can have loop on the sales order line. Expression = `object.order_line`."
        ),
        'copy_object':
        fields.reference('Copy Of', selection=_select_objects, size=256),
    }
    _defaults = {
        'state':
        lambda *a: 'dummy',
        'condition':
        lambda *a: 'True',
        'type':
        lambda *a: 'ir.actions.server',
        'sequence':
        lambda *a: 5,
        'code':
        lambda *a: """# You can use the following variables:
#  - self: ORM model of the record on which the action is triggered
#  - object: browse_record of the record on which the action is triggered if there is one, otherwise None
#  - pool: ORM model pool (i.e. self.pool)
#  - time: Python time module
#  - cr: database cursor
#  - uid: current user id
#  - context: current context
# If you plan to return an action, assign: action = {...}
""",
    }

    def get_email(self, cr, uid, action, context):
        obj_pool = self.pool.get(action.model_id.model)
        id = context.get('active_id')
        obj = obj_pool.browse(cr, uid, id)

        fields = None

        if '/' in action.email.complete_name:
            fields = action.email.complete_name.split('/')
        elif '.' in action.email.complete_name:
            fields = action.email.complete_name.split('.')

        for field in fields:
            try:
                obj = getattr(obj, field)
            except Exception:
                _logger.exception('Failed to parse: %s', field)

        return obj

    def get_mobile(self, cr, uid, action, context):
        obj_pool = self.pool.get(action.model_id.model)
        id = context.get('active_id')
        obj = obj_pool.browse(cr, uid, id)

        fields = None

        if '/' in action.mobile.complete_name:
            fields = action.mobile.complete_name.split('/')
        elif '.' in action.mobile.complete_name:
            fields = action.mobile.complete_name.split('.')

        for field in fields:
            try:
                obj = getattr(obj, field)
            except Exception:
                _logger.exception('Failed to parse: %s', field)

        return obj

    def merge_message(self, cr, uid, keystr, action, context=None):
        if context is None:
            context = {}

        def merge(match):
            obj_pool = self.pool.get(action.model_id.model)
            id = context.get('active_id')
            obj = obj_pool.browse(cr, uid, id)
            exp = str(match.group()[2:-2]).strip()
            result = eval(
                exp,
                {
                    'object': obj,
                    'context':
                    dict(context
                         ),  # copy context to prevent side-effects of eval
                    'time': time,
                })
            if result in (None, False):
                return str("--------")
            return tools.ustr(result)

        com = re.compile('(\[\[.+?\]\])')
        message = com.sub(merge, keystr)

        return message

    # Context should contains:
    #   ids : original ids
    #   id  : current id of the object
    # OUT:
    #   False : Finnished correctly
    #   ACTION_ID : Action to launch

    # FIXME: refactor all the eval() calls in run()!
    def run(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        user = self.pool.get('res.users').browse(cr, uid, uid)
        for action in self.browse(cr, uid, ids, context):
            obj = None
            obj_pool = self.pool.get(action.model_id.model)
            if context.get(
                    'active_model') == action.model_id.model and context.get(
                        'active_id'):
                obj = obj_pool.browse(cr,
                                      uid,
                                      context['active_id'],
                                      context=context)
            cxt = {
                'self': obj_pool,
                'object': obj,
                'obj': obj,
                'pool': self.pool,
                'time': time,
                'cr': cr,
                'context':
                dict(context),  # copy context to prevent side-effects of eval
                'uid': uid,
                'user': user
            }
            expr = eval(str(action.condition), cxt)
            if not expr:
                continue

            if action.state == 'client_action':
                if not action.action_id:
                    raise osv.except_osv(
                        _('Error'), _("Please specify an action to launch !"))
                return self.pool.get(action.action_id.type)\
                    .read(cr, uid, action.action_id.id, context=context)

            if action.state == 'code':
                eval(action.code, cxt, mode="exec",
                     nocopy=True)  # nocopy allows to return 'action'
                if 'action' in cxt:
                    return cxt['action']

            if action.state == 'email':
                email_from = config['email_from']
                address = str(action.email)
                try:
                    address = eval(str(action.email), cxt)
                except:
                    pass

                if not address:
                    _logger.info(
                        'No partner email address specified, not sending any email.'
                    )
                    continue

                if not email_from:
                    _logger.debug(
                        '--email-from command line option is not specified, using a fallback value instead.'
                    )
                    if user.user_email:
                        email_from = user.user_email
                    else:
                        email_from = "%s@%s" % (user.login, gethostname())

                subject = self.merge_message(cr, uid, action.subject, action,
                                             context)
                body = self.merge_message(cr, uid, action.message, action,
                                          context)

                ir_mail_server = self.pool.get('ir.mail_server')
                msg = ir_mail_server.build_email(email_from, [address],
                                                 subject, body)
                res_email = ir_mail_server.send_email(cr, uid, msg)
                if res_email:
                    _logger.info('Email successfully sent to: %s', address)
                else:
                    _logger.warning('Failed to send email to: %s', address)

            if action.state == 'trigger':
                wf_service = netsvc.LocalService("workflow")
                model = action.wkf_model_id.model
                m2o_field_name = action.trigger_obj_id.name
                target_id = obj_pool.read(cr, uid, context.get('active_id'),
                                          [m2o_field_name])[m2o_field_name]
                target_id = target_id[0] if isinstance(target_id,
                                                       tuple) else target_id
                wf_service.trg_validate(uid, model, int(target_id),
                                        action.trigger_name, cr)

            if action.state == 'sms':
                #TODO: set the user and password from the system
                # for the sms gateway user / password
                # USE smsclient module from extra-addons
                _logger.warning(
                    'SMS Facility has not been implemented yet. Use smsclient module!'
                )

            if action.state == 'other':
                res = []
                for act in action.child_ids:
                    context['active_id'] = context['active_ids'][0]
                    result = self.run(cr, uid, [act.id], context)
                    if result:
                        res.append(result)
                return res

            if action.state == 'loop':
                expr = eval(str(action.expression), cxt)
                context['object'] = obj
                for i in expr:
                    context['active_id'] = i.id
                    result = self.run(cr, uid, [action.loop_action.id],
                                      context)

            if action.state == 'object_write':
                res = {}
                for exp in action.fields_lines:
                    euq = exp.value
                    if exp.type == 'equation':
                        expr = eval(euq, cxt)
                    else:
                        expr = exp.value
                    res[exp.col1.name] = expr

                if not action.write_id:
                    if not action.srcmodel_id:
                        obj_pool = self.pool.get(action.model_id.model)
                        obj_pool.write(cr, uid, [context.get('active_id')],
                                       res)
                    else:
                        write_id = context.get('active_id')
                        obj_pool = self.pool.get(action.srcmodel_id.model)
                        obj_pool.write(cr, uid, [write_id], res)

                elif action.write_id:
                    obj_pool = self.pool.get(action.srcmodel_id.model)
                    rec = self.pool.get(action.model_id.model).browse(
                        cr, uid, context.get('active_id'))
                    id = eval(action.write_id, {'object': rec})
                    try:
                        id = int(id)
                    except:
                        raise osv.except_osv(
                            _('Error'),
                            _("Problem in configuration `Record Id` in Server Action!"
                              ))

                    if type(id) != type(1):
                        raise osv.except_osv(
                            _('Error'),
                            _("Problem in configuration `Record Id` in Server Action!"
                              ))
                    write_id = id
                    obj_pool.write(cr, uid, [write_id], res)

            if action.state == 'object_create':
                res = {}
                for exp in action.fields_lines:
                    euq = exp.value
                    if exp.type == 'equation':
                        expr = eval(euq, cxt)
                    else:
                        expr = exp.value
                    res[exp.col1.name] = expr

                obj_pool = None
                res_id = False
                obj_pool = self.pool.get(action.srcmodel_id.model)
                res_id = obj_pool.create(cr, uid, res)
                if action.record_id:
                    self.pool.get(action.model_id.model).write(
                        cr, uid, [context.get('active_id')],
                        {action.record_id.name: res_id})

            if action.state == 'object_copy':
                res = {}
                for exp in action.fields_lines:
                    euq = exp.value
                    if exp.type == 'equation':
                        expr = eval(euq, cxt)
                    else:
                        expr = exp.value
                    res[exp.col1.name] = expr

                model = action.copy_object.split(',')[0]
                cid = action.copy_object.split(',')[1]
                obj_pool = self.pool.get(model)
                res_id = obj_pool.copy(cr, uid, int(cid), res)

        return False
Esempio n. 27
0
class oehealth_person(osv.osv):
    _name = "oehealth.person"
    _table = "oehealth_person"
    _description = "Person"
    _inherits = {
        'res.partner': "partner_id",
    }

    def name_code_get(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
        reads = self.read(cr,
                          uid,
                          ids, ['name', 'person_code'],
                          context=context)
        res = []
        for record in reads:
            name = record['name']
            if record['person_code']:
                name = name + ' (' + record['person_code'][1] + ')'
            res.append((record['id'], name))
        return res

    def _name_code_get_fnc(self,
                           cr,
                           uid,
                           ids,
                           prop,
                           unknow_none,
                           context=None):
        res = self.name_code_get(cr, uid, ids, context=context)
        return dict(res)

    def _compute_age(self, cr, uid, ids, field_name, arg, context={}):
        result = {}
        now = datetime.now()
        for r in self.browse(cr, uid, ids, context=context):
            if r.birthday:
                dob = datetime.strptime(r.birthday, '%Y-%m-%d')
                delta = relativedelta(now, dob)
                #result[r.id] = str(delta.years) +"y "+ str(delta.months) +"m "+ str(delta.days)+"d" #if you only want date just give delta.years
                result[r.id] = str(delta.years)
            else:
                result[r.id] = "No Date of Birth!"
        return result

    _columns = {
        'partner_id':
        fields.many2one('res.partner',
                        'Related Partner',
                        required=True,
                        ondelete='cascade',
                        help='Partner-related data of the Person'),
        #we need a related field in order to be able to sort the person by name
        'name_related':
        fields.related('partner_id',
                       'name',
                       type='char',
                       string='Related Partiner',
                       readonly=True,
                       store=True),
        'alias':
        fields.char('Alias',
                    size=64,
                    help='Common name that the Person is referred'),
        'name_code':
        fields.function(_name_code_get_fnc, type="char", string='Name (Code)'),
        'family_id':
        fields.many2one('oehealth.family',
                        string='Family',
                        help='Family Name (Code)'),
        'country_id':
        fields.many2one('res.country', 'Nationality'),
        'birthday':
        fields.date("Date of Birth"),
        'age':
        fields.function(
            _compute_age,
            method=True,
            type='char',
            size=32,
            string='Age',
        ),
        #'birth_state_id': fields.many2one("res.country.state", 'Birth State', domain="[('country_id','=',birth_country_id)]"),
        #'birth_l10n_br_city_id': fields.many2one('l10n_br_base.city', 'Birth City', domain="[('state_id','=',birth_state_id)]"),
        'spouse_id':
        fields.many2one('oehealth.person', 'Spouse'),
        'father_id':
        fields.many2one('oehealth.person', 'Father'),
        'mother_id':
        fields.many2one('oehealth.person', 'Mother'),
        'responsible_id':
        fields.many2one('oehealth.person', 'Responsible'),
        'identification_id':
        fields.char('Person ID', size=10),
        'person_code':
        fields.many2one('oehealth.person.code', 'Person Code'),
        'otherid':
        fields.char('Other ID', size=64),
        'gender':
        fields.selection([('male', 'Male'), ('female', 'Female')], 'Gender'),
        'marital':
        fields.selection([('single', 'Single'), ('married', 'Married'),
                          ('widower', 'Widower'), ('divorced', 'Divorced')],
                         'Marital Status'),
        'community_area_id':
        fields.many2one('oehealth.comm_area', 'Community Area'),
        'notes':
        fields.text('Notes'),
        'category_ids':
        fields.many2many('oehealth.person.category',
                         id1='person_id',
                         id2='category_id',
                         string='Categories'),
        #'coach_id': fields.many2one('res.partner', 'Coach'),
        #'role_id': fields.many2one('oehealth.person.role', 'Role'),
        'color':
        fields.integer('Color Index'),
    }

    _order = 'name_related'

    def onchange_partner_id(self, cr, uid, ids, address, context=None):
        if address:
            address = self.pool.get('res.partner').browse(cr,
                                                          uid,
                                                          address,
                                                          context=context)
            return {
                'value': {
                    'work_phone': address.phone,
                    'mobile_phone': address.mobile
                }
            }
        return {'value': {}}

    _defaults = {
        'active': 1,
        'color': 0,
        'is_person': 1,
    }

    _sql_constraints = [
        ('person_code_uniq', 'unique(person_code)',
         'Person code already in use!'),
    ]
Esempio n. 28
0
class report_xml(osv.osv):
    def _report_content(self, cursor, user, ids, name, arg, context=None):
        res = {}
        for report in self.browse(cursor, user, ids, context=context):
            data = report[name + '_data']
            if not data and report[name[:-8]]:
                fp = None
                try:
                    fp = tools.file_open(report[name[:-8]], mode='rb')
                    data = fp.read()
                except:
                    data = False
                finally:
                    if fp:
                        fp.close()
            res[report.id] = data
        return res

    def _report_content_inv(self,
                            cursor,
                            user,
                            id,
                            name,
                            value,
                            arg,
                            context=None):
        self.write(cursor, user, id, {name + '_data': value}, context=context)

    def _report_sxw(self, cursor, user, ids, name, arg, context=None):
        res = {}
        for report in self.browse(cursor, user, ids, context=context):
            if report.report_rml:
                res[report.id] = report.report_rml.replace('.rml', '.sxw')
            else:
                res[report.id] = False
        return res

    def register_all(self, cr):
        """Report registration handler that may be overridden by subclasses to
           add their own kinds of report services.
           Loads all reports with no manual loaders (auto==True) and
           registers the appropriate services to implement them.
        """
        opj = os.path.join
        cr.execute("SELECT * FROM ir_act_report_xml WHERE auto=%s ORDER BY id",
                   (True, ))
        result = cr.dictfetchall()
        svcs = netsvc.Service._services
        for r in result:
            if svcs.has_key('report.' + r['report_name']):
                continue
            if r['report_rml'] or r['report_rml_content_data']:
                report_sxw('report.' + r['report_name'],
                           r['model'],
                           opj('addons', r['report_rml'] or '/'),
                           header=r['header'])
            if r['report_xsl']:
                report_rml('report.' + r['report_name'], r['model'],
                           opj('addons', r['report_xml']), r['report_xsl']
                           and opj('addons', r['report_xsl']))

    _name = 'ir.actions.report.xml'
    _table = 'ir_act_report_xml'
    _sequence = 'ir_actions_id_seq'
    _order = 'name'
    _columns = {
        'name':
        fields.char('Name', size=64, required=True, translate=True),
        'model':
        fields.char('Object', size=64, required=True),
        'type':
        fields.char('Action Type', size=32, required=True),
        'report_name':
        fields.char('Service Name', size=64, required=True),
        'usage':
        fields.char('Action Usage', size=32),
        'report_type':
        fields.char(
            'Report Type',
            size=32,
            required=True,
            help=
            "Report Type, e.g. pdf, html, raw, sxw, odt, html2html, mako2html, ..."
        ),
        'groups_id':
        fields.many2many('res.groups', 'res_groups_report_rel', 'uid', 'gid',
                         'Groups'),
        'multi':
        fields.boolean(
            'On multiple doc.',
            help=
            "If set to true, the action will not be displayed on the right toolbar of a form view."
        ),
        'attachment':
        fields.char(
            'Save As Attachment Prefix',
            size=128,
            help=
            'This is the filename of the attachment used to store the printing result. Keep empty to not save the printed reports. You can use a python expression with the object and time variables.'
        ),
        'attachment_use':
        fields.boolean(
            'Reload from Attachment',
            help=
            'If you check this, then the second time the user prints with same attachment name, it returns the previous report.'
        ),
        'auto':
        fields.boolean('Custom python parser'),
        'header':
        fields.boolean('Add RML header',
                       help="Add or not the corporate RML header"),
        'report_xsl':
        fields.char('XSL path', size=256),
        'report_xml':
        fields.char('XML path', size=256, help=''),

        # Pending deprecation... to be replaced by report_file as this object will become the default report object (not so specific to RML anymore)
        'report_rml':
        fields.char(
            'Main report file path',
            size=256,
            help=
            "The path to the main report file (depending on Report Type) or NULL if the content is in another data field"
        ),
        # temporary related field as report_rml is pending deprecation - this field will replace report_rml after v6.0
        'report_file':
        fields.related(
            'report_rml',
            type="char",
            size=256,
            required=False,
            readonly=False,
            string='Report file',
            help=
            "The path to the main report file (depending on Report Type) or NULL if the content is in another field",
            store=True),
        'report_sxw':
        fields.function(_report_sxw, type='char', string='SXW path'),
        'report_sxw_content_data':
        fields.binary('SXW content'),
        'report_rml_content_data':
        fields.binary('RML content'),
        'report_sxw_content':
        fields.function(
            _report_content,
            fnct_inv=_report_content_inv,
            type='binary',
            string='SXW content',
        ),
        'report_rml_content':
        fields.function(_report_content,
                        fnct_inv=_report_content_inv,
                        type='binary',
                        string='RML content'),
    }
    _defaults = {
        'type': lambda *a: 'ir.actions.report.xml',
        'multi': lambda *a: False,
        'auto': lambda *a: True,
        'header': lambda *a: True,
        'report_sxw_content': lambda *a: False,
        'report_type': lambda *a: 'pdf',
        'attachment': lambda *a: False,
    }
Esempio n. 29
0
class mrp_workcenter(osv.osv):
    _inherit = 'mrp.workcenter'
    _columns = {
        'operators_ids': fields.many2many('hr.employee', 'hr_employee_mrp_workcenter_rel', 'workcenter_id', 'employee_id', string='Operators'),
    }
Esempio n. 30
0
class users(osv.osv):
    __admin_ids = {}
    _uid_cache = {}
    _name = "res.users"
    _order = 'name'

    WELCOME_MAIL_SUBJECT = u"Welcome to OpenERP"
    WELCOME_MAIL_BODY = u"An OpenERP account has been created for you, "\
        "\"%(name)s\".\n\nYour login is %(login)s, "\
        "you should ask your supervisor or system administrator if you "\
        "haven't been given your password yet.\n\n"\
        "If you aren't %(name)s, this email reached you errorneously, "\
        "please delete it."

    def get_welcome_mail_subject(self, cr, uid, context=None):
        """ Returns the subject of the mail new users receive (when
        created via the res.config.users wizard), default implementation
        is to return config_users.WELCOME_MAIL_SUBJECT
        """
        return self.WELCOME_MAIL_SUBJECT

    def get_welcome_mail_body(self, cr, uid, context=None):
        """ Returns the subject of the mail new users receive (when
        created via the res.config.users wizard), default implementation
        is to return config_users.WELCOME_MAIL_BODY
        """
        return self.WELCOME_MAIL_BODY

    def get_current_company(self, cr, uid):
        cr.execute(
            'select company_id, res_company.name from res_users left join res_company on res_company.id = company_id where res_users.id=%s'
            % uid)
        return cr.fetchall()

    def send_welcome_email(self, cr, uid, id, context=None):
        if isinstance(id, list): id = id[0]
        user = self.read(cr,
                         uid,
                         id, ['email', 'login', 'name', 'user_email'],
                         context=context)
        email = user['email'] or user['user_email']

        ir_mail_server = self.pool.get('ir.mail_server')
        msg = ir_mail_server.build_email(
            email_from=None,  # take config default
            email_to=[email],
            subject=self.get_welcome_mail_subject(cr, uid, context=context),
            body=(self.get_welcome_mail_body(cr, uid, context=context) % user))
        return ir_mail_server.send_email(cr, uid, msg, context=context)

    def _set_interface_type(self,
                            cr,
                            uid,
                            ids,
                            name,
                            value,
                            arg,
                            context=None):
        """Implementation of 'view' function field setter, sets the type of interface of the users.
        @param name: Name of the field
        @param arg: User defined argument
        @param value: new value returned
        @return:  True/False
        """
        if not value or value not in ['simple', 'extended']:
            return False
        group_obj = self.pool.get('res.groups')
        extended_group_id = group_obj.get_extended_interface_group(
            cr, uid, context=context)
        # First always remove the users from the group (avoids duplication if called twice)
        self.write(cr,
                   uid,
                   ids, {'groups_id': [(3, extended_group_id)]},
                   context=context)
        # Then add them back if requested
        if value == 'extended':
            self.write(cr,
                       uid,
                       ids, {'groups_id': [(4, extended_group_id)]},
                       context=context)
        return True

    def _get_interface_type(self, cr, uid, ids, name, args, context=None):
        """Implementation of 'view' function field getter, returns the type of interface of the users.
        @param field_name: Name of the field
        @param arg: User defined argument
        @return:  Dictionary of values
        """
        group_obj = self.pool.get('res.groups')
        extended_group_id = group_obj.get_extended_interface_group(
            cr, uid, context=context)
        extended_users = group_obj.read(cr,
                                        uid,
                                        extended_group_id, ['users'],
                                        context=context)['users']
        return dict(
            zip(ids, [
                'extended' if user in extended_users else 'simple'
                for user in ids
            ]))

    def _set_new_password(self, cr, uid, id, name, value, args, context=None):
        if value is False:
            # Do not update the password if no value is provided, ignore silently.
            # For example web client submits False values for all empty fields.
            return
        if uid == id:
            # To change their own password users must use the client-specific change password wizard,
            # so that the new password is immediately used for further RPC requests, otherwise the user
            # will face unexpected 'Access Denied' exceptions.
            raise osv.except_osv(
                _('Operation Canceled'),
                _('Please use the change password wizard (in User Preferences or User menu) to change your own password.'
                  ))
        self.write(cr, uid, id, {'password': value})

    def _get_password(self, cr, uid, ids, arg, karg, context=None):
        return dict.fromkeys(ids, '')

    _columns = {
        'id':
        fields.integer('ID'),
        'name':
        fields.char('User Name',
                    size=64,
                    required=True,
                    select=True,
                    help="The new user's real name, used for searching"
                    " and most listings"),
        'login':
        fields.char('Login',
                    size=64,
                    required=True,
                    help="Used to log into the system"),
        'password':
        fields.char(
            'Password',
            size=64,
            invisible=True,
            help=
            "Keep empty if you don't want the user to be able to connect on the system."
        ),
        'new_password':
        fields.function(
            _get_password,
            type='char',
            size=64,
            fnct_inv=_set_new_password,
            string='Set password',
            help=
            "Specify a value only when creating a user or if you're changing the user's password, "
            "otherwise leave empty. After a change of password, the user has to login again."
        ),
        'user_email':
        fields.char('Email', size=64),
        'signature':
        fields.text('Signature'),
        'active':
        fields.boolean('Active'),
        'action_id':
        fields.many2one(
            'ir.actions.actions',
            'Home Action',
            help=
            "If specified, this action will be opened at logon for this user, in addition to the standard menu."
        ),
        'menu_id':
        fields.many2one(
            'ir.actions.actions',
            'Menu Action',
            help=
            "If specified, the action will replace the standard menu for this user."
        ),
        'groups_id':
        fields.many2many('res.groups', 'res_groups_users_rel', 'uid', 'gid',
                         'Groups'),

        # Special behavior for this field: res.company.search() will only return the companies
        # available to the current user (should be the user's companies?), when the user_preference
        # context is set.
        'company_id':
        fields.many2one('res.company',
                        'Company',
                        required=True,
                        help="The company this user is currently working for.",
                        context={'user_preference': True}),
        'company_ids':
        fields.many2many('res.company', 'res_company_users_rel', 'user_id',
                         'cid', 'Companies'),
        'context_lang':
        fields.selection(
            _lang_get,
            'Language',
            required=True,
            help=
            "The default language used in the graphical user interface, when translations are available. To add a new language, you can use the 'Load an Official Translation' wizard available from the 'Administration' menu."
        ),
        'context_tz':
        fields.selection(
            _tz_get,
            'Timezone',
            size=64,
            help=
            "The user's timezone, used to output proper date and time values inside printed reports. "
            "It is important to set a value for this field. You should use the same timezone "
            "that is otherwise used to pick and render date and time values: your computer's timezone."
        ),
        'view':
        fields.function(
            _get_interface_type,
            type='selection',
            fnct_inv=_set_interface_type,
            selection=[('simple', 'Simplified'), ('extended', 'Extended')],
            string='Interface',
            help=
            "OpenERP offers a simplified and an extended user interface. If you use OpenERP for the first time we strongly advise you to select the simplified interface, which has less features but is easier to use. You can switch to the other interface from the User/Preferences menu at any time."
        ),
        'menu_tips':
        fields.boolean(
            'Menu Tips',
            help=
            "Check out this box if you want to always display tips on each menu action"
        ),
        'date':
        fields.datetime('Latest Connection', readonly=True),
        'avatar':
        fields.binary('Image', help='', readonly=False),
    }

    def on_change_company_id(self, cr, uid, ids, company_id):
        return {
            'warning': {
                'title':
                _("Company Switch Warning"),
                'message':
                _("Please keep in mind that documents currently displayed may not be relevant after switching to another company. If you have unsaved changes, please make sure to save and close all forms before switching to a different company. (You can click on Cancel in the User Preferences now)"
                  ),
            }
        }

    def read(self,
             cr,
             uid,
             ids,
             fields=None,
             context=None,
             load='_classic_read'):
        def override_password(o):
            if 'password' in o and ('id' not in o or o['id'] != uid):
                o['password'] = '******'
            return o

        result = super(users, self).read(cr, uid, ids, fields, context, load)
        canwrite = self.pool.get('ir.model.access').check(
            cr, uid, 'res.users', 'write', False)
        if not canwrite:
            if isinstance(ids, (int, float)):
                result = override_password(result)
            else:
                result = map(override_password, result)
        return result

    def _check_company(self, cr, uid, ids, context=None):
        return all(
            ((this.company_id in this.company_ids) or not this.company_ids)
            for this in self.browse(cr, uid, ids, context))

    _constraints = [
        (_check_company,
         'The chosen company is not in the allowed companies for this user',
         ['company_id', 'company_ids']),
    ]

    _sql_constraints = [('login_key', 'UNIQUE (login)',
                         'You can not have two users with the same login !')]

    def _get_email_from(self, cr, uid, ids, context=None):
        if not isinstance(ids, list):
            ids = [ids]
        res = dict.fromkeys(ids, False)
        for user in self.browse(cr, uid, ids, context=context):
            if user.user_email:
                res[user.id] = "%s <%s>" % (user.name, user.user_email)
        return res

    def _get_admin_id(self, cr):
        if self.__admin_ids.get(cr.dbname) is None:
            ir_model_data_obj = self.pool.get('ir.model.data')
            mdid = ir_model_data_obj._get_id(cr, 1, 'base', 'user_root')
            self.__admin_ids[cr.dbname] = ir_model_data_obj.read(
                cr, 1, [mdid], ['res_id'])[0]['res_id']
        return self.__admin_ids[cr.dbname]

    def _get_company(self, cr, uid, context=None, uid2=False):
        if not uid2:
            uid2 = uid
        user = self.pool.get('res.users').read(cr, uid, uid2, ['company_id'],
                                               context)
        company_id = user.get('company_id', False)
        return company_id and company_id[0] or False

    def _get_companies(self, cr, uid, context=None):
        c = self._get_company(cr, uid, context)
        if c:
            return [c]
        return False

    def _get_menu(self, cr, uid, context=None):
        dataobj = self.pool.get('ir.model.data')
        try:
            model, res_id = dataobj.get_object_reference(
                cr, uid, 'base', 'action_menu_admin')
            if model != 'ir.actions.act_window':
                return False
            return res_id
        except ValueError:
            return False

    def _get_group(self, cr, uid, context=None):
        dataobj = self.pool.get('ir.model.data')
        result = []
        try:
            dummy, group_id = dataobj.get_object_reference(
                cr, 1, 'base', 'group_user')
            result.append(group_id)
            dummy, group_id = dataobj.get_object_reference(
                cr, 1, 'base', 'group_partner_manager')
            result.append(group_id)
        except ValueError:
            # If these groups does not exists anymore
            pass
        return result

    _defaults = {
        'password': '',
        'context_lang': 'en_US',
        'active': True,
        'menu_id': _get_menu,
        'company_id': _get_company,
        'company_ids': _get_companies,
        'groups_id': _get_group,
        'menu_tips': False
    }

    # User can write to a few of her own fields (but not her groups for example)
    SELF_WRITEABLE_FIELDS = [
        'menu_tips', 'view', 'password', 'signature', 'action_id',
        'company_id', 'user_email', 'name'
    ]

    def write(self, cr, uid, ids, values, context=None):
        if not hasattr(ids, '__iter__'):
            ids = [ids]
        if ids == [uid]:
            for key in values.keys():
                if not (key in self.SELF_WRITEABLE_FIELDS
                        or key.startswith('context_')):
                    break
            else:
                if 'company_id' in values:
                    if not (values['company_id'] in self.read(
                            cr, 1, uid, ['company_ids'],
                            context=context)['company_ids']):
                        del values['company_id']
                uid = 1  # safe fields only, so we write as super-user to bypass access rights
        if 'avatar' in values and values.get('avatar') is not False:
            logo = cStringIO.StringIO()
            img = Image.open(
                cStringIO.StringIO(base64.decodestring(values.get('avatar'))))
            img.thumbnail((64, 64), Image.ANTIALIAS)
            img.save(logo, format='PNG')
            img = base64.encodestring(logo.getvalue())
            values['avatar'] = img
        res = super(users, self).write(cr, uid, ids, values, context=context)

        # clear caches linked to the users
        self.pool.get('ir.model.access').call_cache_clearing_methods(cr)
        clear = partial(self.pool.get('ir.rule').clear_cache, cr)
        map(clear, ids)
        db = cr.dbname
        if db in self._uid_cache:
            for id in ids:
                if id in self._uid_cache[db]:
                    del self._uid_cache[db][id]

        return res

    def unlink(self, cr, uid, ids, context=None):
        if 1 in ids:
            raise osv.except_osv(
                _('Can not remove root user!'),
                _('You can not remove the admin user as it is used internally for resources created by OpenERP (updates, module installation, ...)'
                  ))
        db = cr.dbname
        if db in self._uid_cache:
            for id in ids:
                if id in self._uid_cache[db]:
                    del self._uid_cache[db][id]
        return super(users, self).unlink(cr, uid, ids, context=context)

    def name_search(self,
                    cr,
                    user,
                    name='',
                    args=None,
                    operator='ilike',
                    context=None,
                    limit=100):
        if not args:
            args = []
        if not context:
            context = {}
        ids = []
        if name:
            ids = self.search(cr,
                              user, [('login', '=', name)] + args,
                              limit=limit,
                              context=context)
        if not ids:
            ids = self.search(cr,
                              user, [('name', operator, name)] + args,
                              limit=limit,
                              context=context)
        return self.name_get(cr, user, ids, context=context)

    def copy(self, cr, uid, id, default=None, context=None):
        user2copy = self.read(cr, uid, [id], ['login', 'name'])[0]
        if default is None:
            default = {}
        copy_pattern = _("%s (copy)")
        copydef = dict(
            login=(copy_pattern % user2copy['login']),
            name=(copy_pattern % user2copy['name']),
        )
        copydef.update(default)
        return super(users, self).copy(cr, uid, id, copydef, context)

    def context_get(self, cr, uid, context=None):
        user = self.browse(cr, uid, uid, context)
        result = {}
        for k in self._columns.keys():
            if k.startswith('context_'):
                res = getattr(user, k) or False
                if isinstance(res, browse_record):
                    res = res.id
                result[k[8:]] = res or False
        return result

    def action_get(self, cr, uid, context=None):
        dataobj = self.pool.get('ir.model.data')
        data_id = dataobj._get_id(cr, 1, 'base', 'action_res_users_my')
        return dataobj.browse(cr, uid, data_id, context=context).res_id

    def authenticate(self, db, login, password, user_agent_env):
        """Verifies and returns the user ID corresponding to the given
          ``login`` and ``password`` combination, or False if there was
          no matching user.

           :param str db: the database on which user is trying to authenticate
           :param str login: username
           :param str password: user password
           :param dict user_agent_env: environment dictionary describing any
               relevant environment attributes
        """
        uid = self.login(db, login, password)
        if uid == openerp.SUPERUSER_ID:
            # Successfully logged in as admin!
            # Attempt to guess the web base url...
            if user_agent_env and user_agent_env.get('base_location'):
                cr = pooler.get_db(db).cursor()
                try:
                    self.pool.get('ir.config_parameter').set_param(
                        cr, uid, 'web.base.url',
                        user_agent_env['base_location'])
                    cr.commit()
                except Exception:
                    _logger.exception(
                        "Failed to update web.base.url configuration parameter"
                    )
                finally:
                    cr.close()
        return uid

    def get_groups_names(self, db, uid):
        if not uid:
            return []
        cr = pooler.get_db(db).cursor()
        user = self.browse(
            cr,
            uid,
            uid,
        )
        cr.execute(
            '''
                SELECT module, name
                FROM ir_model_data
                WHERE res_id IN %s
                    AND model = 'res.groups'
                  ''',
            (tuple(group.id for group in user.groups_id) or tuple([]), ))
        groups = cr.fetchall()
        groups = groups and ["%s.%s" % group for group in groups]
        return groups

    def login(self, db, login, password):
        if not password:
            return False
        cr = pooler.get_db(db).cursor()
        try:
            # autocommit: our single request will be performed atomically.
            # (In this way, there is no opportunity to have two transactions
            # interleaving their cr.execute()..cr.commit() calls and have one
            # of them rolled back due to a concurrent access.)
            # We effectively unconditionally write the res_users line.
            cr.autocommit(True)
            # Even w/ autocommit there's a chance the user row will be locked,
            # in which case we can't delay the login just for the purpose of
            # update the last login date - hence we use FOR UPDATE NOWAIT to
            # try to get the lock - fail-fast
            cr.execute("""SELECT id from res_users
                          WHERE login=%s AND password=%s
                                AND active FOR UPDATE NOWAIT""",
                       (tools.ustr(login), tools.ustr(password)),
                       log_exceptions=False)
            cr.execute(
                """UPDATE res_users
                            SET date = now() AT TIME ZONE 'UTC'
                            WHERE login=%s AND password=%s AND active
                            RETURNING id""",
                (tools.ustr(login), tools.ustr(password)))
        except Exception:
            # Failing to acquire the lock on the res_users row probably means
            # another request is holding it - no big deal, we skip the update
            # for this time, and let the user login anyway.
            cr.rollback()
            cr.execute(
                """SELECT id from res_users
                          WHERE login=%s AND password=%s
                                AND active""",
                (tools.ustr(login), tools.ustr(password)))
        finally:
            res = cr.fetchone()
            cr.close()
            if res:
                return res[0]
        return False

    def check_super(self, passwd):
        if passwd == tools.config['admin_passwd']:
            return True
        else:
            raise openerp.exceptions.AccessDenied()

    def check(self, db, uid, passwd):
        """Verifies that the given (uid, password) pair is authorized for the database ``db`` and
           raise an exception if it is not."""
        if not passwd:
            # empty passwords disallowed for obvious security reasons
            raise openerp.exceptions.AccessDenied()
        if self._uid_cache.get(db, {}).get(uid) == passwd:
            return
        cr = pooler.get_db(db).cursor()
        try:
            cr.execute(
                'SELECT COUNT(1) FROM res_users WHERE id=%s AND password=%s AND active=%s',
                (int(uid), passwd, True))
            res = cr.fetchone()[0]
            if not res:
                raise openerp.exceptions.AccessDenied()
            if self._uid_cache.has_key(db):
                ulist = self._uid_cache[db]
                ulist[uid] = passwd
            else:
                self._uid_cache[db] = {uid: passwd}
        finally:
            cr.close()

    def access(self, db, uid, passwd, sec_level, ids):
        if not passwd:
            return False
        cr = pooler.get_db(db).cursor()
        try:
            cr.execute('SELECT id FROM res_users WHERE id=%s AND password=%s',
                       (uid, passwd))
            res = cr.fetchone()
            if not res:
                raise openerp.exceptions.AccessDenied()
            return res[0]
        finally:
            cr.close()

    def change_password(self, cr, uid, old_passwd, new_passwd, context=None):
        """Change current user password. Old password must be provided explicitly
        to prevent hijacking an existing user session, or for cases where the cleartext
        password is not used to authenticate requests.

        :return: True
        :raise: openerp.exceptions.AccessDenied when old password is wrong
        :raise: except_osv when new password is not set or empty
        """
        self.check(cr.dbname, uid, old_passwd)
        if new_passwd:
            return self.write(cr, uid, uid, {'password': new_passwd})
        raise osv.except_osv(
            _('Warning!'),
            _("Setting empty passwords is not allowed for security reasons!"))
Esempio n. 31
0
                    break
            flag = flag or create_directory(path)
            filename = random_name()
            fname = os.path.join(path, flag, filename)
            fp = file(fname,'wb')
            v = base64.decodestring(value)
            fp.write(v)
            filesize = os.stat(fname).st_size
            cr.execute('update ir_attachment set store_fname=%s,store_method=%s,file_size=%s where id=%s', (os.path.join(flag,filename),'fs',len(v),id))
            return True
        except Exception,e :
            raise except_orm(_('Error!'), str(e))

    _columns = {
        'user_id': fields.many2one('res.users', 'Owner', select=1),
        'group_ids': fields.many2many('res.groups', 'document_directory_group_rel', 'item_id', 'group_id', 'Groups'),
        'parent_id': fields.many2one('document.directory', 'Directory', select=1),
        'file_size': fields.integer('File Size', required=True),
        'file_type': fields.char('Content Type', size=32),
        'index_content': fields.text('Indexed Content'),
        'write_date': fields.datetime('Date Modified', readonly=True),
        'write_uid':  fields.many2one('res.users', 'Last Modification User', readonly=True),
        'create_date': fields.datetime('Date Created', readonly=True),
        'create_uid':  fields.many2one('res.users', 'Creator', readonly=True),
        'store_method': fields.selection([('db','Database'),('fs','Filesystem'),('link','Link')], "Storing Method"),
        'datas': fields.function(_data_get,method=True,fnct_inv=_data_set,string='File Content',type="binary"),
        'store_fname': fields.char('Stored Filename', size=200),
        'res_model': fields.char('Attached Model', size=64), #res_model
        'res_id': fields.integer('Attached ID'), #res_id
        'partner_id':fields.many2one('res.partner', 'Partner', select=1),
        'title': fields.char('Resource Title',size=64),
Esempio n. 32
0
class groups(osv.osv):
    _name = "res.groups"
    _description = "Access Groups"
    _rec_name = 'full_name'

    def _get_full_name(self, cr, uid, ids, field, arg, context=None):
        res = {}
        for g in self.browse(cr, uid, ids, context):
            if g.category_id:
                res[g.id] = '%s / %s' % (g.category_id.name, g.name)
            else:
                res[g.id] = g.name
        return res

    _columns = {
        'name':
        fields.char('Name', size=64, required=True, translate=True),
        'users':
        fields.many2many('res.users', 'res_groups_users_rel', 'gid', 'uid',
                         'Users'),
        'model_access':
        fields.one2many('ir.model.access', 'group_id', 'Access Controls'),
        'rule_groups':
        fields.many2many('ir.rule',
                         'rule_group_rel',
                         'group_id',
                         'rule_group_id',
                         'Rules',
                         domain=[('global', '=', False)]),
        'menu_access':
        fields.many2many('ir.ui.menu', 'ir_ui_menu_group_rel', 'gid',
                         'menu_id', 'Access Menu'),
        'comment':
        fields.text('Comment', size=250, translate=True),
        'category_id':
        fields.many2one('ir.module.category', 'Application', select=True),
        'full_name':
        fields.function(_get_full_name, type='char', string='Group Name'),
    }

    _sql_constraints = [('name_uniq', 'unique (category_id, name)',
                         'The name of the group must be unique !')]

    def search(self,
               cr,
               uid,
               args,
               offset=0,
               limit=None,
               order=None,
               context=None,
               count=False):
        # add explicit ordering if search is sorted on full_name
        if order and order.startswith('full_name'):
            ids = super(groups, self).search(cr, uid, args, context=context)
            gs = self.browse(cr, uid, ids, context)
            gs.sort(key=lambda g: g.full_name, reverse=order.endswith('DESC'))
            gs = gs[offset:offset + limit] if limit else gs[offset:]
            return map(int, gs)
        return super(groups, self).search(cr, uid, args, offset, limit, order,
                                          context, count)

    def copy(self, cr, uid, id, default=None, context=None):
        group_name = self.read(cr, uid, [id], ['name'])[0]['name']
        default.update({'name': _('%s (copy)') % group_name})
        return super(groups, self).copy(cr, uid, id, default, context)

    def write(self, cr, uid, ids, vals, context=None):
        if 'name' in vals:
            if vals['name'].startswith('-'):
                raise osv.except_osv(
                    _('Error'),
                    _('The name of the group can not start with "-"'))
        res = super(groups, self).write(cr, uid, ids, vals, context=context)
        self.pool.get('ir.model.access').call_cache_clearing_methods(cr)
        return res

    def create(self, cr, uid, vals, context=None):
        if 'name' in vals:
            if vals['name'].startswith('-'):
                raise osv.except_osv(
                    _('Error'),
                    _('The name of the group can not start with "-"'))
        gid = super(groups, self).create(cr, uid, vals, context=context)
        if context and context.get('noadmin', False):
            pass
        else:
            # assign this new group to user_root
            user_obj = self.pool.get('res.users')
            aid = user_obj.browse(cr, 1, user_obj._get_admin_id(cr))
            if aid:
                aid.write({'groups_id': [(4, gid)]})
        return gid

    def unlink(self, cr, uid, ids, context=None):
        group_users = []
        for record in self.read(cr, uid, ids, ['users'], context=context):
            if record['users']:
                group_users.extend(record['users'])
        if group_users:
            user_names = [
                user.name for user in self.pool.get('res.users').browse(
                    cr, uid, group_users, context=context)
            ]
            user_names = list(set(user_names))
            if len(user_names) >= 5:
                user_names = user_names[:5] + ['...']
            raise osv.except_osv(_('Warning !'),
                        _('Group(s) cannot be deleted, because some user(s) still belong to them: %s !') % \
                            ', '.join(user_names))
        return super(groups, self).unlink(cr, uid, ids, context=context)

    def get_extended_interface_group(self, cr, uid, context=None):
        data_obj = self.pool.get('ir.model.data')
        extended_group_data_id = data_obj._get_id(cr, uid, 'base',
                                                  'group_extended')
        return data_obj.browse(cr,
                               uid,
                               extended_group_data_id,
                               context=context).res_id
Esempio n. 33
0
                cr.execute('select id from sync_server_entity_activity where entity_id=%s for update nowait', (entity.id,), log_exceptions=False)
            cr.execute('update sync_server_entity_activity set datetime=%s, activity=%s where entity_id=%s', (now, activity, entity.id))
        except psycopg2.OperationalError, e:
            if not wait and e.pgcode == '55P03':
                # can't acquire lock: ok the show must go on
                cr.execute("ROLLBACK TO update_entity_last_activity")
                logging.getLogger('sync.server').info("Can't acquire lock to set last_activity")
                return
            raise

    _columns = {
        'name':fields.char('Instance Name', size=64, required=True, select=True),
        'identifier':fields.char('Identifier', size=64, readonly=True, select=True),
        'hardware_id' : fields.char('Hardware Identifier', size=128, select=True),
        'parent_id':fields.many2one('sync.server.entity', 'Parent Instance', ondelete='cascade'),
        'group_ids':fields.many2many('sync.server.entity_group', 'sync_entity_group_rel', 'entity_id', 'group_id', string="Groups"),
        'state' : fields.selection([('pending', 'Pending'), ('validated', 'Validated'), ('invalidated', 'Invalidated'), ('updated', 'Updated')], 'State'),
        'email':fields.char('Contact Email', size=512),
        'user_id': fields.many2one('res.users', 'User', ondelete='restrict', required=True),
        
        #just in case, since the many2one exist it has no cost in database
        'children_ids' : fields.one2many('sync.server.entity', 'parent_id', 'Children Instances'),
        'update_token' : fields.char('Update security token', size=256),

        'activity' : fields.function(_get_activity, type='char', string="Activity", method=True, multi="_get_act"),
        'last_dateactivity': fields.function(_get_activity, type='datetime', string="Date of last activity", method=True, multi="_get_act"),
        #'last_activity' : fields.datetime("Date of last activity", readonly=True),

        'parent_left' : fields.integer("Left Parent", select=1),
        'parent_right' : fields.integer("Right Parent", select=1),
        
class account_payment_populate_statement(osv.osv_memory):
    _name = "account.payment.populate.statement"
    _description = "Account Payment Populate Statement"
    _columns = {
        'lines':
        fields.many2many('payment.line', 'payment_line_rel_', 'payment_id',
                         'line_id', 'Payment Lines')
    }

    def fields_view_get(self,
                        cr,
                        uid,
                        view_id=None,
                        view_type='form',
                        context=None,
                        toolbar=False,
                        submenu=False):
        line_obj = self.pool.get('payment.line')

        res = super(account_payment_populate_statement,
                    self).fields_view_get(cr,
                                          uid,
                                          view_id=view_id,
                                          view_type=view_type,
                                          context=context,
                                          toolbar=toolbar,
                                          submenu=False)
        line_ids = line_obj.search(cr, uid,
                                   [('move_line_id.reconcile_id', '=', False),
                                    ('bank_statement_line_id', '=', False),
                                    ('move_line_id.state', '=', 'valid')])
        line_ids.extend(
            line_obj.search(cr, uid,
                            [('move_line_id.reconcile_id', '=', False),
                             ('order_id.mode', '=', False),
                             ('move_line_id.state', '=', 'valid')]))
        domain = '[("id", "in", ' + str(line_ids) + ')]'
        doc = etree.XML(res['arch'])
        nodes = doc.xpath("//field[@name='lines']")
        for node in nodes:
            node.set('domain', domain)
        res['arch'] = etree.tostring(doc)
        return res

    def populate_statement(self, cr, uid, ids, context=None):
        line_obj = self.pool.get('payment.line')
        statement_obj = self.pool.get('account.bank.statement')
        statement_line_obj = self.pool.get('account.bank.statement.line')
        currency_obj = self.pool.get('res.currency')
        voucher_obj = self.pool.get('account.voucher')
        voucher_line_obj = self.pool.get('account.voucher.line')
        move_line_obj = self.pool.get('account.move.line')

        if context is None:
            context = {}
        data = self.read(cr, uid, ids, [], context=context)[0]
        line_ids = data['lines']
        if not line_ids:
            return {'type': 'ir.actions.act_window_close'}

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

        for line in line_obj.browse(cr, uid, line_ids, context=context):
            ctx = context.copy()
            ctx['date'] = line.ml_maturity_date  # was value_date earlier,but this field exists no more now
            amount = currency_obj.compute(cr,
                                          uid,
                                          line.currency.id,
                                          statement.currency.id,
                                          line.amount_currency,
                                          context=ctx)

            if not line.move_line_id.id:
                continue
            context.update({'move_line_ids': [line.move_line_id.id]})
            result = voucher_obj.onchange_partner_id(
                cr,
                uid, [],
                partner_id=line.partner_id.id,
                journal_id=statement.journal_id.id,
                amount=abs(amount),
                currency_id=statement.currency.id,
                ttype='payment',
                date=line.ml_maturity_date,
                context=context)

            if line.move_line_id:
                voucher_res = {
                    'type':
                    'payment',
                    'name':
                    line.name,
                    'partner_id':
                    line.partner_id.id,
                    'journal_id':
                    statement.journal_id.id,
                    'account_id':
                    result.get(
                        'account_id',
                        statement.journal_id.default_credit_account_id.id),
                    'company_id':
                    statement.company_id.id,
                    'currency_id':
                    statement.currency.id,
                    'date':
                    line.date or time.strftime('%Y-%m-%d'),
                    'amount':
                    abs(amount),
                    'period_id':
                    statement.period_id.id
                }
                voucher_id = voucher_obj.create(cr,
                                                uid,
                                                voucher_res,
                                                context=context)
                voucher_line_dict = False
                if result['value']['line_ids']:
                    for line_dict in result['value']['line_ids']:
                        move_line = move_line_obj.browse(
                            cr, uid, line_dict['move_line_id'], context)
                        if line.move_line_id.move_id.id == move_line.move_id.id:
                            voucher_line_dict = line_dict
                if voucher_line_dict:
                    voucher_line_dict.update({'voucher_id': voucher_id})
                    voucher_line_obj.create(cr,
                                            uid,
                                            voucher_line_dict,
                                            context=context)

                st_line_id = statement_line_obj.create(
                    cr,
                    uid, {
                        'name': line.order_id.reference or '?',
                        'amount': -amount,
                        'type': 'supplier',
                        'partner_id': line.partner_id.id,
                        'account_id': line.move_line_id.account_id.id,
                        'statement_id': statement.id,
                        'ref': line.communication,
                        'voucher_id': voucher_id,
                    },
                    context=context)

                line_obj.write(cr, uid, [line.id],
                               {'bank_statement_line_id': st_line_id})
        return {'type': 'ir.actions.act_window_close'}
Esempio n. 35
0
                # TODO schedule a retry (ir.cron)
                return False
        return True

    def _valid_get(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        for contract in self.browse(cr, uid, ids, context=context):
            res[contract.id] = ("unvalid", "valid")[contract.date_stop >= time.strftime('%Y-%m-%d')]
        return res

    _columns = {
        'name' : fields.char('Contract ID', size=256, required=True, readonly=True),
        'password' : fields.char('Password', size=64, invisible=True, required=True, readonly=True),
        'date_start' : fields.date('Starting Date', readonly=True),
        'date_stop' : fields.date('Ending Date', readonly=True),
        'module_ids' : fields.many2many('maintenance.contract.module', 'maintenance_contract_module_rel', 'contract_id', 'module_id', 'Covered Modules', readonly=True),
        'state' : fields.function(_valid_get, method=True, string="State", type="selection", selection=[('valid', 'Valid'),('unvalid', 'Unvalid')], readonly=True),
        'kind' : fields.selection([('full', 'Full'),('partial', 'Partial')], 'Kind', required=True, readonly=True),
    }
    _defaults = {
        'password' : lambda obj,cr,uid,context={} : '',
    }
    _sql_constraints = [
        ('uniq_name', 'unique(name)', "Your maintenance contract is already subscribed in the system !")
    ]

maintenance_contract()


class maintenance_contract_wizard(osv.osv_memory):
    _name = 'maintenance.contract.wizard'
class project_phase(osv.osv):
    _name = "project.phase"
    _description = "Project Phase"

    def _check_recursion(self, cr, uid, ids, context=None):
         if context is None:
            context = {}

         data_phase = self.browse(cr, uid, ids[0], context=context)
         prev_ids = data_phase.previous_phase_ids
         next_ids = data_phase.next_phase_ids
         # it should neither be in prev_ids nor in next_ids
         if (data_phase in prev_ids) or (data_phase in next_ids):
             return False
         ids = [id for id in prev_ids if id in next_ids]
         # both prev_ids and next_ids must be unique
         if ids:
             return False
         # unrelated project
         prev_ids = [rec.id for rec in prev_ids]
         next_ids = [rec.id for rec in next_ids]
         # iter prev_ids
         while prev_ids:
             cr.execute('SELECT distinct prv_phase_id FROM project_phase_rel WHERE next_phase_id IN %s', (tuple(prev_ids),))
             prv_phase_ids = filter(None, map(lambda x: x[0], cr.fetchall()))
             if data_phase.id in prv_phase_ids:
                 return False
             ids = [id for id in prv_phase_ids if id in next_ids]
             if ids:
                 return False
             prev_ids = prv_phase_ids
         # iter next_ids
         while next_ids:
             cr.execute('SELECT distinct next_phase_id FROM project_phase_rel WHERE prv_phase_id IN %s', (tuple(next_ids),))
             next_phase_ids = filter(None, map(lambda x: x[0], cr.fetchall()))
             if data_phase.id in next_phase_ids:
                 return False
             ids = [id for id in next_phase_ids if id in prev_ids]
             if ids:
                 return False
             next_ids = next_phase_ids
         return True

    def _check_dates(self, cr, uid, ids, context=None):
         for phase in self.read(cr, uid, ids, ['date_start', 'date_end'], context=context):
             if phase['date_start'] and phase['date_end'] and phase['date_start'] > phase['date_end']:
                 return False
         return True

    def _compute_progress(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        if not ids:
            return res
        for phase in self.browse(cr, uid, ids, context=context):
            if phase.state=='done':
                res[phase.id] = 100.0
                continue
            elif phase.state=="cancelled":
                res[phase.id] = 0.0
                continue
            elif not phase.task_ids:
                res[phase.id] = 0.0
                continue

            tot = done = 0.0
            for task in phase.task_ids:
                tot += task.total_hours
                done += min(task.effective_hours, task.total_hours)

            if not tot:
                res[phase.id] = 0.0
            else:
                res[phase.id] = round(100.0 * done / tot, 2)
        return res

    _columns = {
        'name': fields.char("Name", size=64, required=True),
        'date_start': fields.datetime('Start Date', select=True, help="It's computed by the scheduler according the project date or the end date of the previous phase.", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
        'date_end': fields.datetime('End Date', help=" It's computed by the scheduler according to the start date and the duration.", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
        'constraint_date_start': fields.datetime('Minimum Start Date', help='force the phase to start after this date', states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
        'constraint_date_end': fields.datetime('Deadline', help='force the phase to finish before this date', states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
        'project_id': fields.many2one('project.project', 'Project', required=True, select=True),
        'next_phase_ids': fields.many2many('project.phase', 'project_phase_rel', 'prv_phase_id', 'next_phase_id', 'Next Phases', states={'cancelled':[('readonly',True)]}),
        'previous_phase_ids': fields.many2many('project.phase', 'project_phase_rel', 'next_phase_id', 'prv_phase_id', 'Previous Phases', states={'cancelled':[('readonly',True)]}),
        'sequence': fields.integer('Sequence', select=True, help="Gives the sequence order when displaying a list of phases."),
        'duration': fields.float('Duration', required=True, help="By default in days", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
        'product_uom': fields.many2one('product.uom', 'Duration Unit of Measure', required=True, help="Unit of Measure (Unit of Measure) is the unit of measurement for Duration", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
        'task_ids': fields.one2many('project.task', 'phase_id', "Project Tasks", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
        'user_force_ids': fields.many2many('res.users', string='Force Assigned Users'),
        'user_ids': fields.one2many('project.user.allocation', 'phase_id', "Assigned Users",states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]},
            help="The resources on the project can be computed automatically by the scheduler."),
        'state': fields.selection([('draft', 'New'), ('cancelled', 'Cancelled'),('open', 'In Progress'), ('pending', 'Pending'), ('done', 'Done')], 'Status', readonly=True, required=True,
                                  help='If the phase is created the state \'Draft\'.\n If the phase is started, the state becomes \'In Progress\'.\n If review is needed the phase is in \'Pending\' state.\
                                  \n If the phase is over, the states is set to \'Done\'.'),
        'progress': fields.function(_compute_progress, string='Progress', help="Computed based on related tasks"),
     }
    _defaults = {
        'state': 'draft',
        'sequence': 10,
        'product_uom': lambda self,cr,uid,c: self.pool.get('product.uom').search(cr, uid, [('name', '=', _('Day'))], context=c)[0]
    }
    _order = "project_id, date_start, sequence"
    _constraints = [
        (_check_recursion,'Loops in phases not allowed',['next_phase_ids', 'previous_phase_ids']),
        (_check_dates, 'Phase start-date must be lower than phase end-date.', ['date_start', 'date_end']),
    ]

    def onchange_project(self, cr, uid, ids, project, context=None):
        return {}

    def copy(self, cr, uid, id, default=None, context=None):
        if default is None:
            default = {}
        if not default.get('name', False):
            default['name'] = self.browse(cr, uid, id, context=context).name + _(' (copy)')
        return super(project_phase, self).copy(cr, uid, id, default, context)

    def set_draft(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {'state': 'draft'})
        return True

    def set_open(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {'state': 'open'})
        return True

    def set_pending(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {'state': 'pending'})
        return True

    def set_cancel(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {'state': 'cancelled'})
        return True

    def set_done(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {'state': 'done'})
        return True

    def generate_phase(self, cr, uid, phases, context=None):
        context = context or {}
        result = ""

        task_pool = self.pool.get('project.task')
        for phase in phases:
            if phase.state in ('done','cancelled'):
                continue
            duration_uom = {
                'days': 'd', 'day': 'd', 'd':'d',
                'months': 'm', 'month':'month', 'm':'m',
                'weeks': 'w', 'week': 'w', 'w':'w',
                'hours': 'H', 'hour': 'H', 'h':'H',
            }.get(phase.product_uom.name.lower(), "H")
            duration = str(phase.duration) + duration_uom
            result += '''
    def Phase_%s():
        effort = \"%s\"''' % (phase.id, duration)
            start = []
            if phase.constraint_date_start:
                start.append('datetime.datetime.strptime("'+str(phase.constraint_date_start)+'", "%Y-%m-%d %H:%M:%S")')
            for previous_phase in phase.previous_phase_ids:
                start.append("up.Phase_%s.end" % (previous_phase.id,))
            if start:
                result += '''
        start = max(%s)
''' % (','.join(start))

            if phase.user_force_ids:
                result += '''
        resource = %s
''' % '|'.join(map(lambda x: 'User_'+str(x.id), phase.user_force_ids))

            result += task_pool._generate_task(cr, uid, phase.task_ids, ident=8, context=context)
            result += "\n"

        return result
Esempio n. 37
0
        'replan': lambda self,cr,uid,record, groups_code: record.state == 'done',
        'normal_mode_finished': lambda self,cr,uid,record, groups_code: self._task_survey_rights(cr, uid, record, groups_code) and record.state == 'open',
        'normal_mode_unfinished': lambda self,cr,uid,record, groups_code: self._task_survey_rights(cr, uid, record, groups_code) and record.state == 'open',
        'light_mode_finished': lambda self,cr,uid,record, groups_code: self._task_survey_rights(cr, uid, record, groups_code) and record.state == 'draft',
        'light_mode_unfinished': lambda self,cr,uid,record, groups_code: self._task_survey_rights(cr, uid, record, groups_code) and record.state == 'draft',
        'modify': lambda self,cr,uid,record, groups_code: True,

        }



    _columns = {
        'active':fields.function(_get_active, method=True,type='boolean', store=False),
        'ask_id': fields.many2one('openstc.ask', 'Demande', ondelete='set null', select="1"),
        'project_id': fields.many2one('project.project', 'Intervention', ondelete='set null'),
        'equipment_ids':fields.many2many('openstc.equipment', 'openstc_equipment_task_rel', 'task_id', 'equipment_id', 'Equipments'),
        'consumable_ids':fields.many2many('openbase.consumable', 'openbase_consumable_task_rel', 'task_id', 'consumable_id', 'Fournitures'),
        'parent_id': fields.many2one('project.task', 'Parent Task'),
        'intervention_assignement_id':fields.many2one('openstc.intervention.assignement', 'Assignement'),
        'absent_type_id':fields.many2one('openstc.absent.type', 'Type d''abscence'),
        'category_id':fields.many2one('openstc.task.category', 'Category'),
        'state': fields.selection([('absent', 'Absent'),('draft', 'New'),('open', 'In Progress'),('pending', 'Pending'), ('done', 'Done'), ('cancelled', 'Cancelled')], 'State', readonly=True, required=True,
                                  help='If the task is created the state is \'Draft\'.\n If the task is started, the state becomes \'In Progress\'.\n If review is needed the task is in \'Pending\' state.\
                                  \n If the task is over, the states is set to \'Done\'.'),
        'team_id': fields.many2one('openstc.team', 'Team'),

        'km': fields.integer('Km', select=1),
        'oil_qtity': fields.float('oil quantity', select=1),
        'oil_price': fields.float('oil price', select=1),
        'site1':fields.related('project_id','site1',type='many2one',relation='openstc.site', string='Site',store={'project.task':[lambda self,cr,uid,ids,ctx={}:ids, ['project_id'], 10],
                                                                                                                  'project.project':[_get_task_from_inter, ['site1'],11]}),
Esempio n. 38
0
class equipment(OpenbaseCore):
    _name = "openstc.equipment"
    _description = "openstc.equipment"
    #_inherit = 'product.product'
    _inherits = {'product.product': "product_product_id"}
    ## @return: "{name} / {categ_id}" (if categ_id is set, else "name" only)
    ## 
    def name_get(self, cr, uid, ids, context=None):
        if not len(ids):
            return []
        reads = self.read(cr, uid, ids, ['name','categ_id'], context=context)
        res = []
        for record in reads:
            #hack to avoid bugs on equipments stored without product_product_id
            if 'name' in record and record['name']:
                name = record['name']
                if record['categ_id']:
                    name =  name + ' / '+ record['categ_id'][1]
                res.append((record['id'], name))
        return res

    def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
        res = self.name_get(cr, uid, ids, context=context)
        return dict(res)


    _fields_names = {'service_names':'service_ids',
                    'maintenance_service_names':'maintenance_service_ids',
                    'service_bookable_names':'service_bookable_ids',
                    'partner_type_bookable_names':'partner_type_bookable_ids'}

    _columns = {
            'immat': fields.char('Imatt', size=128),
            'complete_name': fields.function(_name_get_fnc, type="char", string='Name',method=True, select=True, store={'openstc.equipment':[lambda self,cr,uid,ids,ctx={}:ids, ['name','categ_id'], 10]}),
            'product_product_id': fields.many2one('product.product', 'Product', help="", ondelete="cascade"),
            #Service authorized to use equipment
            'service_ids':fields.many2many('openstc.service', 'openstc_equipment_services_rel', 'equipment_id', 'service_id', 'Services'),
            'internal_use':fields.boolean('Internal Use', help='Means that this equipment can be used in intervention, or be the target of intervention request.'),
            #Services authorized to book equipment
            'service_bookable_ids':fields.many2many('openstc.service', 'openstc_equipment_bookable_services_rel', 'equipment_id', 'service_id', 'Services'),
            'internal_booking':fields.boolean('Internal Booking', help="Means that this equipment can be booked by internal departments"),
            #Partner types authorized to book equipment
            'partner_type_bookable_ids':fields.many2many('openstc.partner.type', 'openstc_equipment_bookable_partner_type_rel', 'equipment_id', 'partner_type_id', 'Services'),
            'external_booking':fields.boolean('External Booking', help="Means that this equipment can be booked by external partners"),

            #Service owner
            'service':fields.many2one('openstc.service', 'Service'),
            'maintenance_service_ids': fields.many2many('openstc.service','openstc_equipement_maintenance_services_rel','equipment_id','service_id', 'Maintenance services'),

            'marque': fields.char('Marque', size=128),
            'type': fields.char('Type', size=128),
            'usage': fields.char('Usage', size=128),

            'technical_vehicle': fields.boolean('Technical vehicle'),
            'commercial_vehicle': fields.boolean('Commercial vehicle'),

            'small_material': fields.boolean('Small'),
            'fat_material': fields.boolean('Fat'),

            'cv': fields.integer('CV', select=1),
            'purchase_date':fields.date('Date of purchase'),
            'time': fields.integer('Time', select=1),
            'km': fields.integer('Km', select=1),

            'manager_id':fields.many2one('res.users','Responsable'),
            'energy_type':fields.char('Type d\'énergie',size=128),
            'length_amort':fields.integer('Durée d\'amortissement'),
            'purchase_price':fields.float('Prix d\'achat',digits=(6,2)),
            'hour_price':fields.float('Hour price', digits=(4,2)),
            'built_date':fields.date('Built Date'),
            'warranty_date':fields.date('End date of Warranty')
            #'year': fields.integer('Year', select=1),
            #Calcul total price and liters
            #'oil_qtity': fields.integer('oil quantity', select=1),
            #'oil_price': fields.integer('oil price', select=1),
        }
    _defaults = {
         'type_prod':'materiel',
         'internal_use': False,
         'type':'service'
        }

    """ @note: Override to force qty of product to 1 for openstc.site
    """
    def create(self, cr, uid, vals, context=None):
        ret = super(equipment, self).create(cr, uid, vals, context=context)
        equipmt = self.read(cr, uid, ret, ['product_product_id'])
        prod_obj = self.pool.get('product.product')
        prod_obj.write(cr, uid, equipmt['product_product_id'][0], {'type':'service'}, context=context)
        return ret
Esempio n. 39
0
        ('draft', 'Request for Quotation'),
        ('wait', 'Waiting'),
        ('confirmed', 'Waiting Procurement Manager Approve'),
        ('confirmed2', 'Waiting Head of Procurement Division'),
        ('confirmed3', 'Waiting Head of Division Approve'),
        ('confirmed4', 'Waiting CEO Approve'),
        ('approved', 'Approved'),
        ('except_picking', 'Shipping Exception'),
        ('except_invoice', 'Invoice Exception'),
        ('done', 'Done'),
        ('cancel', 'Cancelled')
    ]

    _columns = {
        'state'                 : fields.selection(STATE_SELECTION, 'State', readonly=True, help="The state of the purchase order or the quotation request. A quotation is a purchase order in a 'Draft' state. Then the order has to be confirmed by the user, the state switch to 'Confirmed'. Then the supplier must confirm the order to change the state to 'Approved'. When the purchase order is paid and received, the state becomes 'Done'. If a cancel action occurs in the invoice or in the reception of goods, the state becomes in exception.", select=True),
        'budget_info_ids_po'    : fields.many2many('budget.info.po', 'budget_info_rel_po', 'order_id', 'budget_info_id_po', 'Budget Line', readonly=True),
        'budget_note'           : fields.text('Budget Note'),
        'budget_note_line_ids'  : fields.one2many('budget.note.po', 'order_id', 'Budget Note History'),
        
        #######DICOUNT#####################
        'amount_untaxed': fields.function(_amount_all, method=True, digits_compute= dp.get_precision('Purchase Price'), string='Untaxed Amount',
            store={
                'purchase.order.line': (_get_order, None, 10),
                'purchase.order': (lambda self, cr, uid, ids, c={}: ids, ['discount_total'], 20),
            }, multi="sums", help="The amount without tax"),
        'amount_tax': fields.function(_amount_all, method=True, digits_compute= dp.get_precision('Purchase Price'), string='Taxes',
            store={
                'purchase.order.line': (_get_order, None, 10),
                'purchase.order': (lambda self, cr, uid, ids, c={}: ids, ['discount_total'], 20),
            }, multi="sums", help="The tax amount"),
        'amount_total': fields.function(_amount_all, method=True, digits_compute= dp.get_precision('Purchase Price'), string='Total',
Esempio n. 40
0
class hr_interview(osv.osv):
    _name = "hr.interview"
    _description = "Interview Evaluation"

    def eval_performance(self, cr, uid, ids, *args):
        tech_obj = self.pool.get("technical.skill")
        tot_marks = obt_marks = 0
        tech_id = tech_obj.search(cr, uid, [('candidate_id', '=', ids[0])])
        if tech_id:
            for rec in tech_obj.browse(cr, uid, tech_id):
                tot_marks += rec.tot_marks
                obt_marks += rec.obt_marks
            self.write(cr, uid, ids,
                       {'performance': (obt_marks * 100) / tot_marks})
        return True

    def _constraint_obt_marks(self, cr, uid, ids):
        tech_skill_obj = self.pool.get("technical.skill")
        tech_skill_ids = tech_skill_obj.search(cr, uid,
                                               [('candidate_id', '=', ids[0])])
        for rec in tech_skill_obj.browse(cr, uid, tech_skill_ids):
            if rec['obt_marks'] > rec['tot_marks'] or rec['tot_marks'] <= 0:
                return False
        return True

    def _constraint_evaluator(self, cr, uid, ids):
        rec = self.read(cr, uid, ids[0])
        if rec['reference_id']:
            if rec['reference_id'][0] in rec['evaluator_ids']:
                return False
        return True

    _columns = {
        'hr_id':
        fields.char("Interview ID", size=64),
        'name':
        fields.char("Candidate Name", size=64, required=True, select=True),
        'crm_case_id':
        fields.many2one('crm.case', "Case"),
        'email':
        fields.char("E-mail", size=64, required=True),
        'mobile_no':
        fields.char("Mobile", size=64),
        'date':
        fields.datetime('Scheduled Date'),
        'exam_date':
        fields.datetime('Exam On'),
        'education':
        fields.selection([("be_ce", "BE Computers"), ("be_it", "BE IT"),
                          ("bsc_it", "BSc IT"), ("bca", "BCA"),
                          ("btech_ce", "BTech Computers"),
                          ("btech_it", "BTech IT"), ("mca", "MCA"),
                          ("msc_it", "MSc IT"),
                          ("mtech_ce", "MTech Computers"), ("other", "Other")],
                         "Education"),
        'category_id':
        fields.many2one("candidate.category", "Category"),
        'experience_id':
        fields.many2one("candidate.experience", "Experience"),
        'remarks':
        fields.text("Remarks"),
        'evaluator_ids':
        fields.many2many("hr.employee", 'hr_empl_rel', 'hr_cand_id', 'emp_id',
                         "Evaluator"),
        'reference_id':
        fields.many2one("hr.employee", "Reference"),
        'tech_skills_ids':
        fields.one2many("technical.skill", "candidate_id",
                        "Technology Skills"),
        'performance':
        fields.float("Performance (%)", readonly=True),
        'state':
        fields.selection([("draft", "Draft"), ('scheduled', 'Scheduled'),
                          ('re-scheduled', 'Re-Scheduled'),
                          ('start-interview', 'Start-Interview'),
                          ('end-interview', 'End-Interview'),
                          ("selected", "Selected"), ('rejected', 'Rejected'),
                          ("cancel", "Cancel")],
                         "State",
                         readonly=True,
                         select=1),
        'history_log_ids':
        fields.one2many("hr.interview.log",
                        "history_id",
                        "Interview Logs",
                        readonly=True),
    }
    _defaults = {
        'state':
        lambda *a: "draft",
        'hr_id':
        lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(
            cr, uid, 'hr.interview'),
    }

    _constraints = [
        (_constraint_obt_marks,
         _('Obtained marks cannot be greater than Total marks!'),
         ['obt_marks']),
        (_constraint_evaluator, "Reference Person cannot be among Evaluators!",
         ['reference_id'])
    ]

    def state_scheduled(self, cr, uid, ids, *arg):
        self.write(cr, uid, ids, {'state': 'scheduled'})
        self._log(cr, uid, ids, 'scheduled')
        return True

    def state_cancel(self, cr, uid, ids, *arg):
        self.write(cr, uid, ids, {'state': 'cancel'})
        self._log(cr, uid, ids, 'cancel')
        return True

    def state_re_scheduled(self, cr, uid, ids, *arg):
        self.write(cr, uid, ids, {'state': 're-scheduled'})
        self._log(cr, uid, ids, 're-scheduled')
        return True

    def state_start_interview(self, cr, uid, ids, *arg):
        self.write(cr, uid, ids, {'state': 'start-interview'})
        self._log(cr, uid, ids, 'start-interview')
        return True

    def state_end_interview(self, cr, uid, ids, *arg):
        self.write(cr, uid, ids, {'state': 'end-interview'})
        self._log(cr, uid, ids, 'end-interview')
        return True

    def state_selected(self, cr, uid, ids, *arg):
        self.write(cr, uid, ids, {'state': 'selected'})
        self._log(cr, uid, ids, 'selected')
        return True

    def state_rejected(self, cr, uid, ids, *arg):
        self.write(cr, uid, ids, {'state': 'rejected'})
        self._log(cr, uid, ids, 'rejected')
        return True

    def _log(self, cr, uid, ids, action):
        his_obj = self.pool.get("hr.interview.log")
        his_obj.create(
            cr, uid, {
                'state': action,
                'date': strftime("%Y-%m-%d %H:%M:%S"),
                "user_id": uid,
                'history_id': ids[0]
            })
        return True

    def copy(self, cr, uid, id, default=None, context=None):
        raise osv.except_osv(_('Error !'),
                             _('You cannot duplicate the resource!'))
        return False

    def create(self, cr, uid, vals, context=None):
        que_obj = self.pool.get("category.question")
        tech_skill_obj = self.pool.get("technical.skill")
        hr_id = super(hr_interview, self).create(cr,
                                                 uid,
                                                 vals,
                                                 context=context)
        if vals.get('category_id', False):
            cate_id = vals.get('category_id')
            que_ids = que_obj.search(cr,
                                     uid, [('category_id', '=', int(cate_id))],
                                     context=context)
            for rec in que_obj.browse(cr, uid, que_ids, context=context):
                tech_skill_obj.create(
                    cr, uid, {
                        'name': rec.name,
                        'tot_marks': rec.tot_marks,
                        'candidate_id': hr_id
                    })
        self._log(cr, uid, [hr_id], 'draft')
        return hr_id

    def write(self, cr, uid, ids, vals, context=None):
        que_obj = self.pool.get("category.question")
        tech_skill_obj = self.pool.get("technical.skill")
        if 'category_id' in vals:
            cate_id = vals['category_id']
            que_ids = que_obj.search(cr, uid,
                                     [('category_id', '=', int(cate_id))])
            tech_skill_ids = tech_skill_obj.search(
                cr, uid, [('candidate_id', '=', ids[0])])
            if tech_skill_ids:
                tech_skill_obj.unlink(cr, uid, tech_skill_ids)
            for rec in que_obj.browse(cr, uid, que_ids):
                tech_skill_obj.create(
                    cr, uid, {
                        'name': rec.name,
                        'tot_marks': rec.tot_marks,
                        'candidate_id': ids[0]
                    })
        return super(hr_interview, self).write(cr,
                                               uid,
                                               ids,
                                               vals,
                                               context=context)