예제 #1
0
class website_wishlist(osv.osv):
    _name = "website.wishlist"

    def create(self, cr, uid, vals, context=None):
        if vals.has_key('template_id') and vals.has_key('partner_id'):
            check = self.search(cr, SUPERUSER_ID,
                                [('template_id', '=', vals['template_id']),
                                 ('partner_id', '=', vals['partner_id'])])
            if check:
                return check[0]
        return super(website_wishlist, self).create(cr, uid, vals, context)

    def get_wishlist_products(self, cr, uid, context=None):
        obj = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid)
        if obj.partner_id:
            if obj.partner_id.website_wishlist:
                return obj.partner_id.website_wishlist
        return False

    def _get_uid(self, cr, uid, ids, names, args, context=None):
        res = {}
        res = dict.fromkeys(ids, uid)
        return res

    _columns = {
        'template_id': fields.many2one('product.product', 'Product'),
        'partner_id': fields.many2one('res.partner', 'Partner'),
        'user_id': fields.function(_get_uid, type="integer", string='User ID'),
    }
예제 #2
0
class stock_quant(osv.osv):
    """
    Quants are the smallest unit of stock physical instances
    """
    _inherit = "stock.quant"

    def _calc_inventory_value(self, cr, uid, ids, name, attr, context=None):
        context = dict(context or {})
        res = {}
        uid_company_id = self.pool.get('res.users').browse(
            cr, uid, uid, context=context).company_id.id
        for quant in self.browse(cr, uid, ids, context=context):
            context.pop('force_company', None)
            if quant.company_id.id != uid_company_id:
                #if the company of the quant is different than the current user company, force the company in the context
                #then re-do a browse to read the property fields for the good company.
                context['force_company'] = quant.company_id.id
                quant = self.browse(cr, uid, quant.id, context=context)
            res[quant.id] = self._get_inventory_value(cr,
                                                      uid,
                                                      quant,
                                                      context=context)
        return res

    _columns = {
        'inventory_value':
        fields.function(_calc_inventory_value,
                        string="Inventory Value",
                        type='float',
                        readonly=True,
                        digits_compute=dp.get_precision('Product Price')),
    }
class nomor_faktur_pajak(osv.osv):
    _name = "nomor.faktur.pajak"
    _description = 'Nomor faktur Pajak'

    def _nomor_faktur(self, cr, uid, ids, nomorfaktur, arg, context=None):
        res = {}
        for nomor in self.browse(cr, uid, ids, context):    
            res[nomor.id] = "%s.%s.%s" % (nomor.nomor_perusahaan, nomor.tahun_penerbit, nomor.nomor_urut)
        return res
    
    _columns = {
        'nomor_perusahaan' : fields.char('Nomor Perusahaan', size=3),
        'tahun_penerbit': fields.char('Tahun Penerbit', size=2),
        'nomor_urut': fields.char('Nomor Urut', size=8),
        'name': fields.function(_nomor_faktur, type='char', string="Nomor Faktur", store=True),
        'invoice_id': fields.many2one('account.invoice','Invoice No'),
        'partner_id'    : fields.many2one('res.partner', "Customer"),
        'dpp'   : fields.float('Untaxed Amount'),
        'tax_amount': fields.float("Tax Amount"),
        'date_used' : fields.date("Used Date"),
        'company_id': fields.many2one('res.company', 'Company'),
        'currency_id': fields.many2one('res.currency', 'Currency'),
        'type'      : fields.selection([('in','Faktur Pajak Masukan'),('out','Faktur Pajak Keluaran')],'Type'),
        'status': fields.selection([('1','Used'),('0','Not Used')],'Status'),
    }
    
    _defaults = {
        'status': '0',
    }
    
    _sql_constraints = [
        ('faktur_unique', 'unique(nomor_perusahaan,tahun_penerbit,nomor_urut)', 'Number Faktur Must Be Unique.'),
    ]
예제 #4
0
class res_partner(models.Model):
    _inherit = 'res.partner'

    
    def _sale_credit_get(self, cr, uid, ids, field_names, arg, context=None):
        ctx = context.copy()
        ctx['all_fiscalyear'] = True
        #query = self.pool.get('account.move.line')._query_get(cr, uid, context=ctx)
        cr.execute("""SELECT p.id, 'receivable', s.residual
                      FROM res_partner p
                      JOIN sale_order s ON (s.partner_id = p.id)
                      WHERE  p.id IN %s
                          AND s.state != 'cancel'
                          AND s.state != 'draft'
                      union all
                      SELECT p.id, 'receivable', i.residual
                      FROM res_partner p
                      JOIN account_invoice i ON (i.partner_id=p.id)
                      WHERE p.id IN %s
                          AND i.state = 'open'
                      """,
                   (tuple(ids),))
        maps = {'receivable':'credit', 'payable':'debit' }
        res = {}
        for id in ids:
            res[id] = {}.fromkeys(field_names, 0)
        for pid,type,val in cr.fetchall():
            if val is None: val=0
            res[pid][maps[type]] = (type=='receivable') and val or -val
        return res


    total_credit = fields.function(_sale_credit_get, string='Total Receivable', store=True)
예제 #5
0
class account_analytic_account(models.Model):
    _inherit = 'account.analytic.account'

    def _get_full_name(self, cr, uid, ids, name=None, args=None, context=None):
        if context == None:
            context = {}
        res = {}
        for elmt in self.browse(cr, uid, ids, context=context):
            segment = elmt.segment and '.' in elmt.segment and elmt.segment.split('.')[1] or 'NN'
            res[elmt.id] = '%s - %s' % (segment, self._get_one_full_name(elmt))
        return res

    _columns = {
        'complete_name': fields.function(_get_full_name, type='char', string='Full Name')
    }
예제 #6
0
class upload_images(osv.osv):
    _name = 'upload_images.tutorial'
    _description = 'Tutorial image uploading'

    def _get_image(self, cr, uid, ids, name, args, context=None):
        result = dict.fromkeys(ids, False)
        for obj in self.browse(cr, uid, ids, context=context):
            result[obj.id] = tools.image_get_resized_images(obj.image)
        return result

    def _set_image(self, cr, uid, id, name, value, args, context=None):
        return self.write(cr,
                          uid, [id],
                          {'image': tools.image_resize_image_big(value)},
                          context=context)

    _columns = {
    'name': fields.char('Name', required=True, translate=True),
    'image': fields.binary("Image",
            help="This field holds the image used as image for our customers, limited to 1024x1024px."),
    'image_medium': fields.function(_get_image, fnct_inv=_set_image,
            string="Image (auto-resized to 128x128):", type="binary", multi="_get_image",
            store={
                'upload_images.tutorial': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
            },help="Medium-sized image of the category. It is automatically "\
                 "resized as a 128x128px image, with aspect ratio preserved. "\
                 "Use this field in form views or some kanban views."),
    'image_small': fields.function(_get_image, fnct_inv=_set_image,
            string="Image (auto-resized to 64x64):", type="binary", multi="_get_image",
            store={
                'upload_images.tutorial': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
            },
            help="Small-sized image of the category. It is automatically "\
                 "resized as a 64x64px image, with aspect ratio preserved. "\
                 "Use this field anywhere a small image is required."),
    }
예제 #7
0
class hr_payslip_worked_days(models.Model):
    _inherit = 'hr.payslip.worked_days'

    def _get_total(self, cr, uid, ids, field_name, arg=None, context=None):
        res = {}
        for wd in self.browse(cr, uid, ids, context=context):
            res[wd.id] = wd.number_of_hours \
                * wd.hourly_rate * wd.rate / 100
        return res

    _columns = {
        'hourly_rate':
        fields.float('Hourly Rate',
                     help="""\
The employee's standard hourly rate for one hour of work.
Example, 25 Euros per hour."""),
        'rate':
        fields.float('Rate (%)',
                     help="""\
The rate by which to multiply the standard hourly rate.
Example, an overtime hour could be paid the standard rate multiplied by 150%.
"""),

        # When a worked day has a number of hours and an hourly rate,
        # it is necessary to have a date interval,
        # because hourly rates are likely to change over the time.
        'date_from':
        fields.date('Date From'),
        'date_to':
        fields.date('Date To'),
        'total':
        fields.function(
            _get_total,
            method=True,
            type="float",
            string="Total",
        ),
    }
    _defaults = {
        'hourly_rate': 0,
        'rate': 100,
        'date_from':
        lambda *a: datetime.now().strftime(DEFAULT_SERVER_DATE_FORMAT),
        'date_to':
        lambda *a: datetime.now().strftime(DEFAULT_SERVER_DATE_FORMAT)
    }
예제 #8
0
파일: models.py 프로젝트: hwua/openerp
class SurveUserInput(osv.Model):
    _inherit = "survey.user_input"

    def _quizz_get_score(self, cr, uid, ids, name, args, context=None):
        ret = dict()
        for user_input in self.browse(cr, uid, ids, context=context):
            sn = 0.0
            user_option = {}  #选择的成绩

            for uil in user_input.user_input_line_ids:
                if (uil.question_id.type == 'multiple_choice'):
                    # 已回答的题目和用户选项
                    if not user_option.has_key(uil.question_id.id):
                        user_option[uil.question_id.id] = []
                    user_option[uil.question_id.id].append(
                        uil.value_suggested.id)

                else:
                    sn += uil.quizz_mark

            if user_option:
                for (question, labels) in user_option.items():
                    right = self.pool.get('survey.label').search(
                        cr, uid, [('question_id', '=', question),
                                  ('quizz_mark', '>', 0.0)], None)  # 此题的正确选项
                    wrong = list(set(labels).difference(
                        set(right)))  # 用户选择的错误选项

                    if wrong == [] and right == labels:  #无错,正确值和题目正确值相同,即合计分数
                        survey_labels = self.pool.get('survey.label').browse(
                            cr, uid, labels)
                        sn += sum([sl.quizz_mark for sl in survey_labels]
                                  or [0.0])

            ret[user_input.id] = sn

        return ret

    _columns = {
        'quizz_score':
        fields.function(_quizz_get_score,
                        type="float",
                        string="Score for the quiz")
    }
예제 #9
0
class account_invoice(osv.osv):
    _name = "account.invoice"
    _inherit = "account.invoice"

    def _sale_amount_text(self, cr, uid, ids, name, args, context=None):
        res = {}
        for line in self.browse(cr, uid, ids, context=context):
            if line.amount_total <> 0.00:
                res[line.id] = trad(int(line.amount_total)).upper()
        return res

    _columns = {
        'object':
        fields.char('Objet', required=False, help="Objet de l'offre"),
        'amount_text':
        fields.function(_sale_amount_text,
                        string='en lettre',
                        type='char',
                        help="Amount in text",
                        readonly=True),
    }
예제 #10
0
파일: sale.py 프로젝트: hwua/openerp
class sale_order_loan_grant_schedule(osv.osv):
    _inherit = 'sale.order'

    def _amount_grant_schedule_number(self,
                                      cr,
                                      uid,
                                      ids,
                                      field_name,
                                      arg,
                                      context=None):
        res = dict(map(lambda x: (x, 0), ids))
        for orders in self.browse(cr, uid, ids, context):
            res[orders.id] = str(
                orders.amount_grant_already_number) + '/' + str(
                    orders.amount_grant_number)
        return res

    _columns = {
        'amount_grant_schedule_number':
        fields.function(_amount_grant_schedule_number,
                        string='已完成/总进度',
                        type='char'),
    }
예제 #11
0
class account_voucher(osv.osv):
    _name ='account.voucher'
    _inherit = 'account.voucher'

    def _amount_text(self, cr, uid, ids, field_name, args, context=None):
        if not context:
            context = {}
        res = {}
        amount_to_text = ''
        for record in self.browse(cr, uid, ids, context=context):
            if record.amount > 0:
                amount_to_text = amount_to.get_amount_to_text(
                    self, record.amount, 'es_cheque', record.currency_id.name
                    )
            res[record.id] = amount_to_text
        return res


    _columns = {        
        'amount_to_text': fields.function(_amount_text, method=True, string='Monto en Letra', type='char', size=256, store=True),


    }
예제 #12
0
class sale_order(osv.osv):
    _name ='sale.order'
    _inherit = 'sale.order'

    def _amount_text(self, cr, uid, ids, field_name, args, context=None):
        if not context:
            context = {}
        res = {}
        amount_to_text = ''
        for record in self.browse(cr, uid, ids, context=context):
            if record.amount_total > 0:
                amount_to_text = amount_to.get_amount_to_text(
                    self, record.amount_total, 'es_cheque', record.pricelist_id.currency_id.name
                    )
            res[record.id] = amount_to_text
        return res


    _columns = {        
        'amount_to_text': fields.function(_amount_text, method=True, string='Monto en Letra', type='char', size=256, store=True),
        'pay_method_id': fields.many2one('pay.method', 'Forma de Pago'),
        'transport': fields.char('Transporte', size=128),

    }
예제 #13
0
class product_product(osv.osv):

    _inherit = "product.product"

    @api.one
    @api.onchange('lst_price') # if these fields are changed, call method
    def check_change_price(self):
        #import pdb;pdb.set_trace();
        pricelists = self.env['product.pricelist'].search([])
        pricelist = pricelists[0]

        return {}

    def product_meli_get_products( self, cr, uid, context=None ):
        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        company = user_obj.company_id
        product_obj = self.pool.get('product.product')
        #product = product_obj.browse(cr, uid, ids[0])

        CLIENT_ID = company.mercadolibre_client_id
        CLIENT_SECRET = company.mercadolibre_secret_key
        ACCESS_TOKEN = company.mercadolibre_access_token
        REFRESH_TOKEN = company.mercadolibre_refresh_token

        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

        url_login_meli = meli.auth_url(redirect_URI=REDIRECT_URI)
        #url_login_oerp = "/meli_login"

        response = meli.get("/users/"+company.mercadolibre_seller_id+"/items/search", {'access_token':meli.access_token})

        print "product_meli_get_products: " + response.content
        rjson = response.json()

        if 'error' in rjson:
            if rjson['message']=='invalid_token' or rjson['message']=='expired_token':
                ACCESS_TOKEN = ''
                REFRESH_TOKEN = ''
                company.write({'mercadolibre_access_token': ACCESS_TOKEN, 'mercadolibre_refresh_token': REFRESH_TOKEN, 'mercadolibre_code': '' } )
            return {
	        "type": "ir.actions.act_url",
	        "url": url_login_meli,
	        "target": "new",
        }

        results = rjson['results']
        if (results):
            for item_id in results:
                print item_id
                posting_id = self.pool.get('product.product').search(cr,uid,[('meli_id','=',item_id)])
                response = meli.get("/items/"+item_id, {'access_token':meli.access_token})
                rjson = response.json()
                if (posting_id):
                    print "Item already in database: " + str(posting_id[0])
                else:
                    idcreated = self.pool.get('product.product').create(cr,uid,{ 'name': rjson['title'], 'meli_id': rjson['id'] })
                    if (idcreated):
                        product = product_obj.browse(cr, uid, idcreated)
                        product_obj.product_meli_get_product( cr, uid, [idcreated] )
        return {}

    def product_meli_get_product( self, cr, uid, ids, context=None ):
        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        company = user_obj.company_id
        product_obj = self.pool.get('product.product')
        product = product_obj.browse(cr, uid, ids[0])

        product_template_obj = self.pool.get('product.template')
        product_template = product_template_obj.browse(cr, uid, product.product_tmpl_id.id)

        CLIENT_ID = company.mercadolibre_client_id
        CLIENT_SECRET = company.mercadolibre_secret_key
        ACCESS_TOKEN = company.mercadolibre_access_token
        REFRESH_TOKEN = company.mercadolibre_refresh_token

        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

        response = meli.get("/items/"+product.meli_id, {'access_token':meli.access_token})

        print "product_meli_get_product: " + response.content
        rjson = response.json()

        des = ''
        desplain = ''
        vid = ''
        if 'error' in rjson:
            return {}

        #TODO: traer la descripcion: con
        #https://api.mercadolibre.com/items/{ITEM_ID}/description?access_token=$ACCESS_TOKEN
        if rjson['descriptions']:
            response2 = meli.get("/items/"+product.meli_id+"/description", {'access_token':meli.access_token})
            rjson2 = response2.json()
            des = rjson2['text']
            desplain = rjson2['plain_text']
            if (len(des)>0):
                desplain = des

        #TODO: verificar q es un video
        if rjson['video_id']:
            vid = ''

        #TODO: traer las imagenes
        #TODO:
        pictures = rjson['pictures']
        if pictures and len(pictures):
            thumbnail_url = pictures[0]['url']
            image = urllib2.urlopen(thumbnail_url).read()
            image_base64 = base64.encodestring(image)
            product.image_medium = image_base64
            #if (len(pictures)>1):
                #complete product images:
                #delete all images...

        #categories
        mlcatid = ""
        if ('category_id' in rjson):
            category_id = rjson['category_id']
            ml_cat_id = self.pool.get('mercadolibre.category').search(cr,uid,[('meli_category_id','=',category_id)])
            if (ml_cat_id):
              print "category exists!" + str(ml_cat_id)
              mlcatid = ml_cat_id[0]
            else:
              print "Creating category: " + str(category_id)
              #https://api.mercadolibre.com/categories/MLA1743
              response_cat = meli.get("/categories/"+str(category_id), {'access_token':meli.access_token})
              rjson_cat = response_cat.json()
              print "category:" + str(rjson_cat)
              fullname = ""
              if ("path_from_root" in rjson_cat):
                  path_from_root = rjson_cat["path_from_root"]
                  for path in path_from_root:
                    fullname = fullname + "/" + path["name"]

              #fullname = fullname + "/" + rjson_cat['name']
              print "category fullname:" + fullname
              cat_fields = {
                'name': fullname,
                'meli_category_id': ''+str(category_id),
              }
              ml_cat_id = self.pool.get('mercadolibre.category').create(cr,uid,(cat_fields))
              if (ml_cat_id):
                  mlcatid = ml_cat_id

        imagen_id = ''
        if (len(rjson['pictures'])>0):
            imagen_id = rjson['pictures'][0]['id']

        meli_fields = {
            'name': str(rjson['title']),
            'meli_imagen_id': imagen_id,
            'meli_post_required': True,
            'meli_id': rjson['id'],
            'meli_permalink': rjson['permalink'],
            'meli_title': rjson['title'],
            'meli_description': desplain,
#            'meli_description_banner_id': ,
            'meli_category': mlcatid,
            'meli_listing_type': rjson['listing_type_id'],
            'meli_buying_mode':rjson['buying_mode'],
            'meli_price': str(rjson['price']),
            'meli_price_fixed': True,
            'meli_currency': rjson['currency_id'],
            'meli_condition': rjson['condition'],
            'meli_available_quantity': rjson['available_quantity'],
            'meli_warranty': rjson['warranty'],
##            'meli_imagen_logo': fields.char(string='Imagen Logo', size=256),
##            'meli_imagen_id': fields.char(string='Imagen Id', size=256),
            'meli_imagen_link': rjson['thumbnail'],
##            'meli_multi_imagen_id': fields.char(string='Multi Imagen Ids', size=512),
            'meli_video': str(vid)
        }
        tmpl_fields = {
          'name': str(rjson['title'])
        }
        product.write( meli_fields )
        product_template.write( tmpl_fields )
#{"id":"MLA639109219","site_id":"MLA","title":"Disco Vinilo Queen - Rock - A Kind Of Magic","subtitle":null,"seller_id":171329758,"category_id":"MLA2038","official_store_id":null,"price":31,"base_price":31,"original_price":null,"currency_id":"ARS","initial_quantity":5,"available_quantity":5,"sold_quantity":0,"buying_mode":"buy_it_now","listing_type_id":"free","start_time":"2016-10-17T20:36:22.000Z","stop_time":"2016-12-16T20:36:22.000Z","end_time":"2016-12-16T20:36:22.000Z","expiration_time":null,"condition":"used","permalink":"http://articulo.mercadolibre.com.ar/MLA-639109219-disco-vinilo-queen-rock-a-kind-of-magic-_JM","thumbnail":"http://mla-s1-p.mlstatic.com/256905-MLA25108641321_102016-I.jpg","secure_thumbnail":"https://mla-s1-p.mlstatic.com/256905-MLA25108641321_102016-I.jpg","pictures":[{"id":"256905-MLA25108641321_102016","url":"http://mla-s1-p.mlstatic.com/256905-MLA25108641321_102016-O.jpg","secure_url":"https://mla-s1-p.mlstatic.com/256905-MLA25108641321_102016-O.jpg","size":"500x400","max_size":"960x768","quality":""},{"id":"185215-MLA25150338489_112016","url":"http://www.mercadolibre.com/jm/img?s=STC&v=O&f=proccesing_image_es.jpg","secure_url":"https://www.mercadolibre.com/jm/img?s=STC&v=O&f=proccesing_image_es.jpg","size":"500x500","max_size":"500x500","quality":""}],"video_id":null,"descriptions":[{"id":"MLA639109219-1196717922"}],"accepts_mercadopago":true,"non_mercado_pago_payment_methods":[],"shipping":{"mode":"not_specified","local_pick_up":false,"free_shipping":false,"methods":[],"dimensions":null,"tags":[]},"international_delivery_mode":"none","seller_address":{"id":193196973,"comment":"3B","address_line":"Billinghurst 1711","zip_code":"1425","city":{"id":"TUxBQlBBTDI1MTVa","name":"Palermo"},"state":{"id":"AR-C","name":"Capital Federal"},"country":{"id":"AR","name":"Argentina"},"latitude":-34.5906131,"longitude":-58.4101982,"search_location":{"neighborhood":{"id":"TUxBQlBBTDI1MTVa","name":"Palermo"},"city":{"id":"TUxBQ0NBUGZlZG1sYQ","name":"Capital Federal"},"state":{"id":"TUxBUENBUGw3M2E1","name":"Capital Federal"}}},"seller_contact":null,"location":{},"geolocation":{"latitude":-34.5906131,"longitude":-58.4101982},"coverage_areas":[],"attributes":[],"warnings":[],"listing_source":"","variations":[],"status":"active","sub_status":[],"tags":[],"warranty":null,"catalog_product_id":null,"domain_id":null,"seller_custom_field":null,"parent_item_id":null,"differential_pricing":null,"deal_ids":[],"automatic_relist":false,"date_created":"2016-10-17T20:36:22.000Z","last_updated":"2016-11-07T21:38:10.000Z"}

        return {}

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

        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        company = user_obj.company_id

        REDIRECT_URI = company.mercadolibre_redirect_uri
        CLIENT_ID = company.mercadolibre_client_id
        CLIENT_SECRET = company.mercadolibre_secret_key
        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET)

        url_login_meli = meli.auth_url(redirect_URI=REDIRECT_URI)
        #url_login_oerp = "/meli_login"


        return {
	        "type": "ir.actions.act_url",
	        "url": url_login_meli,
	        "target": "new",
        }

    def product_get_meli_loginstate( self, cr, uid, ids, field_name, attributes, context=None ):
        # recoger el estado y devolver True o False (meli)
        #False if logged ok
        #True if need login
        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        company = user_obj.company_id

        CLIENT_ID = company.mercadolibre_client_id
        CLIENT_SECRET = company.mercadolibre_secret_key
        ACCESS_TOKEN = company.mercadolibre_access_token
        REFRESH_TOKEN = company.mercadolibre_refresh_token

        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

        ML_state = False
        if ACCESS_TOKEN=='':
            ML_state = True
        else:
            response = meli.get("/users/me/", {'access_token':meli.access_token} )
            rjson = response.json()
            if 'error' in rjson:
                if rjson['message']=='invalid_token' or rjson['message']=='expired_token':
                    ACCESS_TOKEN = ''
                    REFRESH_TOKEN = ''
                    company.write({'mercadolibre_access_token': ACCESS_TOKEN, 'mercadolibre_refresh_token': REFRESH_TOKEN, 'mercadolibre_code': '' } )
                    ML_state = True
                    #raise osv.except_osv( _('MELI WARNING'), _('INVALID TOKEN (must login, go to Edit Company and login):  error: %s, message: %s, status: %s') % ( rjson["error"], rjson["message"],rjson["status"],))

        res = {}
        for product in self.browse(cr,uid,ids):
            res[product.id] = ML_state
        return res

    def product_meli_status_close( self, cr, uid, ids, context=None ):
        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        company = user_obj.company_id
        product_obj = self.pool.get('product.product')
        product = product_obj.browse(cr, uid, ids[0])

        CLIENT_ID = company.mercadolibre_client_id
        CLIENT_SECRET = company.mercadolibre_secret_key
        ACCESS_TOKEN = company.mercadolibre_access_token
        REFRESH_TOKEN = company.mercadolibre_refresh_token

        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

        response = meli.put("/items/"+product.meli_id, { 'status': 'closed' }, {'access_token':meli.access_token})

        #print "product_meli_status_close: " + response.content

        return {}

    def product_meli_status_pause( self, cr, uid, ids, context=None ):
        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        company = user_obj.company_id
        product_obj = self.pool.get('product.product')
        product = product_obj.browse(cr, uid, ids[0])

        CLIENT_ID = company.mercadolibre_client_id
        CLIENT_SECRET = company.mercadolibre_secret_key
        ACCESS_TOKEN = company.mercadolibre_access_token
        REFRESH_TOKEN = company.mercadolibre_refresh_token

        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

        response = meli.put("/items/"+product.meli_id, { 'status': 'paused' }, {'access_token':meli.access_token})

        #print "product_meli_status_pause: " + response.content

        return {}

    def product_meli_status_active( self, cr, uid, ids, context=None ):
        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        company = user_obj.company_id
        product_obj = self.pool.get('product.product')
        product = product_obj.browse(cr, uid, ids[0])

        CLIENT_ID = company.mercadolibre_client_id
        CLIENT_SECRET = company.mercadolibre_secret_key
        ACCESS_TOKEN = company.mercadolibre_access_token
        REFRESH_TOKEN = company.mercadolibre_refresh_token

        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

        response = meli.put("/items/"+product.meli_id, { 'status': 'active' }, {'access_token':meli.access_token})

        #print "product_meli_status_active: " + response.content

        return {}

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

        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        company = user_obj.company_id
        product_obj = self.pool.get('product.product')
        product = product_obj.browse(cr, uid, ids[0])

        if product.meli_status!='closed':
            self.product_meli_status_close( cr, uid, ids, context )

        CLIENT_ID = company.mercadolibre_client_id
        CLIENT_SECRET = company.mercadolibre_secret_key
        ACCESS_TOKEN = company.mercadolibre_access_token
        REFRESH_TOKEN = company.mercadolibre_refresh_token

        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

        response = meli.put("/items/"+product.meli_id, { 'deleted': 'true' }, {'access_token':meli.access_token})

        #print "product_meli_delete: " + response.content
        rjson = response.json()
        ML_status = rjson["status"]
        if "error" in rjson:
            ML_status = rjson["error"]
        if "sub_status" in rjson:
            if len(rjson["sub_status"]) and rjson["sub_status"][0]=='deleted':
                product.write({ 'meli_id': '' })

        return {}

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

        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        company = user_obj.company_id

        product_obj = self.pool.get('product.product')
        product = product_obj.browse(cr, uid, ids[0])

        CLIENT_ID = company.mercadolibre_client_id
        CLIENT_SECRET = company.mercadolibre_secret_key
        ACCESS_TOKEN = company.mercadolibre_access_token
        REFRESH_TOKEN = company.mercadolibre_refresh_token

        #
        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

        if product.image==None or product.image==False:
            return { 'status': 'error', 'message': 'no image to upload' }

        # print "product_meli_upload_image"
        #print "product_meli_upload_image: " + response.content
        imagebin = base64.b64decode(product.image)
        imageb64 = product.image
#       print "data:image/png;base64,"+imageb64
#       files = [ ('images', ('image_medium', imagebin, "image/png")) ]
        files = { 'file': ('image.jpg', imagebin, "image/jpeg"), }
        #print  files
        response = meli.upload("/pictures", files, { 'access_token': meli.access_token } )
       # print response.content

        rjson = response.json()
        if ("error" in rjson):
            raise osv.except_osv( _('MELI WARNING'), _('No se pudo cargar la imagen en MELI! Error: %s , Mensaje: %s, Status: %s') % ( rjson["error"], rjson["message"],rjson["status"],))
            return { 'status': 'error', 'message': 'not uploaded'}

        _logger.info( rjson )

        if ("id" in rjson):
            #guardar id
            product.write( { "meli_imagen_id": rjson["id"], "meli_imagen_link": rjson["variations"][0]["url"] })
            #asociar imagen a producto
            if product.meli_id:
                response = meli.post("/items/"+product.meli_id+"/pictures", { 'id': rjson["id"] }, { 'access_token': meli.access_token } )
            else:
                return { 'status': 'warning', 'message': 'uploaded but not assigned' }

        return { 'status': 'success', 'message': 'uploaded and assigned' }

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

        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        company = user_obj.company_id

        product_obj = self.pool.get('product.product')
        product = product_obj.browse(cr, uid, ids[0])

        CLIENT_ID = company.mercadolibre_client_id
        CLIENT_SECRET = company.mercadolibre_secret_key
        ACCESS_TOKEN = company.mercadolibre_access_token
        REFRESH_TOKEN = company.mercadolibre_refresh_token

        #
        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

        if product.images==None:
            return { 'status': 'error', 'message': 'no images to upload' }

        image_ids = []
        c = 0

        #loop over images
        for product_image in product.images:
            if (product_image.image):
                print "product_image.image:" + str(product_image.image)
                imagebin = base64.b64decode( product_image.image )
                #files = { 'file': ('image.png', imagebin, "image/png"), }
                files = { 'file': ('image.jpg', imagebin, "image/jpeg"), }
                response = meli.upload("/pictures", files, { 'access_token': meli.access_token } )
                print "meli upload:" + response.content
                rjson = response.json()
                if ("error" in rjson):
                    raise osv.except_osv( _('MELI WARNING'), _('No se pudo cargar la imagen en MELI! Error: %s , Mensaje: %s, Status: %s') % ( rjson["error"], rjson["message"],rjson["status"],))
                    #return { 'status': 'error', 'message': 'not uploaded'}
                else:
                    image_ids+= [ { 'id': rjson['id'] }]
                    c = c + 1
                    print "image_ids:" + str(image_ids)

        product.write( { "meli_multi_imagen_id": "%s" % (image_ids) } )

        return image_ids


    def product_on_change_meli_banner(self, cr, uid, ids, banner_id ):

        banner_obj = self.pool.get('mercadolibre.banner')

        #solo para saber si ya habia una descripcion completada
        product_obj = self.pool.get('product.product')
        if len(ids):
            product = product_obj.browse(cr, uid, ids[0])
        else:
            product = product_obj.browse(cr, uid, ids)

        banner = banner_obj.browse( cr, uid, banner_id )

        #banner.description
        _logger.info( banner.description )
        result = ""
        if (banner.description!="" and banner.description!=False and product.meli_imagen_link!=""):
            imgtag = "<img style='width: 420px; height: auto;' src='%s'/>" % ( product.meli_imagen_link )
            result = banner.description.replace( "[IMAGEN_PRODUCTO]", imgtag )
            if (result):
                _logger.info( "result: %s" % (result) )
            else:
                result = banner.description

        return { 'value': { 'meli_description' : result } }

    def product_get_meli_status( self, cr, uid, ids, field_name, attributes, context=None ):

        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        company = user_obj.company_id
        warningobj = self.pool.get('warning')

        product_obj = self.pool.get('product.product')
        product = product_obj.browse(cr, uid, ids[0])

        CLIENT_ID = company.mercadolibre_client_id
        CLIENT_SECRET = company.mercadolibre_secret_key
        ACCESS_TOKEN = company.mercadolibre_access_token
        REFRESH_TOKEN = company.mercadolibre_refresh_token

        ML_status = "unknown"
        if ACCESS_TOKEN=='':
            ML_status = "unknown"
        else:
            meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)
            if product.meli_id:
                response = meli.get("/items/"+product.meli_id, {'access_token':meli.access_token} )
                rjson = response.json()
                ML_status = rjson["status"]
                if "error" in rjson:
                    ML_status = rjson["error"]
                if "sub_status" in rjson:
                    if len(rjson["sub_status"]) and rjson["sub_status"][0]=='deleted':
                        product.write({ 'meli_id': '' })

        res = {}
        for product in self.browse(cr,uid,ids):
            res[product.id] = ML_status
        return res

    def product_get_permalink( self, cr, uid, ids, field_name, attributes, context=None ):
        ML_permalink = ''

        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        company = user_obj.company_id

        product_obj = self.pool.get('product.product')
        product = product_obj.browse(cr, uid, ids[0])

        CLIENT_ID = company.mercadolibre_client_id
        CLIENT_SECRET = company.mercadolibre_secret_key
        ACCESS_TOKEN = company.mercadolibre_access_token
        REFRESH_TOKEN = company.mercadolibre_refresh_token


        ML_permalink = ""
        if ACCESS_TOKEN=='':
            ML_permalink = ""
        else:
            meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)
            if product.meli_id:
                response = meli.get("/items/"+product.meli_id, {'access_token':meli.access_token} )
                rjson = response.json()
                if "permalink" in rjson:
                    ML_permalink = rjson["permalink"]
                if "error" in rjson:
                    ML_permalink = ""
                #if "sub_status" in rjson:
                    #if len(rjson["sub_status"]) and rjson["sub_status"][0]=='deleted':
                    #    product.write({ 'meli_id': '' })


        res = {}
        for product in self.browse(cr,uid,ids):
            res[product.id] = ML_permalink
        return res


    def product_post(self, cr, uid, ids, context=None):
        import pdb;pdb.set_trace();
#        product_ids = context['active_ids']
        product_ids = ids
        product_obj = self.pool.get('product.product')

        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        #user_obj.company_id.meli_login()
        company = user_obj.company_id
        warningobj = self.pool.get('warning')

        #company = self.pool.get('res.company').browse(cr,uid,1)

        REDIRECT_URI = company.mercadolibre_redirect_uri
        CLIENT_ID = company.mercadolibre_client_id
        CLIENT_SECRET = company.mercadolibre_secret_key
        ACCESS_TOKEN = company.mercadolibre_access_token
        REFRESH_TOKEN = company.mercadolibre_refresh_token


        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

        if ACCESS_TOKEN=='':
            meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET)
            url_login_meli = meli.auth_url(redirect_URI=REDIRECT_URI)
            return {
                "type": "ir.actions.act_url",
                "url": url_login_meli,
                "target": "new",
            }

        for product_id in product_ids:
            product = product_obj.browse(cr,uid,product_id)

            if (product.meli_id):
                response = meli.get("/items/%s" % product.meli_id, {'access_token':meli.access_token})

            # print product.meli_category.meli_category_id

            if product.meli_title==False:
                # print 'Assigning title: product.meli_title: %s name: %s' % (product.meli_title, product.name)
                product.meli_title = product.name

            if product.meli_price==False:
                # print 'Assigning price: product.meli_price: %s standard_price: %s' % (product.meli_price, product.standard_price)
                product.meli_price = product.standard_price

            body = {
                "title": product.meli_title or '',
                "description": product.meli_description or '',
                "category_id": product.meli_category.meli_category_id or '0',
                "listing_type_id": product.meli_listing_type or '0',
                "buying_mode": product.meli_buying_mode or '',
                "price": product.meli_price  or '0',
                "currency_id": product.meli_currency  or '0',
                "condition": product.meli_condition  or '',
                "available_quantity": product.meli_available_quantity  or '0',
                "warranty": product.meli_warranty or '',
                #"pictures": [ { 'source': product.meli_imagen_logo} ] ,
                "video_id": product.meli_video  or '',
            }

            # print body

            assign_img = False and product.meli_id

            #publicando imagen cargada en OpenERP
            if product.image==None:
                return warningobj.info(cr, uid, title='MELI WARNING', message="Debe cargar una imagen de base en el producto.", message_html="" )
            elif product.meli_imagen_id==False:
                # print "try uploading image..."
                resim = product.product_meli_upload_image()
                if "status" in resim:
                    if (resim["status"]=="error" or resim["status"]=="warning"):
                        error_msg = 'MELI: mensaje de error:   ', resim
                        _logger.error(error_msg)
                    else:
                        assign_img = True and product.meli_imagen_id

            #modificando datos si ya existe el producto en MLA
            if (product.meli_id):
                body = {
                    "title": product.meli_title or '',
                    #"description": product.meli_description or '',
                    #"category_id": product.meli_category.meli_category_id,
                    #"listing_type_id": product.meli_listing_type,
                    "buying_mode": product.meli_buying_mode or '',
                    "price": product.meli_price or '0',
                    #"currency_id": product.meli_currency,
                    "condition": product.meli_condition or '',
                    "available_quantity": product.meli_available_quantity or '0',
                    "warranty": product.meli_warranty or '',
                    "pictures": [],
                    #"pictures": [ { 'source': product.meli_imagen_logo} ] ,
                    "video_id": product.meli_video or '',
                }

            #publicando multiples imagenes
            multi_images_ids = {}
            if (product.images):
                # print 'website_multi_images presente:   ', product.images
                #recorrer las imagenes y publicarlas
                multi_images_ids = product.product_meli_upload_multi_images()

            #asignando imagen de logo (por source)
            if product.meli_imagen_logo:
                if product.meli_imagen_id:
                    if 'pictures' in body.keys():
                        body["pictures"]+= [ { 'id': product.meli_imagen_id } ]
                    else:
                        body["pictures"] = [ { 'id': product.meli_imagen_id } ]

                        if (multi_images_ids):
                            if 'pictures' in body.keys():
                                body["pictures"]+= multi_images_ids
                            else:
                                body["pictures"] = multi_images_ids

                    if 'pictures' in body.keys():
                        body["pictures"]+= [ { 'source': product.meli_imagen_logo} ]
                    else:
                        body["pictures"]+= [ { 'source': product.meli_imagen_logo} ]
                else:
                    imagen_producto = ""
                    if (product.meli_description!="" and product.meli_description!=False and product.meli_imagen_link!=""):
                        imgtag = "<img style='width: 420px; height: auto;' src='%s'/>" % ( product.meli_imagen_link )
                        result = product.meli_description.replace( "[IMAGEN_PRODUCTO]", imgtag )
                        if (result):
                            _logger.info( "result: %s" % (result) )
                            product.meli_description = result
                        else:
                            result = product.meli_description



            else:
                return warningobj.info(cr, uid, title='MELI WARNING', message="Debe completar el campo 'Imagen_Logo' con el url: http://www.nuevohorizonte-sa.com.ar/images/logo1.png", message_html="")

            #check fields
            if product.meli_description==False:
                return warningobj.info(cr, uid, title='MELI WARNING', message="Debe completar el campo 'description' (en html)", message_html="")

            #put for editing, post for creating
            if product.meli_id:
                response = meli.put("/items/"+product.meli_id, body, {'access_token':meli.access_token})
            else:
                assign_img = True and product.meli_imagen_id
                response = meli.post("/items", body, {'access_token':meli.access_token})

            #check response
            # print response.content
            rjson = response.json()

            #check error
            if "error" in rjson:
                #print "Error received: %s " % rjson["error"]
                error_msg = 'MELI: mensaje de error:  %s , mensaje: %s, status: %s, cause: %s ' % (rjson["error"], rjson["message"], rjson["status"], rjson["cause"])
                _logger.error(error_msg)

                missing_fields = error_msg

                #expired token
                if "message" in rjson and (rjson["message"]=='invalid_token' or rjson["message"]=="expired_token"):
                    meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET)
                    url_login_meli = meli.auth_url(redirect_URI=REDIRECT_URI)
                    #print "url_login_meli:", url_login_meli
                    #raise osv.except_osv( _('MELI WARNING'), _('INVALID TOKEN or EXPIRED TOKEN (must login, go to Edit Company and login):  error: %s, message: %s, status: %s') % ( rjson["error"], rjson["message"],rjson["status"],))
                    return warningobj.info(cr, uid, title='MELI WARNING', message="Debe iniciar sesión en MELI.  ", message_html="")
                else:
                     #Any other errors
                    return warningobj.info(cr, uid, title='MELI WARNING', message="Completar todos los campos!  ", message_html="<br><br>"+missing_fields )

            #last modifications if response is OK
            if "id" in rjson:
                product.write( { 'meli_id': rjson["id"]} )

            posting_fields = {'posting_date': str(datetime.now()),'meli_id':rjson['id'],'product_id':product.id,'name': 'Post: ' + product.meli_title }

            posting_id = self.pool.get('mercadolibre.posting').search(cr,uid,[('meli_id','=',rjson['id'])])

            if not posting_id:
                posting_id = self.pool.get('mercadolibre.posting').create(cr,uid,(posting_fields))


        return {}

    _columns = {
    'meli_imagen_id': fields.char(string='Imagen Id', size=256),
    'meli_post_required': fields.boolean(string='Este producto es publicable en Mercado Libre'),
	'meli_id': fields.char( string='Id del item asignado por Meli', size=256),
    'meli_permalink': fields.function( product_get_permalink, method=True, type='char',  size=256, string='PermaLink in MercadoLibre' ),
	'meli_title': fields.char(string='Nombre del producto en Mercado Libre',size=256),
	'meli_description': fields.html(string='Descripción'),
    'meli_description_banner_id': fields.many2one("mercadolibre.banner","Banner"),
	'meli_category': fields.many2one("mercadolibre.category","Categoría de MercadoLibre"),
	'meli_listing_type': fields.selection([("free","Libre"),("bronze","Bronce"),("silver","Plata"),("gold","Oro"),("gold_premium","Gold Premium"),("gold_special","Gold Special"),("gold_pro","Oro Pro")], string='Tipo de lista'),
	'meli_buying_mode': fields.selection( [("buy_it_now","Compre ahora"),("classified","Clasificado")], string='Método de compra'),
	'meli_price': fields.char(string='Precio de venta', size=128),
	'meli_price_fixed': fields.boolean(string='Price is fixed'),
	'meli_currency': fields.selection([("ARS","Peso Argentino (ARS)")],string='Moneda (ARS)'),
	'meli_condition': fields.selection([ ("new", "Nuevo"), ("used", "Usado"), ("not_specified","No especificado")],'Condición del producto'),
	'meli_available_quantity': fields.integer(string='Cantidad disponible'),
	'meli_warranty': fields.char(string='Garantía', size=256),
	'meli_imagen_logo': fields.char(string='Imagen Logo', size=256),
    'meli_imagen_id': fields.char(string='Imagen Id', size=256),
    'meli_imagen_link': fields.char(string='Imagen Link', size=256),
    'meli_multi_imagen_id': fields.char(string='Multi Imagen Ids', size=512),
	'meli_video': fields.char( string='Video (id de youtube)', size=256),
	'meli_state': fields.function( product_get_meli_loginstate, method=True, type='boolean', string="Inicio de sesión requerida", store=False ),
    'meli_status': fields.function( product_get_meli_status, method=True, type='char', size=128, string="Estado del producto en MLA", store=False ),
	### Agregar imagen/archivo uno o mas, y la descripcion en HTML...
	# TODO Agregar el banner
    }

    _defaults = {
        'meli_imagen_logo': 'None',
        'meli_video': ''
    }
예제 #14
0
class SaleQuickInvoiceConfirm(osv.TransientModel):
    _name = 'quick.invoice.confirm'

    def del_the_confirm(self, cr, uid, ids, context=None):
        for confirm_id in ids:
            self.unlink(cr, uid, confirm_id, context)
        return {'type': 'ir.actions.act_window_close'}

    def _get_info(self, cr, uid, ids, field_name, arg, context=None):
        down_payment_id = self.pool['ir.values'].get_default(
            cr, uid, 'sale.config.settings', 'deposit_product_id_setting')

        res = dict(map(lambda x: (x, 0), ids))
        for confirm_order in self.browse(cr, uid, ids, context):
            down_payment = discount = should_total = not_receivable = 0.0
            for line in confirm_order.sale_quick_invoice_lines:
                if field_name == 'show' and line:
                    lsp = line.sale_order_line.product_id

                    down_payment += line.price_total if lsp.id == down_payment_id else 0.0
                    discount += line.price_total if lsp.name == u'价格优惠' else 0.0
                    should_total += line.price_total if (
                        (lsp.id != down_payment_id) or
                        (lsp.name == u'价格优惠')) else 0.0

            not_receivable += confirm_order.sale_order_id.not_receivable
            should_total = should_total + discount

            res[confirm_order.id] = ('<table class="mid">\
                    <tbody>\
                        <tr>\
                            <th>预付</th>\
                            <td>%s</td>\
                        </tr>\
                        <tr>\
                            <th>优惠</th>\
                            <td>%s</td>\
                        </tr>\
                        <tr>\
                            <th>应收总款</th>\
                            <td>%s</td>\
                        </tr>\
                        <tr>\
                            <th>待收款</th>\
                            <td>%s</td>\
                        </tr>\
                    </tbody>\
                </table>' % (down_payment, discount, should_total - discount,
                             not_receivable))

        return res

    _columns = {
        'sale_order_id':
        fields.many2one('sale.order'),
        'sale_quick_invoice_lines':
        fields.one2many('sale.quick.invoice.confirm.line',
                        'quick_invoice_line',
                        string='销售产品',
                        readonly=True,
                        ondelete='cascade'),
        'account_quick_invoices':
        fields.one2many('account.quick.invoice.confirm.line',
                        'quick_invoice_line',
                        string='收款记录',
                        ondelete='cascade'),
        'show':
        fields.function(_get_info, type='html', string='收款信息')
    }
예제 #15
0
class wage_increment(models.Model):

    _name = 'hr.contract.wage.increment'
    _description = 'HR Contract Wage Adjustment'

    def _calculate_difference(self,
                              cr,
                              uid,
                              ids,
                              field_name,
                              args,
                              context=None):

        res = dict.fromkeys(ids)
        for incr in self.browse(cr, uid, ids, context=context):
            if incr.wage >= incr.contract_id.wage:
                percent = ((incr.wage / incr.contract_id.wage) - 1.0) * 100.0
            else:
                percent = (1.0 - (incr.wage / incr.contract_id.wage)) * -100.0
            res[incr.id] = {
                'wage_difference': incr.wage - incr.current_wage,
                'wage_difference_percent': percent,
            }

        return res

    def _get_department(self, cr, uid, ids, field_name, arg, context=None):

        res = dict.fromkeys(ids, False)
        for incr in self.browse(cr, uid, ids, context=context):
            res[incr.id] = incr.employee_id.department_id.id,

        return res

    _columns = {
        'effective_date':
        fields.date(
            'Effective Date',
            required=True,
            readonly=True,
            states={'draft': [('readonly', False)]},
        ),
        'wage':
        fields.float(
            'New Wage',
            digits_compute=dp.get_precision('Payroll'),
            required=True,
            readonly=True,
            states={'draft': [('readonly', False)]},
        ),
        'new_contract_id':
        fields.many2one(
            'hr.contract',
            'New Contract',
            readonly=True,
        ),
        'contract_id':
        fields.many2one(
            'hr.contract',
            'Contract',
            readonly=True,
        ),
        'current_wage':
        fields.related(
            'contract_id',
            'wage',
            type='float',
            string='Current Wage',
            store=True,
            readonly=True,
        ),
        'wage_difference':
        fields.function(
            _calculate_difference,
            type='float',
            method=True,
            string='Difference',
            multi='diff',
            readonly=True,
        ),
        'wage_difference_percent':
        fields.function(
            _calculate_difference,
            type='float',
            method=True,
            string='Percentage',
            multi='diff',
            readonly=True,
        ),
        'employee_id':
        fields.related(
            'contract_id',
            'employee_id',
            relation='hr.employee',
            type='many2one',
            string='Employee',
            store=True,
            readonly=True,
        ),
        'job_id':
        fields.related(
            'contract_id',
            'job_id',
            relation='hr.job',
            type='many2one',
            string='Job',
            store=True,
            readonly=True,
        ),
        'department_id':
        fields.related(
            'employee_id',
            'department_id',
            relation='hr.department',
            type='many2one',
            string='Department',
            store=True,
            readonly=True,
        ),
        'state':
        fields.selection(
            [('draft', 'Draft'), ('confirm', 'Confirmed'),
             ('approve', 'Approved'), ('decline', 'Declined')],
            'State',
            readonly=True,
        ),
        'run_id':
        fields.many2one(
            'hr.contract.wage.increment.run',
            'Batch Run',
            readonly=True,
            ondelete='cascade',
        ),
    }

    def _get_contract_data(self, cr, uid, field_list, context=None):

        if context is None:
            context = {}
        employee_id = self._get_employee(cr, uid, context=context)
        ee_data = self.pool.get('hr.employee').read(cr,
                                                    uid,
                                                    employee_id,
                                                    ['contract_id'],
                                                    context=context)
        contract_id = ee_data.get('contract_id', False)[0]
        if not contract_id:
            return False

        data = self.pool.get('hr.contract').read(cr,
                                                 uid,
                                                 contract_id,
                                                 field_list,
                                                 context=context)

        return data

    def _get_contract_id(self, cr, uid, context=None):

        data = self._get_contract_data(cr, uid, ['id'], context)
        return data.get('id', False)

    def _get_employee(self, cr, uid, context=None):

        if context is None:
            context = {}
        employee_id = context.get('active_id', False)

        return employee_id

    def _get_effective_date(self, cr, uid, context=None):

        contract_id = self._get_contract_id(cr, uid, context=context)
        if not contract_id:
            return False

        contract = self.pool.get('hr.contract').browse(cr,
                                                       uid,
                                                       contract_id,
                                                       context=context)
        if contract.pps_id:
            first_day = 1
            if contract.pps_id.type == 'monthly':
                first_day = contract.pps_id.mo_firstday
            date_format = '%Y-%m-' + first_day
            dThisMonth = datetime.now().strftime(date_format).strptime(
                DEFAULT_SERVER_DATE_FORMAT).date()
            dNextMonth = (datetime.now() + relativedelta(months=+1)).strftime(
                date_format).strptime(DEFAULT_SERVER_DATE_FORMAT).date()
            if dThisMonth < datetime.now().date():
                return dNextMonth.strftime(DEFAULT_SERVER_DATE_FORMAT)
            else:
                return dThisMonth.strftime(DEFAULT_SERVER_DATE_FORMAT)

        return False

    _defaults = {
        'contract_id': _get_contract_id,
        'employee_id': _get_employee,
        'effective_date': _get_effective_date,
        'state': 'draft',
    }

    _rec_name = 'effective_date'

    def _check_state(self, cr, uid, wage_incr, context=None):

        wage_incr_ids = self.search(
            cr,
            uid, [
                ('contract_id', '=', wage_incr.contract_id.id),
                ('state', 'in', ['draft', 'confirm', 'approved']),
                ('id', '!=', wage_incr.id),
            ],
            context=context)
        if len(wage_incr_ids) > 0:
            data = self.pool.get('hr.contract').read(cr,
                                                     uid,
                                                     wage_incr.contract_id.id,
                                                     ['name'],
                                                     context=context)
            raise models.except_orm(
                _('Warning'),
                _('There is already another wage adjustment in progress for '
                  'this contract: %s.') % (data['name']))

        contract_obj = self.pool.get('hr.contract')
        data = contract_obj.read(cr,
                                 uid,
                                 wage_incr.contract_id.id,
                                 ['state', 'date_end'],
                                 context=context)

        if data['state'] in ['draft', 'done']:
            data = self.pool.get('hr.contract').read(cr,
                                                     uid,
                                                     wage_incr.contract_id.id,
                                                     ['name'],
                                                     context=context)
            raise models.except_orm(
                _('Warning!'),
                _('The current state of the contract does not permit a wage '
                  'change: %s') % (data['name']))

        if data.get('date_end', False) and data['date_end'] != '':
            dContractEnd = datetime.strptime(data['date_end'],
                                             DEFAULT_SERVER_DATE_FORMAT)
            dEffective = datetime.strptime(wage_incr.effective_date,
                                           DEFAULT_SERVER_DATE_FORMAT)
            if dEffective >= dContractEnd:
                data = self.pool.get('hr.contract').read(
                    cr,
                    uid,
                    wage_incr.contract_id.id, ['name'],
                    context=context)
                raise models.except_orm(
                    _('Warning!'),
                    _('The contract end date is on or before the effective '
                      'date of the adjustment: %s') % (data['name']))
        return True

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

        hr_obj = self.pool.get('hr.contract')

        if isinstance(ids, (int, long)):
            ids = [ids]

        # Copy the contract and adjust start/end dates and wage accordingly.
        #
        for wi in self.browse(cr, uid, ids, context=context):

            if -0.01 < wi.wage_difference < 0.01:
                continue

            self._check_state(cr, uid, wi, context=context)

            default = {
                'wage': wi.wage,
                'date_start': wi.effective_date,
                'name': False,
                'state': False,
                'message_ids': False,
                'trial_date_start': False,
                'trial_date_end': False,
            }
            data = hr_obj.copy_data(cr,
                                    uid,
                                    wi.contract_id.id,
                                    default=default,
                                    context=context)
            notes = data.get('notes', False)
            if not notes:
                notes = ''
            notes = notes + \
                _('\nSuperceedes (because of wage adjustment) previous '
                  'contract: ') + wi.contract_id.name
            data['notes'] = notes

            c_id = hr_obj.create(cr, uid, data, context=context)
            if c_id:
                if wi.contract_id.notes:
                    notes = wi.contract_id.notes
                else:
                    notes = ''
                notes = notes + \
                    _('\nSuperceeded (for wage adjustment) by contract: ') + \
                    wi.contract_id.name
                vals = {'notes': notes, 'date_end': False}
                wkf = netsvc.LocalService('workflow')

                # Set the new contract to the appropriate state
                wkf.trg_validate(uid, 'hr.contract', c_id, 'signal_confirm',
                                 cr)

                # Terminate the current contract (and trigger appropriate state
                # change)
                vals['date_end'] = datetime.strptime(
                    wi.effective_date, '%Y-%m-%d').date() + \
                    relativedelta(days=-1)
                hr_obj.write(cr, uid, wi.contract_id.id, vals, context=context)
                wkf.trg_validate(uid, 'hr.contract', wi.contract_id.id,
                                 'signal_done', cr)

        return

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

        contract_id = vals.get('contract_id', False)

        if not contract_id:
            if context is not None:
                contract_id = context.get('active_id')

        data = self.pool.get('hr.contract').read(cr,
                                                 uid,
                                                 contract_id,
                                                 ['name', 'date_start'],
                                                 context=context)

        # Check that the contract start date is before the effective date
        if vals['effective_date'] <= data['date_start']:
            raise models.except_orm(
                _('Error'),
                _('The effective date of the adjustment must be after the '
                  'contract start date. Contract: %s.') % (data['name']))

        wage_incr_ids = self.search(
            cr,
            uid, [
                ('contract_id', '=', contract_id),
                ('state', 'in', ['draft', 'confirm', 'approved']),
            ],
            context=context)
        if len(wage_incr_ids) > 0:
            raise models.except_orm(
                _('Warning'),
                _('There is already another wage adjustment in progress for '
                  'this contract: %s.') % (data['name']))

        return super(wage_increment, self).create(cr,
                                                  uid,
                                                  vals,
                                                  context=context)

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

        for wi in self.browse(cr, uid, ids, context=context):
            self._check_state(cr, uid, wi, context=context)
            self.write(cr, uid, wi.id, {'state': 'confirm'}, context=context)

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

        for i in ids:
            self.action_wage_increment(cr, uid, [i], context=context)
            self.write(cr, uid, i, {'state': 'approve'}, context=context)

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

        for incr in self.browse(cr, uid, ids, context=context):
            if incr.state in ['approve']:
                raise models.except_orm(
                    _('The record cannot be deleted!'),
                    _("""\
You may not delete a record that is in a %s state:
Employee: %s""") % (incr.state, incr.employee_id.name))

        return super(wage_increment, self).unlink(cr,
                                                  uid,
                                                  ids,
                                                  context=context)
예제 #16
0
class AccountQuickInvoiceConfirmLine(osv.TransientModel):
    _name = 'account.quick.invoice.confirm.line'

    def _get_invoice_info(self, cr, uid, ids, field_name, arg, context=None):
        res = dict(map(lambda x: (x, 0), ids))
        for line in self.browse(cr, uid, ids, context):
            if line.invoice_id:
                if field_name == 'invoice_line_ids':
                    invoice_text = ''
                    for invoice_line in line.invoice_id.invoice_line_ids:
                        invoice_text += invoice_line.product_id.name + u';'
                    res[line.id] = invoice_text
                if field_name == 'total':
                    invoice_total = 0.0
                    for invoice_line in line.invoice_id.invoice_line_ids:
                        invoice_total += invoice_line.price_subtotal
                    res[line.id] = invoice_total
                if field_name == 'cdate':
                    res[line.id] = line.invoice_id.create_date

        return res

    # 实体字段使用constrain获取
    @api.constrains('invoice_id')
    def _get_enity_invoice_field(self):
        self.write({
            'invoice_number': self.invoice_id.invoice_number,
            'date_invoice': self.invoice_id.date_invoice,
            'state': self.invoice_id.state
        })

    _columns = {
        'quick_invoice_line':
        fields.many2one('quick.invoice.confirm',
                        required=True,
                        ondelete='cascade',
                        readonly=True),
        'invoice_id':
        fields.many2one('account.invoice',
                        string='付款ID',
                        required=True,
                        ondelete='cascade',
                        readonly=True),
        'invoice_line_ids':
        fields.function(_get_invoice_info, type='html', string='目标产品'),
        'total':
        fields.function(_get_invoice_info, type='float', string='收款'),
        'cdate':
        fields.function(_get_invoice_info, type='datetime', string='创建时间'),
        'invoice_number':
        fields.char(string='收据号'),
        'date_invoice':
        fields.date(string='收款日期'),
        'state':
        fields.selection([('draft', '草稿'), ('proforma', '形式'),
                          ('proforma2', '形式2'), ('open', '确认(待收)'),
                          ('paid', '已收'), ('cancel', '已取消')],
                         string='状态',
                         readonly=True),
    }

    @api.multi
    def confirm_cancel(self):
        qid = self.quick_invoice_line.id
        return self.env['sale.order'].confirm_cancel(qid)

    @api.multi
    def action_invoice(self):
        vals = {}
        if self.invoice_number:
            vals['invoice_number'] = self.invoice_number
        if self.date_invoice:
            vals['date_invoice'] = self.date_invoice
        self.env['account.invoice'].browse(self.invoice_id.id).write(vals)

        imd = self.env['ir.model.data']
        action = imd.xmlid_to_object('account.action_account_invoice_payment')
        form_view_id = imd.xmlid_to_res_id(
            'account.view_account_payment_invoice_form')

        result = {
            'res_id': False,
            'name': '确认',
            'type': action.type,
            'view_type': 'form',
            'view_model': 'form',
            'res_model': action.res_model,
            'views': [(form_view_id, 'form')],
            'views_id': form_view_id,
            'context': {
                'default_invoice_ids': [(4, self.invoice_id.id, None)]
            },
            'target': 'new',
        }

        return result
예제 #17
0
class SaleQuickInvoiceConfirmLine(osv.TransientModel):
    _name = 'sale.quick.invoice.confirm.line'

    def _get_order_line_info(self,
                             cr,
                             uid,
                             ids,
                             field_name,
                             arg,
                             context=None):
        down_payment_id = self.pool['ir.values'].get_default(
            cr, uid, 'sale.config.settings', 'deposit_product_id_setting')

        res = dict(map(lambda x: (x, 0), ids))
        for line in self.browse(cr, uid, ids, context):
            if line.sale_order_line:
                sol = line.sale_order_line

                if field_name == 'product_id':
                    res[line.id] = sol.product_id.name
                if field_name == 'sequence':
                    res[line.id] = sol.sequence
                if field_name == 'price_unit':
                    res[line.id] = sol.price_unit
                if field_name == 'price_total':
                    if line.identification != 'discount':
                        res[line.id] = sol.price_unit if (
                            sol.product_id.id
                            == down_payment_id) else sol.price_total
                    else:
                        res[line.id] = sol.price_total
                if field_name == 'product_uom_qty':
                    res[line.id] = sol.product_uom_qty
                if field_name == 'qty_invoiced' and line.identification == 'commodity':
                    res[line.id] = sol.qty_invoiced
                if field_name == 'balance':
                    invoice_total = 0.0
                    for invoice in sol.invoice_lines:
                        if line.identification == 'discount':
                            invoice_total += -invoice.price_subtotal
                        else:
                            invoice_total += invoice.price_subtotal
                    res[line.id] = (
                        line.price_total - invoice_total
                    ) if line.identification == 'discount' else (
                        line.price_total - invoice_total)

        return res

    _columns = {
        'quick_invoice_line':
        fields.many2one('quick.invoice.confirm',
                        required=True,
                        ondelete='cascade'),
        'sale_order_line':
        fields.many2one('sale.order.line',
                        string='订单行ID',
                        required=True,
                        ondelete='cascade'),
        'product_id':
        fields.function(_get_order_line_info, string='产品', type='char'),
        'sequence':
        fields.function(_get_order_line_info, string='序号', type='integer'),
        'price_unit':
        fields.function(_get_order_line_info, string='单价', type='float'),
        'price_total':
        fields.function(_get_order_line_info, string='小计', type='float'),
        'product_uom_qty':
        fields.function(_get_order_line_info, string='数量', type='float'),
        'qty_invoiced':
        fields.function(_get_order_line_info, string='收款次数', type='float'),
        'balance':
        fields.function(_get_order_line_info, string='余款', type='float'),
        'amount':
        fields.float(string='本次收款'),
        'comment':
        fields.text(string='说明'),
        'invoice_number':
        fields.char(string='收据号'),
        'date_invoice':
        fields.date(string='收款日期'),
        'identification':
        fields.selection([('down_payment', '预付'), ('discount', '优惠'),
                          ('commodity', '产品')],
                         string='类型'),
    }

    @api.multi
    def create_new_invoice(self):
        imd = self.env['ir.model.data']
        action = imd.xmlid_to_object(
            'account_expend.act_sale_quick_invoice_confirm')
        form_view_id = imd.xmlid_to_res_id(
            'account_expend.view_sale_quick_invoice_confirm_line_from')

        result = {
            'res_id': self.id,
            'name': '收款信息',
            'type': action.type,
            'view_type': 'form',
            'view_model': 'form',
            'res_model': action.res_model,
            'views': [(form_view_id, 'form')],
            'views_id': form_view_id,
            'target': 'new',
        }

        return result

    @api.multi
    def confirm_cancel(self):
        qid = self.quick_invoice_line.id
        return self.env['sale.order'].confirm_cancel(qid)

    # 覆盖sale_make_invoice_advance的发票创建方法
    @api.multi
    def action_invoice_create(self,
                              order_ids,
                              order_line_id,
                              grouped=False,
                              final=False):
        inv_obj = self.env['account.invoice']
        precision = self.env['decimal.precision'].precision_get(
            'Product Unit of Measure')
        orders = self.env['sale.order'].browse(order_ids)
        invoices = {}

        for order in orders:
            group_key = order.id if grouped else (order.partner_invoice_id.id,
                                                  order.currency_id.id)

            line = self.env['sale.order.line'].browse(order_line_id)

            if line:

                # if float_is_zero(line.qty_to_invoice, precision_digits=precision):
                #     continue
                if group_key not in invoices:
                    inv_data = order._prepare_invoice()

                    if self.invoice_number:
                        inv_data['invoice_number'] = self.invoice_number
                    if self.date_invoice:
                        inv_data['date_invoice'] = self.date_invoice
                    if self.comment:
                        inv_data['comment'] = self.comment
                    # 如果产品为优惠,那么建立退款收据
                    if line.product_id.name == u'价格优惠':
                        inv_data['type'] = 'out_refund'
                    invoice = inv_obj.create(inv_data)
                    invoices[group_key] = invoice
                elif group_key in invoices:
                    vals = {}
                    if order.name not in invoices[group_key].origin.split(
                            ', '):
                        vals['origin'] = invoices[
                            group_key].origin + ', ' + order.name
                    if order.client_order_ref and order.client_order_ref not in invoices[
                            group_key].name.split(', '):
                        vals['name'] = invoices[
                            group_key].name + ', ' + order.client_order_ref

                    invoices[group_key].write(vals)

                    # if not float_is_zero(qty, precision_digits=precision):
                vals = self._prepare_invoice_line(qty=line.product_uom_qty)
                vals.update({
                    'invoice_id': invoices[group_key].id,
                    'sale_line_ids': [(6, 0, [line.id])]
                })

                self.env['account.invoice.line'].create(vals)

        if not invoices:
            raise UserError(_('There is no invoicable line.'))

        for invoice in invoices.values():
            if not invoice.invoice_line_ids:
                raise UserError(_('There is no invoicable line.'))

            if invoice.amount_untaxed < 0:
                invoice.type = 'out_refund'
                for line in invoice.invoice_line_ids:
                    line.quantity = line.quantity

            for line in invoice.invoice_line_ids:
                line._set_additional_fields(invoice)

            invoice.compute_taxes()

            # 调用验证按钮的工作流
            if invoice.state not in ('draft', 'proforma', 'proforma2'):
                pass
            invoice.signal_workflow('invoice_open')

        return [inv.id for inv in invoices.values()]

    @api.multi
    def _prepare_invoice_line(self, qty):
        sol = self.sale_order_line
        product = sol.product_id
        order_id = sol.order_id

        res = {}
        account = product.property_account_income_id or product.categ_id.property_account_income_categ_id
        if not account:
            raise UserError(_('Please define income account for this product: "%s" (id:%d) - or for its category: "%s".') % \
                            (product.name, product.id, product.categ_id.name))

        fpos = order_id.fiscal_position_id or order_id.partner_id.property_account_position_id
        if fpos:
            account = fpos.map_account(account)

        # 因为收款改为手写,当出现数量大于1时,一定有计算的必要,变为计算单价的方式
        res = {
            'name': sol.name,
            'sequence': sol.sequence,
            'origin': sol.order_id.name,
            'account_id': account.id,
            'price_unit': self.amount / qty,
            'quantity': qty,
            'price_subtotal': self.amount,
            'discount': sol.discount,
            'uom_id': sol.product_uom.id,
            'product_id': product.id or False,
            'invoice_line_tax_ids': [(6, 0, sol.tax_id.ids)],
            'account_analytic_id': sol.order_id.project_id.id,
        }

        return res

    @api.multi
    def create_invoice(self):
        if self.identification == 'commodity':
            self.amount = abs(self.amount)
        if self.amount <= 0.0:
            raise ValidationError(u'收款不能小于或等于0.0')
        if self.identification != 'discount' and self.amount > self.balance:
            raise ValidationError(u'收款不能大于余款')

        new_invoices = self.action_invoice_create(
            [self.sale_order_line.order_id.id],
            self.sale_order_line.id,
            grouped=True)

        invoices = []
        for new_invoice in new_invoices:
            self.env['account.quick.invoice.confirm.line'].create({
                'quick_invoice_line':
                self.quick_invoice_line.id,
                'invoice_id':
                new_invoice
            })

        return self.confirm_cancel()
예제 #18
0
class account_invoice(models.Model):

    _name = "account.invoice"
    _inherit = "account.invoice"
    _description = 'Invoice'

    def _amount_all(self, cr, uid, ids, name, args, context=None):
        res = {}
        for invoice in self.browse(cr, uid, ids, context=context):
            amount_untaxed = 0.0
            res[invoice.id] = {
                'amount_untaxed': 0.0,
                'amount_tax': 0.0,
                'amount_total': 0.0,
                'add_disc_amt': 0.0,
                'amount_net': 0.0,
            }
            for line in invoice.invoice_line:
                amount_untaxed += line.price_subtotal
            res[invoice.
                id]['add_disc_amt'] = amount_untaxed * invoice.add_disc / 100
            for line in invoice.tax_line:
                res[invoice.id]['amount_tax'] += line.amount
            res[invoice.id]['amount_untaxed'] = amount_untaxed - res[
                invoice.id]['add_disc_amt']
            res[invoice.id]['amount_net'] = res[invoice.id]['amount_untaxed']
            res[invoice.id]['amount_total'] = res[
                invoice.id]['amount_tax'] + res[invoice.id]['amount_untaxed']
        return res

    _columns = {
        'add_disc':
        fields.float('Additional Discount(%)',
                     digits=(4, 2),
                     readonly=True,
                     states={'draft': [('readonly', False)]}),
        'add_disc_amt':
        fields.function(_amount_all,
                        method=True,
                        digits_compute=dp.get_precision('Sale Price'),
                        string='Additional Disc Amt',
                        store=True,
                        multi='sums',
                        help="The additional discount on untaxed amount."),
        'amount_net':
        fields.function(_amount_all,
                        method=True,
                        digits_compute=dp.get_precision('Sale Price'),
                        string='Net Amount',
                        store=True,
                        multi='sums',
                        help="The amount after additional discount."),
        'amount_untaxed':
        fields.function(_amount_all,
                        method=True,
                        digits_compute=dp.get_precision('Account'),
                        string='Untaxed',
                        store=True,
                        multi='all'),
        'amount_tax':
        fields.function(_amount_all,
                        method=True,
                        digits_compute=dp.get_precision('Account'),
                        string='Tax',
                        store=True,
                        multi='all'),
        'amount_total':
        fields.function(_amount_all,
                        method=True,
                        digits_compute=dp.get_precision('Account'),
                        string='Total',
                        store=True,
                        multi='all'),
    }

    _defaults = {
        'add_disc': 0.0,
    }
예제 #19
0
class hr_activity(models.Model):
    """
    An activity is a job or a leave type
    When a job or a leave type is created, the related activity is created
    automatically
    """
    _name = 'hr.activity'
    _description = 'Employee Activities'

    def _get_activity_name(self,
                           cr,
                           uid,
                           ids,
                           field_name=False,
                           arg=False,
                           context=False):
        res = {}

        if isinstance(ids, (int, long)):
            ids = [ids]

        for activity in self.browse(cr, uid, ids, context=context):
            if activity.type == 'job' and activity.job_id:
                res[activity.id] = activity.job_id.name_get()[0][1]

            elif activity.type == 'leave' and activity.leave_id:
                res[activity.id] = activity.leave_id.name_get()[0][1]

            else:
                res[activity.id] = ''

        return res

    def onchange_activity_type(self, cr, uid, ids, context=None):
        return {
            'value': {
                'job_id': 0,
                'leave_id': 0,
            }
        }

    _columns = {
        'name':
        fields.function(
            _get_activity_name,
            string='Activity Name',
            method=True,
            type="char",
        ),
        'type':
        fields.selection(
            (
                ('leave', 'Leave'),
                ('job', 'Job'),
            ),
            'Activity Type',
            required=True,
        ),
        'code':
        fields.char(
            'Code',
            help="Used for payslip computation",
        ),
        'job_id':
        fields.many2one(
            'hr.job',
            'Job',
            ondelete='cascade',
        ),
        'leave_id':
        fields.many2one(
            'hr.holidays.status',
            'Leave Type',
            ondelete='cascade',
        ),
    }

    _order = 'type'
예제 #20
0
class AccountVoucher(osv.osv):
    _inherit = "account.voucher"
    
    @api.one
    @api.depends('currency_id', 'payment_rate_currency_id', 'payment_rate', 'amount', 'date', 'journal_id')
    def _compute_rate_amount(self):
        print "--_compute_rate_amount-"
        if self.currency_id != self.payment_rate_currency_id:
            currency_obj = self.env['res.currency']
            currency_str = payment_rate_str = ''
            if self.currency_id:
                currency_str = currency_obj.browse(self.currency_id.id)
            if self.payment_rate_currency_id:
                payment_rate_str = currency_obj.browse(self.payment_rate_currency_id.id)
            #currency_payment = currency_obj.browse(self.currency_id.id)#.rate
            amount_curr = u'%s\N{NO-BREAK SPACE}%s' % (currency_str.symbol, locale.format("%d", payment_rate_str.rate, grouping=True))#formatLang(self.env, currency_payment.rate, currency_obj=self.currency_id)
            amount_curr_payment = u'%s\N{NO-BREAK SPACE}%s' % (payment_rate_str.symbol, locale.format("%d", currency_str.rate, grouping=True))
            #print "====",self.date,currency_str.rate,payment_rate_str.rate
            currency_help_label = _('The exchange rate was %s = %s') % (amount_curr, amount_curr_payment)
            self.amount_info = self.amount * currency_str.rate
            self.currency_inverse_help_label = currency_help_label
    
    def _get_currency_help_label(self, cr, uid, currency_id, payment_rate, payment_rate_currency_id, context=None):
        rml_parser = report_sxw.rml_parse(cr, uid, 'currency_help_label', context=context)
        currency_pool = self.pool.get('res.currency')
        currency_str = payment_rate_str = ''
        if currency_id:
            currency_str = rml_parser.formatLang(1, currency_obj=currency_pool.browse(cr, uid, currency_id, context=context))
        if payment_rate_currency_id:
            payment_rate_str  = rml_parser.formatLang(currency_pool.browse(cr, uid, currency_id, context=context).rate, currency_obj=currency_pool.browse(cr, uid, payment_rate_currency_id, context=context))
        currency_help_label = _('At the operation date, the exchange rate was\n%s = %s') % (currency_str, payment_rate_str)
        return currency_help_label

    def _fnct_currency_help_label(self, cr, uid, ids, name, args, context=None):
        res = {}
        for voucher in self.browse(cr, uid, ids, context=context):
            res[voucher.id] = self._get_currency_help_label(cr, uid, voucher.currency_id.id, voucher.payment_rate, voucher.company_currency_id.id, context=context)
        return res
    
    def _get_amount_help_label(self, cr, uid, currency_id, payment_rate, payment_rate_currency_id, context=None):
#         rml_parser = report_sxw.rml_parse(cr, uid, 'currency_help_label', context=context)
        currency_pool = self.pool.get('res.currency')
#         currency_str = payment_rate_str = ''
        if currency_id:
            #print "=======",currency_pool.browse(cr, uid, currency_id, context=context).rate
#             currency_str = rml_parser.formatLang(1, currency_obj=currency_pool.browse(cr, uid, currency_id, context=context))
#         if payment_rate_currency_id:
#             payment_rate_str  = rml_parser.formatLang(currency_pool.browse(cr, uid, currency_id, context=context).rate, currency_obj=currency_pool.browse(cr, uid, payment_rate_currency_id, context=context))
#         currency_help_label = _('At the operation date, the exchange rate was\n%s = %s') % (currency_str, payment_rate_str)
            return str(payment_rate*currency_pool.browse(cr, uid, currency_id, context=context).rate)
    
    def _fnct_amount_info_label(self, cr, uid, ids, name, args, context=None):
        res = {}        
        for voucher in self.browse(cr, uid, ids, context=context):
            res[voucher.id] = self._get_amount_help_label(cr, uid, voucher.currency_id.id, voucher.amount, voucher.company_currency_id.id, context=context)
        return res
    
    _columns = {
        'is_currency': fields.boolean('Is multi currency'),
        'amount_info': fields.function(_fnct_amount_info_label, type='float', string='Amount Rate'),
        'currency_inverse_help_label': fields.text('Rate'),
        'company_currency_id': fields.related('company_id','currency_id', type='many2one', relation='res.currency', string='Company Currency'),
        'currency_help_label': fields.function(_fnct_currency_help_label, type='text', string="Helping Sentence", help="This sentence helps you to know how to specify the payment rate by giving you the direct effect it has"), 
    }
#     is_currency = fields.Boolean('Is multi currency')
#     amount_info = fields.Float(string='Amount Rate', compute='_compute_rate_amount') 
#     currency_inverse_help_label = fields.Text(string='Helping Rate Sentence', compute='_compute_rate_amount')
    def onchange_rate(self, cr, uid, ids, rate, amount, currency_id, payment_rate_currency_id, company_id, context=None):
        company_currency = self.pool.get('res.company').browse(cr, uid, company_id, context=context).currency_id
        #currency_pool = self.pool.get('res.currency')
        #rate_view = currency_pool.browse(cr, uid, currency_id, context=context).rate
        #print "==onchange_rate==",amount,rate,rate_view,amount*rate_view
        res =  {'value': {'paid_amount_in_company_currency': amount, 'amount_info':  self._get_amount_help_label(cr, uid, currency_id, amount, company_currency.id, context=context), 'currency_help_label': self._get_currency_help_label(cr, uid, currency_id, rate, payment_rate_currency_id, context=context)}}
        if rate and amount and currency_id:
            company_currency = self.pool.get('res.company').browse(cr, uid, company_id, context=context).currency_id
            #context should contain the date, the payment currency and the payment rate specified on the voucher
            amount_in_company_currency = self.pool.get('res.currency').compute(cr, uid, currency_id, company_currency.id, amount, context=context)
            res['value']['paid_amount_in_company_currency'] = amount_in_company_currency
        return res
        
    def onchange_journal(self, cr, uid, ids, journal_id, line_ids, tax_id, partner_id, date, amount, ttype, company_id, context=None):
        if context is None:
            context = {}
        if not journal_id:
            return False
        journal_pool = self.pool.get('account.journal')
        journal = journal_pool.browse(cr, uid, journal_id, context=context)
        if ttype in ('sale', 'receipt'):
            account_id = journal.default_debit_account_id
        elif ttype in ('purchase', 'payment'):
            account_id = journal.default_credit_account_id
        else:
            account_id = journal.default_credit_account_id or journal.default_debit_account_id
        tax_id = False
        if account_id and account_id.tax_ids:
            tax_id = account_id.tax_ids[0].id
 
        vals = {'value':{} }
        if ttype in ('sale', 'purchase'):
            vals = self.onchange_price(cr, uid, ids, line_ids, tax_id, partner_id, context)
            vals['value'].update({'tax_id':tax_id,'amount': amount})
        currency_id = False
        if journal.currency:
            currency_id = journal.currency.id
        else:
            currency_id = journal.company_id.currency_id.id
 
        period_ids = self.pool['account.period'].find(cr, uid, dt=date, context=dict(context, company_id=company_id))
        is_currency = False
        if journal.currency.id and journal.currency.id != journal.company_id.currency_id.id:
            is_currency = True
        #print "===is_currency====",is_currency,journal.currency.id,journal.company_id.currency_id.id
        vals['value'].update({
            'currency_id': currency_id,
            'payment_rate_currency_id': currency_id,
            'is_currency': is_currency,
            'period_id': period_ids and period_ids[0] or False
        })
        #in case we want to register the payment directly from an invoice, it's confusing to allow to switch the journal 
        #without seeing that the amount is expressed in the journal currency, and not in the invoice currency. So to avoid
        #this common mistake, we simply reset the amount to 0 if the currency is not the invoice currency.
        if context.get('payment_expected_currency') and currency_id != context.get('payment_expected_currency'):
            vals['value']['amount'] = 0
            amount = 0
        if partner_id:
            res = self.onchange_partner_id(cr, uid, ids, partner_id, journal_id, amount, currency_id, ttype, date, context)
            for key in res.keys():
                vals[key].update(res[key])
        return vals
예제 #21
0
class certificate(models.Model):
    def _get_status(self, cr, uid, ids, field_name, arg, context=None):
        r = {}
        for cer in self.browse(cr, uid, ids):
            r[cer.id] = 'valid'  #KGB
            continue  #KGB

            if not cer.csr and not cer.crt:
                r[cer.id] = 'empty'
            elif cer.csr and not cer.crt:
                try:
                    req = cer.get_request()[cer.id]
                    pkey = req.get_pubkey()
                    if req.verify(pkey):
                        r[cer.id] = 'valid_request'
                    else:
                        r[cer.id] = 'invalid_request'
                except:
                    r[cer.id] = 'invalid_request'
            elif cer.csr and cer.crt:
                req = cer.get_request()[cer.id]
                pkey = req.get_pubkey()
                try:
                    crt = cer.get_certificate()[cer.id]
                    r[cer.id] = 'valid' if crt.verify() and crt.verify(
                        pkey) else 'invalid'
                except:
                    r[cer.id] = 'invalid'
            elif not cer.csr and cer.pairkey_id and cer.crt:
                pkey = cer.pairkey_id.as_pkey()[cer.pairkey_id.id]
                try:
                    crt = cer.get_certificate()[cer.id]
                    r[cer.id] = 'valid' if crt.verify() and crt.verify(
                        pkey) else 'invalid'
                except:
                    r[cer.id] = 'invalid'

            else:
                r[cer.id] = 'Invalid'
        return r

    _name = "crypto.certificate"
    _columns = {
        'name':
        fields.char('Name', size=256),
        'csr':
        fields.text('Request Certificate',
                    readonly=True,
                    states={'draft': [('readonly', False)]},
                    help='Certificate Request in PEM format.'),
        'crt':
        fields.text('Certificate',
                    readonly=True,
                    states={
                        'draft': [('readonly', False)],
                        'waiting': [('readonly', False)]
                    },
                    help='Certificate in PEM format.'),
        'pairkey_id':
        fields.many2one('crypto.pairkey', 'Key pair'),
        'status':
        fields.function(_get_status,
                        method=True,
                        string='Status',
                        type='char',
                        help='Certificate Status'),
        'state':
        fields.selection(
            [
                ('draft', 'Draft'),
                ('waiting', 'Waiting'),
                ('confirmed', 'Confirmed'),
                ('cancel', 'Cancelled'),
            ],
            'State',
            select=True,
            readonly=True,
            help=
            '* The \'Draft\' state is used when a user is creating a new pair key. Warning: everybody can see the key.\
            \n* The \'Waiting\' state is used when a request has send to Certificate Authority and is waiting for response.\
            \n* The \'Confirmed\' state is used when a certificate is valid.\
            \n* The \'Canceled\' state is used when the key is not more used. You cant use this key again.'
        ),
    }
    _defaults = {
        'state': 'draft',
    }

    def action_validate(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        certs = self.read(cr,
                          uid,
                          ids, ['name', 'status', 'state'],
                          context=context)
        confirm_ids = []
        waiting_ids = []
        for cert in certs:
            status = cert['status']
            state = cert['state']
            if status in 'valid_request' and state == 'draft':
                waiting_ids.append(cert['id'])
            elif status == 'valid' and state in ['draft', 'waiting']:
                confirm_ids.append(cert['id'])
            else:
                #KGB?raise osv.except_osv(_('Invalid action !'),
                #KGB?                     _('Perhaps you want to insert an invalid request or certificate, or you want approve an invalid certificate with an valid request. Status: %s, State: %s'))
                pass
        self.write(cr,
                   uid,
                   confirm_ids, {'state': 'confirmed'},
                   context=context)
        self.write(cr, uid, waiting_ids, {'state': 'waiting'}, context=context)
        return True

    def action_cancel(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
        return True

    def get_request(self, cr, uid, ids, context=None):
        """
        Return Request object.
        """
        r = {}
        for cert in self.browse(cr, uid, ids):
            if cert.csr:
                r[cert.id] = X509.load_request_string(cert.csr.encode('ascii'))
        return r

    def get_certificate(self, cr, uid, ids, context=None):
        """
        Return Certificate object.
        """
        r = {}
        for cert in self.browse(cr, uid, ids):
            if cert.crt:
                r[cert.id] = X509.load_cert_string(cert.crt.encode('ascii'))
        return r

    def generate_certificate(self,
                             cr,
                             uid,
                             ids,
                             issuer,
                             ext=None,
                             serial_number=1,
                             version=2,
                             date_begin=None,
                             date_end=None,
                             expiration=365,
                             context=None):
        """
        Generate certificate
        """
        for item in self.browse(cr, uid, ids):
            if item.status == 'valid_request':
                # Get request data
                pk = item.pairkey_id.as_pkey()[item.pairkey_id.id]
                req = item.get_request()[item.id]
                sub = req.get_subject()
                pkey = req.get_pubkey()
                # Building certificate
                cert = X509.X509()
                cert.set_serial_number(serial_number)
                cert.set_version(version)
                cert.set_subject(sub)

                now = ASN1.ASN1_UTCTIME()
                if date_begin is None:
                    t = long(time.time()) + time.timezone
                    now.set_time(t)
                else:
                    now.set_datetime(date_begin)

                nowPlusYear = ASN1.ASN1_UTCTIME()
                if date_end is None:
                    nowPlusYear.set_time(t + 60 * 60 * 24 * expiration)
                else:
                    nowPlusYear.set_datetime(date_end)

                cert.set_not_before(now)
                cert.set_not_after(nowPlusYear)
                cert.set_issuer(issuer)
                cert.set_pubkey(pkey)
                cert.set_pubkey(cert.get_pubkey())
                if ext:
                    cert.add_ext(ext)
                cert.sign(pk, 'sha1')
                w = {'crt': cert.as_pem()}
                self.write(cr, uid, item.id, w)

    def smime(self, cr, uid, ids, message, context=None):
        """
        Sign message in SMIME format.
        """
        r = {}
        for cert in self.browse(cr, uid, ids):
            #if cert.status == 'valid': # EXTRANGE: Invalid certificates can be used for sign!
            if True:
                smime = SMIME.SMIME()
                ks = BIO.MemoryBuffer(cert.pairkey_id.key.encode('ascii'))
                cs = BIO.MemoryBuffer(cert.crt.encode('ascii'))
                bf = BIO.MemoryBuffer(str(message))
                out = BIO.MemoryBuffer()
                try:
                    smime.load_key_bio(ks, cs)
                except EVP.EVPError:
                    raise except_orm(
                        _('Error in Key and Certificate strings !'),
                        _('Please check if private key and certificate are in ASCII PEM format.'
                          ))
                sbf = smime.sign(bf)
                smime.write(out, sbf)
                r[cert.id] = out.read()
            else:
                raise except_orm(
                    _('This certificate is not ready to sign any message !'),
                    _('Please set a certificate to continue. You must send your certification request to a authoritative certificator to get one, or execute a self sign certification'
                      ))
        return r
class product_product(osv.osv):

    _name = 'product.product'
    _inherit = 'product.product'

    def get_price_pricelist(self, id, pricelist):
        return 1

    def ba_price_frendly_style(self, price):
        if isinstance(price, float):
            price = round(price, 2)
        price_text = str(price).split('.')
        return "$ " + price_text[0] + "<sup>" + price_text[1] + "</sup>"

    def _fnct_pricelist_price(self,
                              cr,
                              uid,
                              ids,
                              field_name,
                              args,
                              context=None):
        product_pricelist_obj = self.pool.get('product.pricelist')
        tax_obj = self.pool.get('account.tax')

        if context is None:
            context = {}
        res = {}
        for product in self.browse(cr, uid, ids, context=context):
            price_pricelist = self.pool.get('product.pricelist').price_get(
                cr, uid, [2], product.id, 1.0, 1, {
                    'uom': 1,
                    'date': unicode(date.today())
                })

            res[product.id] = ''
            if 2 in price_pricelist:
                sum_tax = 0
                for tax in product.taxes_id:
                    sum_tax += price_pricelist[2] * tax.amount
                    res[product.id] = str('%.2f' %
                                          (price_pricelist[2] + sum_tax))

        return res

    def _fnct_sales_condition_text(self,
                                   cr,
                                   uid,
                                   ids,
                                   field_name,
                                   args,
                                   context=None):
        product_pricelist_obj = self.pool.get('product.pricelist')
        if context is None:
            context = {}
        res = {}
        for product in self.browse(cr, uid, ids, context=context):
            product_pricelist = product_pricelist_obj.browse(cr,
                                                             uid,
                                                             31,
                                                             context=context)
            res[product.id] = ""

            price_pricelist = self.pool.get('product.pricelist').price_get(
                cr, uid, [31], product.id, 1.0, 1, {
                    'uom': 1,
                    'date': unicode(date.today())
                })
            sum_tax = 0
            for tax in product.taxes_id:
                sum_tax += price_pricelist[31] * tax.amount
                for conditions_id in product_pricelist[
                        'pricelist_sale_condition']:
                    if conditions_id['fee'] == 1:
                        res[product.id] += conditions_id[
                            'description'] + ' ' + "${0:.2f}".format(
                                (price_pricelist[31] + sum_tax)) + "  | "
                    else:
                        res[product.id] += conditions_id[
                            'description'] + ' ' + "${0:.2f}".format(
                                (price_pricelist[31] + sum_tax) /
                                conditions_id['fee']
                            ) + ' (Total: ' + "${0:.2f}".format(
                                (price_pricelist[31] + sum_tax)) + ') | '

            for pricelist_child in product_pricelist['pricelist_id_set']:
                price_pricelist = self.pool.get('product.pricelist').price_get(
                    cr, uid, [pricelist_child['id']], product.id, 1.0, 1, {
                        'uom': 1,
                        'date': unicode(date.today())
                    })
                sum_tax = 0
                for tax in product.taxes_id:
                    sum_tax += price_pricelist[
                        pricelist_child['id']] * tax.amount
                    for conditions_id in pricelist_child[
                            'pricelist_sale_condition']:
                        if conditions_id['fee'] == 1:
                            res[product.id] += conditions_id[
                                'description'] + ' ' + "${0:.2f}".format(
                                    (price_pricelist[pricelist_child['id']] +
                                     sum_tax)) + "  | "
                        else:
                            res[product.id] += conditions_id[
                                'description'] + ' ' + "${0:.2f}".format(
                                    (price_pricelist[pricelist_child['id']] +
                                     sum_tax) / conditions_id['fee']
                                ) + ' (Total: ' + "${0:.2f}".format(
                                    (price_pricelist[pricelist_child['id']] +
                                     sum_tax)) + ') | '
        return res

    _columns = {
        'total_price':
        fields.function(
            _fnct_pricelist_price,
            string='Precio con impuestos',
            type='char',
            size=256,
        ),
        'total_price_condition_text':
        fields.function(
            _fnct_sales_condition_text,
            string='condiciones',
            type='text',
        ),
    }
예제 #23
0
class hr_contract(models.Model):

    _name = 'hr.contract'
    _inherit = ['hr.contract', 'mail.thread', 'ir.needaction_mixin']

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

        res = []
        employee_pool = self.pool['hr.employee']
        for ee in employee_pool.browse(cr, uid, ids, context=context):
            for contract in ee.contract_ids:
                if contract.state not in ['pending_done', 'done']:
                    res.append(contract.id)
        return res

    def _get_department(self, cr, uid, ids, field_name, arg, context=None):

        res = dict.fromkeys(ids, False)
        states = ['pending_done', 'done']
        for contract in self.browse(cr, uid, ids, context=context):
            if contract.department_id and contract.state in states:
                res[contract.id] = contract.department_id.id
            elif contract.employee_id.department_id:
                res[contract.id] = contract.employee_id.department_id.id
        return res

    _columns = {
        'state':
        fields.selection(
            [('draft', 'Draft'), ('trial', 'Trial'),
             ('trial_ending', 'Trial Period Ending'), ('open', 'Open'),
             ('contract_ending', 'Ending'),
             ('pending_done', 'Pending Termination'), ('done', 'Completed')],
            'State',
            readonly=True,
        ),
        # store this field in the database and trigger a change only if the
        # contract is in the right state: we don't want future changes to an
        # employee's department to impact past contracts that have now ended.
        # Increased priority to override hr_simplify.
        'department_id':
        fields.function(
            _get_department,
            type='many2one',
            method=True,
            obj='hr.department',
            string="Department",
            readonly=True,
            store={
                'hr.employee': (_get_ids_from_employee, ['department_id'], 10)
            },
        ),
        # At contract end this field will hold the job_id, and the
        # job_id field will be set to null so that modules that
        # reference job_id don't include deactivated employees.
        'end_job_id':
        fields.many2one(
            'hr.job',
            'Job Title',
            readonly=True,
        ),
        # The following are redefined again to make them editable only in
        # certain states
        'employee_id':
        fields.many2one(
            'hr.employee',
            "Employee",
            required=True,
            readonly=True,
            states={'draft': [('readonly', False)]},
        ),
        'type_id':
        fields.many2one(
            'hr.contract.type',
            "Contract Type",
            required=True,
            readonly=True,
            states={'draft': [('readonly', False)]},
        ),
        'date_start':
        fields.date(
            'Start Date',
            required=True,
            readonly=True,
            states={'draft': [('readonly', False)]},
        ),
        'wage':
        fields.float(
            'Wage',
            digits=(16, 2),
            required=True,
            readonly=True,
            states={'draft': [('readonly', False)]},
            help="Basic Salary of the employee",
        ),
    }

    _defaults = {
        'state': 'draft',
    }

    _track = {
        'state': {
            'hr_contract_state.mt_alert_trial_ending':
            (lambda s, cr, u, o, c=None: o['state'] == 'trial_ending'),
            'hr_contract_state.mt_alert_open':
            (lambda s, cr, u, o, c=None: o['state'] == 'open'),
            'hr_contract_state.mt_alert_contract_ending':
            (lambda s, cr, u, o, c=None: o['state'] == 'contract_ending'),
        },
    }

    def _needaction_domain_get(self, cr, uid, context=None):

        users_obj = self.pool.get('res.users')
        domain = []

        if users_obj.has_group(cr, uid, 'base.group_hr_manager'):
            domain = [('state', 'in',
                       ['draft', 'contract_ending', 'trial_ending'])]
            return domain

        return False

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

        import logging
        _l = logging.getLogger(__name__)
        _l.warning('hr_contract_state: onchange_job()')
        res = False
        if isinstance(ids, (int, long)):
            ids = [ids]
        if ids:
            contract = self.browse(cr, uid, ids[0], context=None)
            if contract.state != 'draft':
                return res
        return super(hr_contract, self).onchange_job(cr,
                                                     uid,
                                                     ids,
                                                     job_id,
                                                     context=context)

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

        for contract in self.browse(cr, uid, ids, context=context):
            if not contract.trial_date_start:
                return False
        return True

    def try_signal_ending_contract(self, cr, uid, context=None):

        d = datetime.now().date() + relativedelta(days=+30)
        ids = self.search(
            cr,
            uid, [('state', '=', 'open'),
                  ('date_end', '<=', d.strftime(DEFAULT_SERVER_DATE_FORMAT))],
            context=context)
        if len(ids) == 0:
            return

        wkf = netsvc.LocalService('workflow')
        for contract in self.browse(cr, uid, ids, context=context):
            wkf.trg_validate(uid, 'hr.contract', contract.id,
                             'signal_ending_contract', cr)

    def try_signal_contract_completed(self, cr, uid, context=None):
        d = datetime.now().date()
        ids = self.search(
            cr,
            uid, [('state', '=', 'open'),
                  ('date_end', '<', d.strftime(DEFAULT_SERVER_DATE_FORMAT))],
            context=context)
        if len(ids) == 0:
            return

        wkf = netsvc.LocalService('workflow')
        for contract in self.browse(cr, uid, ids, context=context):
            wkf.trg_validate(uid, 'hr.contract', contract.id,
                             'signal_pending_done', cr)

    def try_signal_ending_trial(self, cr, uid, context=None):

        d = datetime.now().date() + relativedelta(days=+10)
        ids = self.search(
            cr,
            uid,
            [('state', '=', 'trial'),
             ('trial_date_end', '<=', d.strftime(DEFAULT_SERVER_DATE_FORMAT))],
            context=context)
        if len(ids) == 0:
            return

        wkf = netsvc.LocalService('workflow')
        for contract in self.browse(cr, uid, ids, context=context):
            wkf.trg_validate(uid, 'hr.contract', contract.id,
                             'signal_ending_trial', cr)

    def try_signal_open(self, cr, uid, context=None):

        d = datetime.now().date() + relativedelta(days=-5)
        ids = self.search(
            cr,
            uid,
            [('state', '=', 'trial_ending'),
             ('trial_date_end', '<=', d.strftime(DEFAULT_SERVER_DATE_FORMAT))],
            context=context)
        if len(ids) == 0:
            return

        wkf = netsvc.LocalService('workflow')
        for contract in self.browse(cr, uid, ids, context=context):
            wkf.trg_validate(uid, 'hr.contract', contract.id, 'signal_open',
                             cr)

    def onchange_start(self, cr, uid, ids, date_start, context=None):
        return {
            'value': {
                'trial_date_start': date_start,
            },
        }

    def state_trial(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {'state': 'trial'}, context=context)
        return True

    def state_open(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {'state': 'open'}, context=context)
        return True

    def state_pending_done(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {'state': 'pending_done'}, context=context)
        return True

    def state_done(self, cr, uid, ids, context=None):
        for i in ids:
            data = self.read(cr,
                             uid,
                             i, ['date_end', 'job_id'],
                             context=context)
            vals = {
                'state': 'done',
                'date_end': False,
                'job_id': False,
                'end_job_id': data['job_id'][0]
            }

            if data.get('date_end', False):
                vals['date_end'] = data['date_end']
            else:
                vals['date_end'] = time.strftime(DEFAULT_SERVER_DATE_FORMAT)

            self.write(cr, uid, ids, vals, context=context)
        return True
                for amount in sol_amt:
                    cost += amount
            if 0.0 not in sol_amt or not sol_amt:
                if len(sol_amt) > 0.00:
                    try:
                        avg_cost = (float(cost) / len(sol_amt))
                    except:
                        pass
            res[case.id] = avg_cost
        return res

    _columns = {
        'price_total':
        fields.function(_amount_line,
                        string='Tax included in Amount',
                        type="float",
                        digits_compute=dp.get_precision('Account'),
                        store=True,
                        multi='all'),
        'price_subtotal':
        fields.function(_amount_line,
                        string='Amount',
                        type="float",
                        digits_compute=dp.get_precision('Account'),
                        store=True,
                        multi='all'),
        'reference':
        fields.char("Reference", size=20),
        'cost_price':
        fields.function(_cost_prize,
                        string='Cost Price',
                        type="float",
예제 #25
0
class custom_res_partner(osv.osv):
    _name = "res.partner"
    _inherit = 'res.partner'

    def _x_opportunity_meeting_count(self,
                                     cr,
                                     uid,
                                     ids,
                                     field_name,
                                     arg,
                                     context=None):
        res = dict(
            map(
                lambda x: (x, {
                    'x_opportunity_count': 0,
                    'x_meeting_count': 0
                }), ids))
        # the user may not have access rights for opportunities or meetings
        try:
            for partner in self.browse(cr, uid, ids, context):
                if partner.is_company:
                    operator = 'child_of'
                else:
                    operator = '='
                opp_ids = self.pool['crm.lead'].search(
                    cr,
                    uid, [('partner_id', operator, partner.id),
                          ('type', '=', 'opportunity'),
                          ('probability', '<', '100')],
                    context=context)
                res[partner.id] = {
                    'x_opportunity_count': len(opp_ids),
                    'x_meeting_count': len(partner.x_meeting_ids),
                }
        except:
            pass
        return res

    ##########           MEDICAL INFO ???
    # @api.one
    # @api.depends('x_poids','x_taille')
    # def _compute_IMC(self):
    #     if self.x_taille == 0:
    #         self.x_IMC = '0'
    #     else:
    #         self.x_IMC = self.x_poids / ((self.x_taille / 100) * (self.x_taille / 100))
    ##########

    @api.one
    @api.depends('name', 'x_patient_prenom')
    def _compute_display_name(self):
        if self.x_patient_prenom == '':
            names = [self.name]
        else:
            names = [self.name, self.x_patient_prenom]
        self.display_name = ' '.join(filter(None, names))


    _columns = {
        'partner_id' : fields.many2one('res.partner','Customer', default=lambda self: self.env.user.partner_id),
        'display_name' : fields.char(string='Name', compute='_compute_display_name'),
        'x_patient_prenom': fields.char('Prénom', size=16),
        'x_patient_sexe': fields.selection(SEXE_SELECTION, string='Sexe'),
        'x_convention_type': fields.selection(CONVENTION_SELECTION, string='Protection'),
        'x_patient_cafat': fields.char(string='Numéro assuré', size=8, help='Numéro CAFAT du patient'),
        'x_is_pro': fields.boolean('is_pro_bool', help="Check if the contact is a professional, otherwise it is a patient"),
        'x_compte_type': fields.selection(selection=[('patient', 'Patient'), ('pro', 'Pro')], string='Type compte'),
        'dob': fields.date('Date de naissance'),
        'age' : fields.integer('Age'),
        'x_src_avatar' : fields.binary("x_src_avatar", attachment=True,
            help="This field holds the image used as avatar for this contact, limited to 1024x1024px"),
        'x_medecin_traitant': fields.char('Médecin traitant', size=32),
        ##########           MEDICAL INFO ???
        # 'x_groupe_sang': fields.selection(GRP_SANG_SELECTION, string='Groupe sang.'),
        # 'x_taille': fields.float('Taille (cm)',digits=(4,6)),
        # 'x_poids': fields.float('Poids (kg)',digits=(4,6)),
        # 'x_IMC': fields.float(string='IMC', compute='_compute_IMC',digits=(4,6)),
        ##########

        # Reprise de CRM
        'x_opportunity_ids': fields.one2many('crm.lead', 'partner_id',\
            'Opportunities', domain=[('type', '=', 'opportunity')]),
        'x_meeting_ids': fields.one2many('calendar.event', 'x_partner_id',
            'Meetings'),
        'x_opportunity_count': fields.function(_x_opportunity_meeting_count, string="Opportunity", type='integer', multi='opp_meet'),
        'x_meeting_count': fields.function(_x_opportunity_meeting_count, string="# Meetings", type='integer', multi='opp_meet'),
    }

    def redirect_partner_form(self, cr, uid, partner_id, context=None):
        search_view = self.pool.get('ir.model.data').get_object_reference(
            cr, uid, 'base', 'view_res_partner_filter')

    _order = 'name, x_patient_prenom'

    _default = {
        'x_patient_sexe': 'masculin',
        'x_patient_cafat': '',
        'x_is_pro': False,
        'x_compte_type': 'pro',
        'x_medecin_traitant': ' ',
        'x_groupe_sang': '',
        ##########           MEDICAL INFO ???
        # 'x_taille': '0,1',
        # 'x_poids': '0,1',
        ##########
    }

    _sql_constraints = []

    #############            Changement Praticien <-> Patient            #############
    @api.multi
    def _on_change_compte_type(self, x_compte_type):
        return {'value': {'x_is_pro': x_compte_type == 'pro'}}

    #############            Changement de date de naissance            #############
    @api.onchange('dob')
    def _onchange_getage_id(self, cr, uid, ids, dob, context=None):
        current_date = datetime.now()
        current_year = current_date.year
        birth_date = parser.parse(dob)
        current_age = current_year - birth_date.year

        val = {'age': current_age}
        return {'value': val}

    #############            Donne l'image a utiliser comme avatar            #############
    #############    MODIFY ??? !!!
    @api.model
    def _get_default_avatar(self, vals):
        if getattr(threading.currentThread(), 'testing',
                   False) or self.env.context.get('install_mode'):
            return False
        # ------------------ CABINET
        if self.is_company == True:
            img_path = openerp.modules.get_module_resource(
                'AlloDoc', 'static/src/img', 'company_image.png')
        elif self.x_compte_type == 'pro':
            if self.x_patient_sexe == 'feminin':
                img_path = openerp.modules.get_module_resource(
                    'AlloDoc', 'static/src/img', 'avatar_medecin_femme.png')
            else:
                img_path = openerp.modules.get_module_resource(
                    'AlloDoc', 'static/src/img', 'avatar_medecin_homme.png')
        # ------------------ PATIENTS
        #----------------------- Adultes
        elif self.age > 18:
            if self.x_patient_sexe == 'feminin':
                img_path = openerp.modules.get_module_resource(
                    'AlloDoc', 'static/src/img', 'avatar_femme.png')
            else:
                img_path = openerp.modules.get_module_resource(
                    'AlloDoc', 'static/src/img', 'avatar_homme.png')
        #----------------------- Enfants
        elif self.age > 2:
            if self.x_patient_sexe == 'feminin':
                img_path = openerp.modules.get_module_resource(
                    'AlloDoc', 'static/src/img', 'avatar_fille.png')
            else:
                img_path = openerp.modules.get_module_resource(
                    'AlloDoc', 'static/src/img', 'avatar_garcon.png')
        #----------------------- Bebes
        elif self.age <= 2:
            if self.x_patient_sexe == 'feminin':
                img_path = openerp.modules.get_module_resource(
                    'AlloDoc', 'static/src/img', 'avatar_bebe_f.png')
            else:
                img_path = openerp.modules.get_module_resource(
                    'AlloDoc', 'static/src/img', 'avatar_bebe_g.png')
        #----------------------- Default
        else:
            img_path = openerp.modules.get_module_resource(
                'AlloDoc', 'static/src/img', 'avatar_default.png')

        with open(img_path, 'rb') as f:
            x_src_avatar = f.read()

        # return img_avatar
        return tools.image_resize_image_big(x_src_avatar.encode('base64'))

    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.display_name or ''
            if record.parent_id and not record.is_company:
                if not name and record.type in [
                        'invoice', 'delivery', 'other'
                ]:
                    name = dict(
                        self.fields_get(
                            cr, uid, ['type'],
                            context=context)['type']['selection'])[record.type]
                name = "%s, %s" % (record.parent_name, name)
            if context.get('show_address_only'):
                name = self._display_address(cr,
                                             uid,
                                             record,
                                             without_company=True,
                                             context=context)
            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)
            if context.get('html_format'):
                name = name.replace('\n', '<br/>')
            res.append((record.id, name))
        return res

    # Need to write these lines twice to get result I excepted...
    # if not, at save, avatar is not updated with value filled in form (_get_default_avatar),
    # but with values previously stored in DB
    @api.multi
    def write(self, vals):

        vals['x_src_avatar'] = self._get_default_avatar(vals)
        result = super(custom_res_partner, self).write(vals)
        vals['x_src_avatar'] = self._get_default_avatar(vals)
        result = super(custom_res_partner, self).write(vals)

        return result
class account_invoice(osv.osv):
    _name = 'account.invoice'
    _inherit = 'account.invoice'

    def fields_view_get(self,
                        cr,
                        uid,
                        view_id=None,
                        view_type='form',
                        context=None,
                        toolbar=False,
                        submenu=False):

        if context is None:
            context = {}
        res = super(account_invoice, self).fields_view_get(cr,
                                                           uid,
                                                           view_id=view_id,
                                                           view_type=view_type,
                                                           context=context,
                                                           toolbar=toolbar,
                                                           submenu=False)
        doc = etree.XML(res['arch'])
        cr.execute("""select uid from res_groups_users_rel where gid=
          (select id  from res_groups where category_id in 
          ( select id from ir_module_category where name = 'Customer Portal' ) and name = 'Manager') and uid = """
                   + str(uid))
        portal_user = cr.fetchone()
        portal_group = portal_user and portal_user[0]

        if uid == portal_group:
            for node in doc.xpath("//field[@name='partner_id']"):
                node.set('options', "{'no_open' : true}")
                setup_modifiers(node, res['fields']['partner_id'])
                res['arch'] = etree.tostring(doc)

            for node in doc.xpath("//field[@name='contact_id']"):
                node.set('options', "{'no_open' : true}")
                setup_modifiers(node, res['fields']['contact_id'])
                res['arch'] = etree.tostring(doc)

        cr.execute("""select uid from res_groups_users_rel where gid=
          (select id  from res_groups where category_id in 
          ( select id from ir_module_category where name = 'Supplier Portal' ) ) and uid = """
                   + str(uid))
        sup_portal = cr.fetchone()
        supportal_group = sup_portal and sup_portal[0]

        if uid == supportal_group:
            for node in doc.xpath("//field[@name='partner_id']"):
                node.set('options', "{'no_open' : true}")
                setup_modifiers(node, res['fields']['partner_id'])
                res['arch'] = etree.tostring(doc)
        return res

    #Overidden
    def _amount_all(self, cr, uid, ids, name, args, context=None):
        res = {}
        without_round = 0.00

        for invoice in self.browse(cr, uid, ids, context=context):
            res[invoice.id] = {
                'amount_untaxed': 0.0,
                'amount_tax': 0.0,
                'amount_total': 0.0,
                'round_off': 0.0,
            }

            for line in invoice.invoice_line:
                res[invoice.id]['amount_untaxed'] += line.price_subtotal

            for line in invoice.tax_line:
                res[invoice.id]['amount_tax'] += line.amount

            res[invoice.id]['amount_total'] = round(
                res[invoice.id]['amount_tax'] +
                res[invoice.id]['amount_untaxed'])
            without_round = res[invoice.id]['amount_tax'] + res[
                invoice.id]['amount_untaxed']
            res[invoice.id]['round_off'] = res[
                invoice.id]['amount_total'] - without_round

        return res

    #Overidden
    def _get_invoice_line(self, cr, uid, ids, context=None):
        result = {}
        for line in self.pool.get('account.invoice.line').browse(
                cr, uid, ids, context=context):
            result[line.invoice_id.id] = True
        return result.keys()

    # Funtion To Convert Amount to Text
    def _amt_in_words(self, cr, uid, ids, field_name, args, context=None):
        res = {}

        for case in self.browse(cr, uid, ids):
            txt = ''
            res[case.id] = ''
            if case.amount_total:
                txt += amount_to_text_softapps._100000000_to_text(
                    int(round(case.amount_total)))
                res[case.id] = txt
        return res

    def _get_type(self, cr, uid, context=None):
        if context is None:
            context = {}
        return context.get('type', 'out_invoice')

    _columns = {
        'contact_id':
        fields.many2one('res.partner', 'Contact Person'),
        'amt_in_words':
        fields.function(_amt_in_words,
                        method=True,
                        string="Amount in Words",
                        type="text",
                        store=True),
        'transport':
        fields.char("Customer PO Reference", size=50),
        'vehicle':
        fields.char("Vehicle", size=20),
        'dc_ref':
        fields.char("DC Reference", size=200),
        'date_from':
        fields.function(lambda *a, **k: {},
                        method=True,
                        type='date',
                        string="From"),
        'date_to':
        fields.function(lambda *a, **k: {},
                        method=True,
                        type='date',
                        string="To"),
        'terms':
        fields.text("Terms And Condition"),
        #Overidden
        'amount_untaxed':
        fields.function(_amount_all,
                        digits_compute=dp.get_precision('Account'),
                        string='Subtotal',
                        track_visibility='always',
                        store=True,
                        multi='all'),
        'amount_tax':
        fields.function(_amount_all,
                        digits_compute=dp.get_precision('Account'),
                        string='Tax',
                        store=True,
                        multi='all'),
        'amount_total':
        fields.function(_amount_all,
                        digits_compute=dp.get_precision('Account'),
                        string='Total',
                        store=True,
                        multi='all'),
        'round_off':
        fields.function(_amount_all,
                        digits_compute=dp.get_precision('Account'),
                        string='Round off',
                        store=True,
                        multi='all'),
    }
    _order = "id desc"

    def unlink(self, cr, uid, ids, context=None):
        pick_obj = self.pool.get("stock.picking")

        for case in self.browse(cr, uid, ids):
            if case.state == 'draft':
                if case.internal_number:
                    self.write(cr, uid, ids, {'internal_number': False})
                pick_ids = pick_obj.search(cr, uid,
                                           [('invoice_id', '=', case.id)])
                pick_obj.write(cr, uid, pick_ids,
                               {'invoice_state': '2binvoiced'})

        return super(account_invoice, self).unlink(cr, uid, ids, context)
예제 #27
0
파일: employee.py 프로젝트: hwua/openerp
class EmployeeUserInfo(osv.Model):
    _inherit = 'hr.employee'

    @api.multi
    def action_go_to_user(self):
        user = self.mapped('user_id')
        form_view_id = self.env['ir.model.data'].xmlid_to_res_id(
            'base.view_users_form')
        result = {
            'name': '账号',
            'type': 'ir.actions.act_window',
            'views': [(form_view_id, 'form')],
            'target': 'new',
            'res_model': 'res.users',
            'flags': {
                'form': {
                    'action_buttons': True
                }
            }
        }
        if user:
            result['res_id'] = user.id
        else:
            result = {'type': 'ir.actions.act_window_close'}
        return result

    def _get_user_info(self, cr, uid, ids, field_name, arg, context=None):
        ui = self.pool.get('survey.user_input')

        res = dict(map(lambda x: (x, 0), ids))
        for employee in self.browse(cr, uid, ids, context):
            if field_name == 'user_info_mail':
                res[employee.id] = employee.user_id.email
            if field_name == 'user_info_create_time':
                res[employee.id] = employee.user_id.create_date
            if field_name == 'user_info_login_time':
                res[employee.id] = employee.user_id.login_date
            if field_name == 'user_info_role':
                g = ''
                for group in employee.user_id.groups_id:
                    if not group.category_id:
                        g += '<p style="color:green;margin:0;padding:0">' + group.name + '</p>'
                res[employee.id] = g

            # one2many字段需要双向对应,即employee_id与input_id,没有employee模型参与,故使用function计算
            if field_name == 'survey_ids':
                res[employee.id] = self.pool["survey.user_input"].search(
                    cr, uid, [('create_uid', '=', employee.user_id.id),
                              ('state', '=', 'done')])

        return res

    _columns = {
        'user_info_mail':
        fields.function(_get_user_info, type='char', string='用户账号'),
        'user_info_create_time':
        fields.function(_get_user_info, type='char', string='创建时间'),
        'user_info_login_time':
        fields.function(_get_user_info, type='char', string='登录时间'),
        'user_info_role':
        fields.function(_get_user_info, type='html', string='权限'),
        'survey_ids':
        fields.function(_get_user_info,
                        type='one2many',
                        relation='survey.user_input',
                        string='已完成')
    }

    def create(self, cr, uid, vals, context=None):
        vals['state'] = 'draft'
        vals['active'] = False
        return super(EmployeeUserInfo, self).create(cr, uid, vals)
예제 #28
0
class hr_job(models.Model):

    _name = 'hr.job'
    _inherit = 'hr.job'

    def _get_all_child_ids(self, cr, uid, ids, field_name, arg, context=None):
        result = dict.fromkeys(ids)
        for i in ids:
            result[i] = self.search(cr,
                                    uid, [('parent_id', 'child_of', i)],
                                    context=context)

        return result

    _columns = {
        'department_manager':
        fields.boolean('Department Manager', ),
        'parent_id':
        fields.many2one(
            'hr.job',
            'Immediate Superior',
            ondelete='cascade',
        ),
        'child_ids':
        fields.one2many(
            'hr.job',
            'parent_id',
            'Immediate Subordinates',
        ),
        'all_child_ids':
        fields.function(
            _get_all_child_ids,
            type='many2many',
            relation='hr.job',
        ),
        'parent_left':
        fields.integer(
            'Left Parent',
            select=1,
        ),
        'parent_right':
        fields.integer(
            'Right Parent',
            select=1,
        ),
    }

    _parent_name = "parent_id"
    _parent_store = True
    _parent_order = 'name'
    _order = 'parent_left'

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

        # Copied from product.category
        # This is a brute-force approach to the problem, but should be good
        # enough.
        #
        level = 100
        while len(ids):
            cr.execute('select distinct parent_id from hr_job where id IN %s',
                       (tuple(ids), ))
            ids = filter(None, map(lambda x: x[0], cr.fetchall()))
            if not level:
                return False
            level -= 1
        return True

    def _rec_message(self, cr, uid, ids, context=None):
        return _('Error!\nYou cannot create recursive jobs.')

    _constraints = [
        (_check_recursion, _rec_message, ['parent_id']),
    ]

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

        res = super(hr_job, self).write(cr, uid, ids, vals, context=None)

        if isinstance(ids, (int, long)):
            ids = [ids]

        dept_obj = self.pool.get('hr.department')
        if vals.get('department_manager', False):
            for di in ids:
                job = self.browse(cr, uid, di, context=context)
                dept_id = False
                if vals.get('department_id', False):
                    dept_id = vals['department_id']
                else:
                    dept_id = job.department_id.id
                employee_id = False
                for ee in job.employee_ids:
                    employee_id = ee.id
                if employee_id:
                    dept_obj.write(cr,
                                   uid,
                                   dept_id, {
                                       'manager_id': employee_id,
                                   },
                                   context=context)
        elif vals.get('department_id', False):
            for di in ids:
                job = self.browse(cr, uid, di, context=context)
                if job.department_manager:
                    employee_id = False
                    for ee in job.employee_ids:
                        employee_id = ee.id
                    dept_obj.write(cr,
                                   uid,
                                   vals['department_id'], {
                                       'manager_id': employee_id,
                                   },
                                   context=context)
        elif vals.get('parent_id', False):
            ee_obj = self.pool.get('hr.employee')
            parent_job = self.browse(cr,
                                     uid,
                                     vals['parent_id'],
                                     context=context)
            parent_id = False
            for ee in parent_job.employee_ids:
                parent_id = ee.id
            for job in self.browse(cr, uid, ids, context=context):
                ee_obj.write(cr,
                             uid, [ee.id for ee in job.employee_ids], {
                                 'parent_id': parent_id,
                             },
                             context=context)

        return res
예제 #29
0
class cloud_service_domain(models.Model):
    _name = 'cloud.service.domain'
    _inherit = 'cloud.service'
    _description = 'cloud.service.domain'

    def getFournisseurZoneDnsrecordId(self, cr, uid, ids, context):
        # create a client using configuration
        zonerecords = {}
        client = ovh.Client(endpoint='ovh-eu')
        # Request RO, /me API access
        access_rules = [
            {
                'method': 'GET',
                'path': '/*'
            },
            {
                'method': 'POST',
                'path': '/*'
            },
            {
                'method': 'PUT',
                'path': '/*'
            },
            {
                'method': 'DELETE',
                'path': '/*'
            },
        ]
        # Request token
        #validation = client.request_consumerkey(access_rules)
        for domain in self.browse(self, cr, uid, ids, context=None):
            zone = domain.domain
            _logger.info('zone   %s' % (zone))

        zone = '/domain/zone/' + zone
        zonerecords = client.get(zone)
        _logger.info('zone records  %s' % (zonerecords))

        return zonerecords

    def getFournisseurLineZoneDnsrecordById(self,
                                            cr,
                                            uid,
                                            ids,
                                            record,
                                            context=None):
        # create a client using configuration
        linerecordid = {}
        client = ovh.Client(endpoint='ovh-eu')
        # Request RO, /me API access
        access_rules = [
            {
                'method': 'GET',
                'path': '/*'
            },
            {
                'method': 'POST',
                'path': '/*'
            },
            {
                'method': 'PUT',
                'path': '/*'
            },
            {
                'method': 'DELETE',
                'path': '/*'
            },
        ]
        # Request token
        #validation = client.request_consumerkey(access_rules)
        for domain in self.browse(self, cr, uid, ids, context=None):
            zone = domain.domain
            _logger.info('zone   %s' % (zone))

        zone = '/domain/zone/' + zone + '/record/' + record
        linerecordid = client.get(zone)
        _logger.info('zone records  %s' % (linerecordid))

        return zonerecords

    def getLineZonednsByRecords(self, cr, uid, ids, context):

        Records = self.getFournisseurZoneDnsrecordId(cr, uid, ids, context)
        lines = {}
        for record in Records:
            try:
                lines[record] = self.getFournisseurLineZoneDnsrecordById(
                    self, cr, uid, ids, record, context)
            except IOError:
                lines[record] = record

        return lines

    def checkDomainFournisseur(self, cr, uid, ids, context):
        for this in self.browse(cr, uid, ids, context):
            _logger.info('this id  %s' % (this.id))

        # Request token
        #validation = client.request_consumerkey(access_rules)
        lines = getLineZonednsByRecords(self, cr, uid, ids, context)
        #text = "Please visit %s to authenticate" % validation['validationUrl']
        # Print nice welcome message
        text2 = "Welcome , %s" % (lines)
        #text3 = "Btw, your 'consumerKey' is '%s'" % validation['consumerKey']
        s = "Description  avec ovh conf : %s " % (text2)
        self.write(cr, uid, ids, {'description': s}, context=context)

        return True

    def _getGestionDnsActivation(self,
                                 cr,
                                 uid,
                                 ids,
                                 fieldnames,
                                 args,
                                 context=None):

        result = {}
        for record in self.browse(cr, uid, ids, context=context):
            result[record.id] = {
                record.id: 'Qui gere votre zone DNS',
            }
        return result

    _columns = {
        'domain':
        fields.Char('Nom de domain', size=256, required=True),
        'gestion_dns_activation':
        fields.function(
            _getGestionDnsActivation,
            type='text',
            string='Gestion DNS',
            help=
            "Service permettant de traduire votre nom de domain en adresse ip , ou la gestion de vos emails."
        ),
        'dnssec':
        fields.Boolean(
            readonly=True,
            default=False,
            copy=False,
            help="Protection de la zone DNS du domain par authentifiaction."),
        'zone_dns_line':
        fields.One2many('cloud.service.domain.zonedns',
                        'service_domain_id',
                        string='Zone DNS Lines',
                        readonly=True)
    }
예제 #30
0
class sale_order(osv.osv):
    _name = "sale.order"
    _inherit = "sale.order"

    def _sale_amount_text(self, cr, uid, ids, name, args, context=None):
        res = {}
        for line in self.browse(cr, uid, ids, context=context):
            if line.amount_total <> 0.00:
                res[line.id] = trad(int(line.amount_total)).upper()
        return res

    _columns = {
        'object':
        fields.char('Objet', required=False, help="Objet de l'offre"),
        'amount_text':
        fields.function(_sale_amount_text,
                        string='en lettre',
                        type='char',
                        help="Amount in text",
                        readonly=True),
    }

    def _prepare_invoice(self, cr, uid, order, lines, context=None):
        """Prepare the dict of values to create the new invoice for a
			sales order. This method may be overridden to implement custom
			invoice generation (making sure to call super() to establish
			a clean extension chain).

			:param browse_record order: sale.order record to invoice
			:param list(int) line: list of invoice line IDs that must be
									attached to the invoice
			:return: dict of value to create() the invoice
		"""
        if context is None:
            context = {}
        journal_id = self.pool['account.invoice'].default_get(
            cr, uid, ['journal_id'], context=context)['journal_id']
        if not journal_id:
            raise osv.except_osv(
                _('Error!'),
                _('Please define sales journal for this company: "%s" (id:%d).'
                  ) % (order.company_id.name, order.company_id.id))
        invoice_vals = {
            'name':
            order.client_order_ref or '',
            'origin':
            order.name,
            'type':
            'out_invoice',
            'reference':
            order.client_order_ref or order.name,
            'account_id':
            order.partner_invoice_id.property_account_receivable.id,
            'partner_id':
            order.partner_invoice_id.id,
            'journal_id':
            journal_id,
            'invoice_line': [(6, 0, lines)],
            'currency_id':
            order.pricelist_id.currency_id.id,
            'comment':
            order.note,
            'payment_term':
            order.payment_term and order.payment_term.id or False,
            'fiscal_position':
            order.fiscal_position.id
            or order.partner_invoice_id.property_account_position.id,
            'date_invoice':
            context.get('date_invoice', False),
            'company_id':
            order.company_id.id,
            'user_id':
            order.user_id and order.user_id.id or False,
            'section_id':
            order.section_id.id,
            'object':
            order.object,
        }

        # Care for deprecated _inv_get() hook - FIXME: to be removed after 6.1
        invoice_vals.update(self._inv_get(cr, uid, order, context=context))
        return invoice_vals