Example #1
0
    def generate_demo_plans(self):
        demo_plan_module_obj = self.env['saas_portal.demo_plan_module']
        demo_plan_hidden_module_obj = self.env['saas_portal.hidden_demo_plan_module']
        for record in self:
            db, uid, password, models = record._get_xmlrpc_object(record.name)
            ids = models.execute_kw(db, uid, password, 'ir.module.module', 'search',
                                    [[['demo_url', '!=', False]]],
                                    )
            modules = models.execute_kw(db, uid, password, 'ir.module.module', 'read', [ids])
            for module in modules:
                plan = record._create_demo_plan(module)

                if not plan:
                    continue

                vals = record._prepare_module(module, plan)
                demo_plan_module_obj.create(vals)
                record._create_demo_product(module, plan)
                if module.get('demo_addons'):
                    ids = models.execute_kw(db, uid, password, 'ir.module.module', 'search',
                                            [[['name', 'in', module['demo_addons'].split(',')]]],
                                            {'limit': 10})
                    addon_modules = models.execute_kw(db, uid, password, 'ir.module.module', 'read', [ids])
                    for addon in addon_modules:
                        vals = record._prepare_module(addon, plan)
                        demo_plan_module_obj.create(vals)
                if module.get('demo_addons_hidden'):
                    for addon in module['demo_addons_hidden'].split(','):
                        demo_plan_hidden_module_obj.create({'technical_name': addon, 'demo_plan_id': plan.id})

        return True
Example #2
0
def _refresh_cats(self, cr, uid, ids, context=None):
    record = self.browse(cr, uid, ids, context)[0]
    for category in record.categories:
        category.unlink()
    url = record.url
    db = record.db
    username = record.user
    password = record.pwd
    common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
    #print common.version

    rem_uid = common.authenticate(db, username, password, {})
    print "USER ID ON REMOTE ODOO FOR USER admin is: %s" % rem_uid
    models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))

    cat_ids = self.pool.get('product.category').search(cr,
                                                       uid, [],
                                                       context=None)
    print "LENGHT: %s" % cat_ids
    local_cats = [{
        'name': x.name,
        'id': x.id,
        'parent_id': x.parent_id.id
    } for x in self.pool.get('product.category').browse(
        cr, uid, cat_ids, context=None)]

    for c in local_cats:
        f_id = models.execute_kw(db, uid, password, 'product.category',
                                 'search', [[['name', '=', c['name']]]])
        if not f_id:

            self.pool.get('product.compare.category').create(
                cr,
                uid, {
                    "local_cat": c['id'],
                    "compare_id": record.id
                },
                context=None)
        else:

            f_cat = models.execute_kw(db, uid, password, 'product.category',
                                      'read', [f_id],
                                      {'fields': ['name', 'parent_id']})[0]
            parent = False
            if not f_cat['parent_id']:
                parent = True
            elif f_cat['parent_id'] != c['parent_id']:
                parent = True
            if f_id[0] != c['id']:  #or parent:
                self.pool.get('product.compare.category').create(
                    cr,
                    uid, {
                        "local_cat": c['id'],
                        "compare_id": record.id,
                        "wrong_id": True,
                        "remote_cat": f_id[0]
                    },
                    context=None)

    return True
Example #3
0
 def _get_odoo_version(self):
     self.ensure_one()
     db, uid, password, models = self._get_xmlrpc_object(self.name)
     ids = models.execute_kw(db, uid, password, 'ir.module.module', 'search',
                             [[['name', '=', 'base']]],
                             )
     base_module = models.execute_kw(db, uid, password,
                                 'ir.module.module',
                                 'read', [ids],
                                 {'fields': ['latest_version']})
     return base_module[0].get('latest_version')
Example #4
0
 def update_templates(self):
     for record in self:
         plans = self.env['saas_portal.plan'].search([('server_id', '=', record.id),
                                                      ('demo_plan_module_ids', '!=', False),
                                                      ('template_id.state', '=', 'template')])
         for plan in plans:
             db, uid, password, models = plan.template_id._get_xmlrpc_object()
             id = models.execute_kw(db, uid, password, 'ir.module.module', 'search',
                                     [[['name', 'in', ['base']]]])
             models.execute_kw(db, uid, password, 'ir.module.module', 'button_upgrade', [id])
     return True
Example #5
0
    def backup_now(self):
        _logger.error("backup now")

        db_name = self.env.cr.dbname
        cmd = ['pg_dump', '--no-owner']
        cmd.append(db_name)

        t=tempfile.TemporaryFile()

        with odoo.tools.osutil.tempdir() as dump_dir:
            filestore = odoo.tools.config.filestore(db_name)
            if os.path.exists(filestore):
                shutil.copytree(filestore, os.path.join(dump_dir, 'filestore'))
            with open(os.path.join(dump_dir, 'manifest.json'), 'w') as fh:
                db = odoo.sql_db.db_connect(db_name)
                with db.cursor() as cr:
                    json.dump(self.dump_db_manifest(cr), fh, indent=4)
            cmd.insert(-1, '--file=' + os.path.join(dump_dir, 'dump.sql'))
            odoo.tools.exec_pg_command(*cmd)

            
            odoo.tools.osutil.zip_dir(dump_dir, t, include_dir=False, fnct_sort=lambda file_name: file_name != 'dump.sql')
            t.seek(0)
            save_name = db_name + ' ' +  datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' Backup'
            file_name = db_name + ' ' +  datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S') + '.zip'


        for backup_server in self.env['backup.server'].sudo().search([]):
                #Connect to the backup server and save the database
                common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(backup_server.host))
                uid = common.authenticate(backup_server.database_name, backup_server.username, backup_server.password, {})
                models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(backup_server.host))
                backup = models.execute_kw(backup_server.database_name, uid, backup_server.password,'backup.odoo', 'create',[{'user_id':uid, 'backup_type': 'full', 'database_name': self.env.cr.dbname, 'data': base64.b64encode( t.read() ), 'data_filename': file_name}])
Example #6
0
 def create_db_invoice(self):
     get_param = self.env['ir.config_parameter'].get_param
     username = get_param('user', default='')
     password = get_param('password', default='')
     url = get_param('url', default='')
     db = get_param('db', default='')
     if username and password and url and db:
         print username
         print password
         print url
         print db
         common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
         uid = common.authenticate(db, username, password, {})
         models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
         new_invoice = models.execute_kw(
             db,
             uid,
             password,
             'account.invoice',
             'create',
             [{
                 'partner_id': self.partner_id.id,
                 'journal_id': self.journal_id.id,
                 'account_id': self.account_id.id,
                 # 'invoice_line': self.invoice_line.id,
             }])
     else:
         raise ValidationError(
             "Please configure db credential in setting...!")
Example #7
0
    def updatePrices(self, cr, uid, ids, context=None, product_id=None):
        _logger = logging.getLogger(__name__)
        _logger.info("PRODUCT PRICE UPDATE ID: %s" % product_id)
        product_ids = product_id or self.pool.get('product.template').search(
            cr, uid, [('active', '=', True)], context=None)
        products = self.pool.get('product.template').browse(cr,
                                                            uid,
                                                            product_ids,
                                                            context=None)

        record = self.browse(cr, uid, ids, context)[0]

        url = record.url
        db = record.db
        username = record.user
        password = record.pwd
        common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
        #print common.version

        rem_uid = common.authenticate(db, username, password, {})
        _logger.info("_______USER ID ON REMOTE ODOO FOR USER admin is: %s" %
                     rem_uid)
        models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
        cnt = 0
        for p in products:
            if not p.default_code:
                continue
            rem_p_id = models.execute_kw(
                db, uid, password, 'product.template', 'search',
                [[['default_code', '=', p.default_code]]])
            if rem_p_id:
                models.execute_kw(db, uid, password, 'product.template',
                                  'write', [
                                      rem_p_id, {
                                          'list_price': p.list_price,
                                          'net_price': p.net_price
                                      }
                                  ])
                cnt += 1
                _logger.info("----UPDATED %s (%s)" % (p.default_code, cnt))
    def sync_settings(self):

        url = 'http://odooutv.vertel.se'
        db = 'xmlrpc_mail_config'
        username = '******'
        password = '******'

        config = {
            "postfix_active": self.postfix_active,
            "vacation_active": self.vacation_active,
            "forward_active": self.forward_active,
            "forward_address": self.forward_address,
            "forward_cp": self.forward_cp,
            "virus_active": self.virus_active,
            "spam_active": self.spam_active,
            "spam_tag": self.spam_tag,
            "spam_tag2": self.spam_tag2,
            "spam_killevel": self.spam_killevel,
            "maildir": self.maildir,
            "transport": self.transport,
            "quota": self.quota,
            "domain": self.domain,
            "password": self.passwd_mail,
            "mail_alias": self.mail_alias,
        }

        common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
        uid = common.authenticate(db, username, password, {})

        models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))

        models.execute_kw(db, uid, password, 'res.users', 'create',
                          [{
                              "test": "tes"
                          }])

        return
Example #9
0
	def sync_settings(self):


		url = 'http://odooutv.vertel.se'
		db = 'xmlrpc_mail_config'
		username = '******'
		password = '******'

		config = {
			"postfix_active" : self.postfix_active,
			"vacation_active" : self.vacation_active,
			"forward_active" : self.forward_active,
			"forward_address" : self.forward_address,
			"forward_cp" : self.forward_cp,
			"virus_active" : self.virus_active,
			"spam_active" : self.spam_active,
			"spam_tag" : self.spam_tag,
			"spam_tag2" : self.spam_tag2,
			"spam_killevel" : self.spam_killevel,
			"maildir" : self.maildir,
			"transport" : self.transport,
			"quota" : self.quota,
			"domain" : self.domain,
			"password" : self.passwd_mail,
			"mail_alias" : self.mail_alias,
		}

		common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
		uid = common.authenticate(db, username, password, {})		

		models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))

		models.execute_kw(db, uid, password,
		'res.users', 'create', [{"test": "tes"}])

		return
Example #10
0
    def check_database(self):
        import xmlrpclib
        import psycopg2
        import os
        
        if not self.database_name:
            return
        
        try:
            common = xmlrpclib.ServerProxy('%s/xmlrpc/2/common' % 'http://localhost:8069')
            uid = common.authenticate(self.database_name, 'admin', get_config('admin_passwd','Master password is missing'),{})
            models = xmlrpclib.ServerProxy('%s/xmlrpc/2/object' % 'http://localhost:8069')
        except xmlrpclib.Error as err:
            raise Warning(_("%s (server %s, db %s)" % (err, 'localhost', self.database_name)))

        res = models.execute_kw(self.database_name,uid,get_config('admin_passwd','Master password is missing'),'res.users','search', [[['active','=',True],['share','=',False]]],{})
        self.nbr_users = len(set(res)-set([1]))
        res = models.execute_kw(self.database_name,uid,get_config('admin_passwd','Master password is missing'),'res.users','read', [list(set(res)-set([1]))])
        last_login = None
        for l in res:
            if l.get('login_date',None) > last_login:
                last_login = l.get('login_date')
        self.last_login = last_login
        _logger.error('res.users %s' % res)
        conn = psycopg2.connect(dbname=self.database_name, user='******', password=get_config('admin_passwd','Master password is missing'), host='localhost')
        cur = conn.cursor()
        cur.execute("select pg_database_size('%s')" % self.database_name)
        self.database_size = float(cur.fetchone()[0]) / 1024 / 1014 
        cur.close()
        conn.close()

        _logger.error('size %s' % (float(os.popen('du -s /var/lib/odoo/filestore/%s' % self.database_name).read().split('\t')[0]) / 1024))
        self.database_disk = (float(os.popen('du -s /var/lib/odoo/filestore/%s' % self.database_name).read().split('\t')[0]) / 1024)
        #self.database_disk = sum(os.path.getsize(f) for f in [os.listdir('/var/lib/odoo/.local/share/Odoo/filestore/%s/%s' % (self.database_name,d)) for d in os.listdir('/var/lib/odoo/.local/share/Odoo/filestore/%s' % self.database_name)])
        companies = models.execute_kw(self.database_name,uid,get_config('admin_passwd','Master password is missing'),'res.company','search', [[]],{})
        self.mailsize = sum([float(c.get('total_quota',0.0)) for c in models.execute_kw(self.database_name,uid,get_config('admin_passwd','Master password is missing'),'res.company','read', [companies])])
        self.database_backup = ((os.path.getsize('/var/backups/%s.sql.gz' % self.database_name) / 1024 / 1024) + self.database_size + self.database_disk + self.mailsize) * 2
        self.total_size = round(self.mailsize + self.database_backup + self.database_disk + self.database_size)
        
        #raise Warning(len(self.recurring_invoice_line_ids.filtered(lambda r: r.product_id.id == self._product_extra_users())))
        invoice_lines = []
        product_extra_users = self.env['product.product'].browse(self._product_extra_users())
        if self.nbr_users > 1 and len(self.recurring_invoice_line_ids.filtered(lambda r: r.product_id.id == product_extra_users.id))==0:
            invoice_lines.append((0,0,{
                'product_id': product_extra_users.id,
                'name': "Extra användare",
                'price_unit': product_extra_users.list_price,
                'uom_id': product_extra_users.uom_id.id,
                'quantity': 1.0,
            }))
        product_extra_space = self.env['product.product'].browse(self._product_extra_space())
        if self.total_size > 1024.0 and len(self.recurring_invoice_line_ids.filtered(lambda r: r.product_id.id == product_extra_space.id))==0:
            invoice_lines.append((0,0,{
                'product_id': product_extra_space.id,
                'name': "Extra användare",
                'price_unit': product_extra_space.list_price,
                'uom_id': product_extra_space.uom_id.id,
                'quantity': 1.0,
            }))

        self.recurring_invoice_line_ids = invoice_lines
Example #11
0
    def transfer(self, cr, uid, order_id, context=None):
        _logger = logging.getLogger(__name__)
        def_id = self.search(cr, uid, [("in_use", '=', True)], context=None)
        if not def_id:
            return None

        record = self.browse(cr, uid, def_id, context=None)

        order = self.pool.get('sale.order').browse(cr,
                                                   uid,
                                                   order_id,
                                                   context=None)[0]
        _logger.info("++++++ %s" % order.name)

        #CREATE PO local
        po_client = record.po_client_id

        vals = {
            'partner_id': po_client,
            'location_id': 1,
            'pricelist_id': order.pricelist_id.id
        }

        po_local_id = self.pool.get('purchase.order').create(cr,
                                                             uid,
                                                             vals,
                                                             context=None)

        for line in order.order_line:
            vals = {
                'product_id': line.product_id.id,
                'name': line.name,
                'product_qty': line.product_uom_qty,
                'date_planned': datetime.now().strftime('%d/%m/%Y'),
                'price_unit': line.price_unit,
                'order_id': po_local_id,
                'taxes_id': [[6, False, [x.id for x in line.tax_id]]]
            }
            line_id = self.pool.get('purchase.order.line').create(cr,
                                                                  uid,
                                                                  vals,
                                                                  context=None)

        #CREATE REMOTE SO
        url = record.ro_url
        db = record.ro_db
        username = record.ro_user
        password = record.ro_pass

        common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
        uidx = common.authenticate(db, username, password, {})

        models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))

        par = models.execute_kw(
            db, uid, password, 'res.partner', 'read', [[190856]],
            {'fields': ['property_product_pricelist']})  #make user insertable

        par = par[0]
        pricelist = par['property_product_pricelist'][0] if par[
            'property_product_pricelist'] else 1
        vals = {
            'partner_id': record.remote_client_id,
            'pricelist_id': pricelist,
            'partner_invoice_id': record.remote_client_id,
            'partner_shipping_id': record.remote_client_id,
            'order_policy': 'picking',
            'picking_policy': 'direct',
            'warehouse_id': 1,
            'remote_document_id': order.name,
            'state': 'preorder'
        }

        so = models.execute_kw(db, uidx, password, 'sale.order', 'create',
                               [vals])

        for line in order.order_line:
            remote_product_id = models.execute_kw(
                db, uidx, password, 'product.product', 'search_read',
                [[['default_code', '=', line.product_id.default_code]]],
                {'fields': ['uom_id', 'product_tmpl_id']})

            vals = {
                "product_uos_qty":
                line.product_uos_qty,
                "product_uom_qty":
                line.product_uom_qty,
                "order_partner_id":
                record.remote_client_id,
                "product_template":
                remote_product_id[0]['product_tmpl_id'][0],
                "delay":
                0,
                'product_id':
                remote_product_id[0]['id'],
                'name':
                line.name,
                'product_uom':
                remote_product_id[0]['uom_id'][0]
                if 'uom_id' in remote_product_id[0] else 1,
                'price_unit':
                line.price_unit,
                'order_id':
                so,
                'tax_id': [[6, False, [x.id for x in line.tax_id]]],
                'state':
                'preorder'
            }
            models.execute_kw(db, uidx, password, 'sale.order.line', 'create',
                              [vals])
Example #12
0
def _sync(self, cr, uid, ids, context=None, product_id=None):
    _logger = logging.getLogger(__name__)
    record = self.browse(cr, uid, ids, context)[0]

    url = record.url
    db = record.db
    username = record.user
    password = record.pwd
    common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
    #print common.version

    rem_uid = common.authenticate(db, username, password, {})
    _logger.info("_______USER ID ON REMOTE ODOO FOR USER admin is: %s" %
                 rem_uid)
    models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))

    to_check = [x for x in record.field_to_check]
    cat_map_obj = self.pool.get('product.compare.category')

    cat_map = cat_map_obj.browse(cr,
                                 uid,
                                 cat_map_obj.search(cr, uid, [], context=None),
                                 context=None)

    if len(record.lines) == 0:
        return True

    counter = 0
    r_lines = []
    if product_id:
        for p in record.lines:
            if p.product_id.id in product_id:
                r_lines.append(p)

    else:
        r_lines = record.lines
    for p in r_lines:

        #if counter > 200:
        #break
        try:
            if not p.product_id.default_code:
                _logger.info("NO INTERNAL REFERENCE")
                continue

            if p.code_for_foreign:
                f_id = models.execute_kw(
                    db, uid, password, 'product.template', 'search',
                    [[['default_code', '=', p.product_id.default_code]]])
                _logger.info("****************EXISTS: %s" % f_id)

                _logger.info("********************in create %s" %
                             p.product_id.name)
                vals = {}
                vals['name'] = p.code_for_foreign

                vals['categ_id'] = p.product_id.categ_id.id
                for cm in cat_map:

                    if cm.local_cat.id == p.product_id.categ_id.id and cm.compare_id.id == record.id:
                        _logger.info("going with mapped category")
                        vals['categ_id'] = cm.remote_cat

                _logger.info(vals)
                if record.sync_images and p.product_id.image:
                    vals['image'] = p.product_id.image
                for f in to_check:

                    if f.ttype == 'many2one':
                        vals[f.name] = p.product_id[f.name].id
                    elif f.ttype == 'many2many':
                        vals[f.name] = [[4, p.product_id[f.name].id]]
                    else:
                        vals[f.name] = p.product_id[f.name]
                    print vals

                if not f_id:
                    vals['default_code'] = p.product_id.default_code
                    models.execute_kw(db, uid, password, 'product.template',
                                      'create', [vals])
                else:
                    f_id = f_id[0]
                    vals.pop('categ_id')
                    updated = models.execute_kw(db, uid, password,
                                                'product.template', 'write',
                                                [[f_id], vals])
                    _logger.info("************** %s" % updated)

                p.unlink()
                counter += 1
        except:
            #raise osv.except_osv(_('Sync error'), _('There`s been an error trying to sync item %s. Check if category %s exists on other company and if its entered in category mapping table' % (p.product_id.name, p.product_id.categ_id.name)))

            continue

    return True  #_refresh_all(self, cr, uid, ids, context=None)
Example #13
0
def _refresh_all(self, cr, uid, ids, context=None, product_id=None):
    #_logger = logging.getLogger(__name__)
    record = self.browse(cr, uid, ids, context)[0]
    for item in record.lines:
        if product_id:
            if item.product_id.id in product_id:
                item.unlink()
        else:
            item.unlink()

    addAll = record.add_all
    url = record.url
    db = record.db
    username = record.user
    password = record.pwd
    common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
    #print common.version

    rem_uid = common.authenticate(db, username, password, {})
    print "USER ID ON REMOTE ODOO FOR USER admin is: %s" % rem_uid
    models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
    if product_id:
        products = self.pool.get('product.template').browse(cr,
                                                            uid,
                                                            product_id,
                                                            context=None)
        pro_ids = []
        for p in products:
            categ_ids = [x.id for x in p.categ_id.foreign_binding]
            if record.id in categ_ids:
                pro_ids.append(p.id)
    else:
        pro_ids = self.pool.get('product.template').search(
            cr, uid, [("categ_id.foreign_binding", "ilike", record.id),
                      ('active', '=', True)])

    #_logger.info("***********PRODUCTS THAT SHOULD BE ON THIS COMPANY: %s" % len(pro_ids))
    #return True
    #DEBUGGING
    #products = self.pool.get('product.template').browse(cr, uid, pro_ids, context=None)
    #print "PRODUCTS ARE: %s" % [x.name for x in products]
    if not record.field_to_check:
        print "NO FIELDS TO CHECK"
        return True

    to_check = [x for x in record.field_to_check]
    to_retrieve = [x.name for x in record.field_to_check]
    to_retrieve.append('name')
    to_retrieve.append('categ_id')

    #ENDING
    #return True

    if record.sync_images:
        to_retrieve.append('image')

    for p in self.pool.get('product.template').browse(cr,
                                                      uid,
                                                      pro_ids,
                                                      context=None):
        if not p.default_code:
            #_logger.info("skipping %s" % p.name)
            continue
        #_logger.info("going with %s" % p.name)
        f_ids = models.execute_kw(db, uid, password, 'product.template',
                                  'search',
                                  [[['default_code', '=', p.default_code]]])

        if f_ids:
            #BREAKER#BREAKER#BREAKER#BREAKER
            #continue
            #BREAKER#BREAKER#BREAKER#BREAKER
            f_pro = models.execute_kw(db, uid, password, 'product.template',
                                      'read', [f_ids],
                                      {'fields': to_retrieve})[0]
            #_logger.info("exists %s" % f_pro)
            hasDifference = False
            for field in to_check:

                if p[field.name]:
                    #check master type
                    if field.ttype in ['many2many', 'many2one']:
                        value = p[field.name].id
                        slave = False
                        if f_pro[field.name]:
                            slave = f_pro[field.name][0]
                    else:
                        value = p[field.name]
                        slave = f_pro[field.name]

                    if value != slave:
                        hasDifference = True
                        #_logger.info("%s ********* DIFFERENT OR NO %s" % (p.default_code, field.name))
                elif f_pro[field.name]:
                    hasDifference = True

            #MAGENTO INTEGRATION
            mage_price = ''
            if record.mage_integration:
                f_id = f_pro['id']
                mage_price = models.execute_kw(db, uid, password,
                                               'magento_sync', 'getMagePrice',
                                               [{
                                                   'sku': f_id
                                               }])

                if mage_price and float(mage_price) != p.list_price:
                    hasDifference = True

            #END magento

            if hasDifference or addAll:
                #_logger.info("******** in setting %s" % p.default_code)

                vals = {
                    'product_id': p.id,
                    'description': p.description,
                    'default_code': p.default_code,
                    'code_for_foreign': f_pro['name'],
                    'mage_price': mage_price,
                    'info_diff': True,
                    'compare_id': record.id,
                    'category_foreign': f_pro['categ_id'][1]
                }
                self.pool.get('product.compare.line').create(cr,
                                                             uid,
                                                             vals,
                                                             context=context)
            #_logger.info("Exists but no diff")
        else:
            #_logger.info("dont exist %s" % p.name)
            vals = {
                'product_id': p.id,
                'description': p.description,
                'default_code': p.default_code,
                'compare_id': record.id
            }
            self.pool.get("product.compare.line").create(cr,
                                                         uid,
                                                         vals,
                                                         context=context)
    return True
Example #14
0
    def transfer(self, cr, uid, order_id, context=None):
        _logger = logging.getLogger(__name__)
        _logger.info("IN TRANSFER ORDER")
        def_id = self.search(cr, uid, [("in_use", '=', True)], context=None)
        if not def_id:
            _logger.info("no configs in use")
            return None

        record = self.browse(cr, uid, def_id, context=None)

        url = record.ro_url
        db = record.ro_db
        username = record.ro_user
        password = record.ro_pass
        partner_foreign_id = int(
            record.remote_partner_id) if record.remote_partner_id else 0

        common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
        uidx = common.authenticate(db, username, password, {})

        models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))

        order = self.pool.get('purchase.order').browse(cr,
                                                       uidx,
                                                       order_id,
                                                       context=None)[0]

        par = models.execute_kw(
            db, uidx, password, 'res.partner', 'read', [[partner_foreign_id]],
            {'fields': ['property_product_pricelist']})  #make user insertable

        par = par[0]
        pricelist = par['property_product_pricelist'][0] if par[
            'property_product_pricelist'] else 1
        vals = {
            'partner_id': partner_foreign_id,
            'pricelist_id': pricelist,
            'partner_invoice_id': partner_foreign_id,
            'partner_shipping_id': partner_foreign_id,
            'order_policy': 'picking',
            'picking_policy': 'direct',
            'warehouse_id': 1,
            'remote_document_id': order.name,
            'state': 'preorder'
        }

        so = models.execute_kw(db, uidx, password, 'sale.order', 'create',
                               [vals])

        for line in order.order_line:
            remote_product_id = models.execute_kw(
                db, uidx, password, 'product.product', 'search_read',
                [[['default_code', '=', line.product_id.default_code]]],
                {'fields': ['uom_id', 'product_tmpl_id']})

            vals = {
                "product_uos_qty":
                line.product_qty,
                "product_uom_qty":
                line.product_qty,
                "order_partner_id":
                partner_foreign_id,
                "product_template":
                remote_product_id[0]['product_tmpl_id'][0],
                "delay":
                0,
                'product_id':
                remote_product_id[0]['id'],
                'name':
                line.name,
                'product_uom':
                remote_product_id[0]['uom_id'][0]
                if 'uom_id' in remote_product_id[0] else 1,
                'price_unit':
                line.price_unit,
                'order_id':
                so,
                'tax_id': [[6, False, [x.id for x in line.taxes_id]]],
                'state':
                'preorder'
            }
            models.execute_kw(db, uidx, password, 'sale.order.line', 'create',
                              [vals])

        order.remote_order_id = so
Example #15
0
 def update_repositories(self):
     for record in self:
         db, uid, password, models = record._get_xmlrpc_object(record.name)
         ids = models.execute_kw(db, uid, password, 'saas_server.repository', 'search', [[]],)
         models.execute_kw(db, uid, password, 'saas_server.repository', 'update', [ids])
     return True
Example #16
0
    def transfer(self, cr, uid, order_id, context=None):
        _logger = logging.getLogger(__name__)
        def_id = self.search(cr, uid, [("in_use", '=', True)], context=None)
        if not def_id:
            return None

        record = self.browse(cr, uid, def_id, context=None)

        url = record.ro_url
        db = record.ro_db
        username = record.ro_user
        password = record.ro_pass

        common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
        uidx = common.authenticate(db, username, password, {})

        models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))

        order = self.pool.get('sale.order').browse(cr,
                                                   uidx,
                                                   order_id,
                                                   context=None)[0]
        _logger.info("++++++ %s" % order.name)
        par = models.execute_kw(
            db, uid, password, 'res.partner', 'read', [[190856]],
            {'fields': ['property_product_pricelist']})  #make user insertable

        par = par[0]
        pricelist = par['property_product_pricelist'][0] if par[
            'property_product_pricelist'] else 1
        vals = {
            'partner_id': 191286,
            'location_id': 1,
            'pricelist_id': pricelist
        }

        po = models.execute_kw(db, uidx, password, 'purchase.order', 'create',
                               [vals])

        for line in order.order_line:
            remote_product_id = models.execute_kw(
                db, uidx, password, 'product.product', 'search_read',
                [[['default_code', '=', line.product_id.default_code]]],
                {'fields': ['uom_id']})
            remote_uom = models.execute_kw(
                db, uidx, password, 'product.uom', 'search',
                [[['name', '=', remote_product_id[0]['uom_id'][1]]]])

            vals = {
                'product_id': remote_product_id[0]['id'],
                'name': line.name,
                'product_uom': remote_uom[0] if len(remote_uom) else 1,
                'product_qty': line.product_uom_qty,
                'date_planned': datetime.now().strftime('%d/%m/%Y'),
                'price_unit': line.price_unit,
                'order_id': po,
                'taxes_id': [[6, False, [x.id for x in line.tax_id]]]
            }
            models.execute_kw(db, uidx, password, 'purchase.order.line',
                              'create', [vals])

        order.remote_order_id = po
 def ajouter_dans_agenda(self):
     now = datetime.datetime.now()
     tz = pytz.timezone('CET')
     offset=tz.utcoffset(now).total_seconds()
     events=[]
     if self.type_demande in ["cp_rtt_journee","sans_solde","autre"]:
         dt1 = datetime.datetime.strptime(self.date_debut + " 08:00:00", '%Y-%m-%d %H:%M:%S')
         dt2 = datetime.datetime.strptime(self.date_fin   + " 08:00:00", '%Y-%m-%d %H:%M:%S')
         start = dt1
         while start <= dt2:
             events.append([
                 start - datetime.timedelta(seconds=offset), 
                 start - datetime.timedelta(seconds=offset) + datetime.timedelta(hours=10), 
             ])
             start = start + datetime.timedelta(days=1)
     if self.type_demande=="cp_rtt_demi_journee":
         start = self.le
         if self.matin_ou_apres_midi=="matin":
             start = self.le+" 08:00:00"
         else:
             start = self.le+" 13:30:00"
         start = datetime.datetime.strptime(start, '%Y-%m-%d %H:%M:%S')
         start = start - datetime.timedelta(seconds=offset)
         stop = start + datetime.timedelta(hours=4)
         events.append([start, stop])
     if self.type_demande=="rc_heures": 
         hours, minutes = divmod(self.heure_debut*60, 60)
         debut = " %02d:%02d:00"%(hours,minutes)
         hours, minutes = divmod(self.heure_fin*60, 60)
         fin   = " %02d:%02d:00"%(hours,minutes)
         start = self.le + debut
         start = datetime.datetime.strptime(start, '%Y-%m-%d %H:%M:%S')
         start = start - datetime.timedelta(seconds=offset)
         stop = self.le + fin
         stop = datetime.datetime.strptime(stop, '%Y-%m-%d %H:%M:%S')
         stop = stop - datetime.timedelta(seconds=offset)
         events.append([start, stop])
     email = self.demandeur_id.partner_id.email
     company = self.env.user.company_id
     DB = "odoo-agenda"
     USERID = 2
     DBLOGIN = "******"
     USERPASS = company.is_agenda_pwd
     url = company.is_agenda_url+'/xmlrpc/2/common'
     common = xmlrpclib.ServerProxy(url, verbose=False, use_datetime=True, context=ssl._create_unverified_context())
     uid = common.authenticate(DB, DBLOGIN, USERPASS, {})
     url = company.is_agenda_url+'/xmlrpc/object'
     models = xmlrpclib.ServerProxy(url, verbose=False, use_datetime=True, context=ssl._create_unverified_context())
     partner = models.execute_kw(
         DB, USERID, USERPASS, 
         'res.partner', 
         'search_read', 
         [[('email', '=', email)]],
         {'fields': ['name','email'], 'limit': 1}
     )
     if partner:
         partner_id=partner[0]["id"]
         user = models.execute_kw(
             DB, USERID, USERPASS, 
             'res.users', 
             'search_read', 
             [[('partner_id', '=',partner_id)]],
             {'fields': ['login'], 'limit': 1}
         )
         if user:
             user_id=user[0]["id"]
             name=self.type_demande
             for line in _TYPE_DEMANDE:
                 if line[0]==self.type_demande:
                     name = line[1]
             name=u"[Congé] "+name
             for event in events:
                 vals={
                     "name"       : name,
                     "user_id"    : user_id,
                     "start"      : str(event[0]),
                     "stop"       : str(event[1]),
                     "partner_ids": [[6, False, [partner_id]]],
                 }
                 event_id = models.execute_kw(DB, USERID, USERPASS, 'calendar.event', 'create', [vals])
                 print(event_id,vals)
                 if event_id:
                     attendee = models.execute_kw(
                         DB, USERID, USERPASS, 
                         'calendar.attendee', 
                         'search_read', 
                         [[('event_id', '=', event_id)]],
                         {'fields': ['state'], 'limit': 1}
                     )
                     if attendee:
                         attendee_id=attendee[0]["id"]
                         models.execute_kw(DB, USERID, USERPASS, 'calendar.attendee', 'write', [[attendee_id], {'state': "accepted"}])
Example #18
0
 def restart_server(self):
     for record in self:
         db, uid, password, models = record._get_xmlrpc_object(record.name)
         models.execute_kw(db, uid, password, 'saas_server.client', 'restart_server', [])
     return True