Пример #1
0
def execute(conf_attrs, dbname, uid, obj, method, *args, **kwargs):
    import openerp
    from openerp.api import Environment
    from openerp.modules.registry import Registry
    for attr, value in conf_attrs.items():
        openerp.tools.config[attr] = value
    with Environment.manage():
        registry = Registry(dbname)
        cr = registry.cursor()
        context = kwargs.get('context') and kwargs.pop('context') or {}
        env = Environment(cr, uid, context)
        # openerp.api.Environment._local.environments = env
        try:
            getattr(env.registry[obj], method)(cr, uid, *args, **kwargs)
            # Commit only when function finish
            env.cr.commit()
        except Exception as exc:
            env.cr.rollback()
            try:
                raise execute.retry(
                    queue=execute.request.delivery_info['routing_key'],
                    exc=exc,
                    countdown=(execute.request.retries + 1) * 60,
                    max_retries=5)
            except Exception as retry_exc:
                raise retry_exc
        finally:
            env.cr.close()
    return True
Пример #2
0
def execute(conf_attrs, dbname, uid, obj, method, *args, **kwargs):
    import openerp
    from openerp.api import Environment
    from openerp.modules.registry import Registry
    for attr, value in conf_attrs.items():
        openerp.tools.config[attr] = value
    with Environment.manage():
        registry = Registry(dbname)
        cr = registry.cursor()
        context = kwargs.get('context') and kwargs.pop('context') or {}
        env = Environment(cr, uid, context)
        # openerp.api.Environment._local.environments = env
        try:
            print args
            getattr(env.registry[obj], method)(cr, uid, *args, **kwargs)
            # Commit only when function finish
            env.cr.commit()
        except Exception as exc:
            print exc
            env.cr.rollback()
            try:
                raise execute.retry(
                    queue=execute.request.delivery_info['routing_key'],
                    exc=exc, countdown=(execute.request.retries + 1) * 60,
                    max_retries=5)
            except Exception as retry_exc:
                raise retry_exc
        finally:
            env.cr.close()
    return True
Пример #3
0
 def abc_confirm_invoice(self, lines, packages, data, params, res):
     """Confirm invoice. Split into its own function to not lock the invoice sequence."""
     invoice = params.get('invoice')
     if invoice and invoice.state == 'draft':
         self.env.cr.commit()
         env = None
         try:
             # Ne cursor doesn't time out when requesting lock.
             # Could be bad I guess? Works for now.
             # TODO: Look into setting a more reasonable lock wait time.
             new_cr = Registry(self.env.cr.dbname).cursor()
             new_cr.autocommit(True)
             env = api.Environment(new_cr, self.env.uid, self.env.context)
             # Validate invoice
             invoice.signal_workflow('invoice_open')
             res['invoice']['name'] = invoice.number
             res['messages'].append(u"Created and confirmed invoice %s." %
                                    invoice.number)
             res['results']['invoice'] = 'confirmed'
             # Commit to unlock the invoice sequence
             env.cr.commit()
         except Exception as e:
             res['warnings'].append(
                 (_(u"Failed to confirm invoice %s!") %
                  (invoice and
                   (invoice.number or invoice.name) or 'Unknown'),
                  '%s\n\nTraceback:\n%s' %
                  (e.message or 'Unknown Error', traceback.format_exc())))
         finally:
             if env:
                 env.cr.close()
Пример #4
0
	def Getall(self, req,db=None):

		registry = Registry(db)
	
		with registry.cursor() as cr:

			query = cr.execute("""
				SELECT * from sales_activity_plan order by year_p DESC, week_no DESC, dow DESC, user_id, daylight, not_planned_actual limit 100
				""")
			values = cr.fetchall()
		return values
Пример #5
0
    def test_02_uninstall(self):
        """ Check a few things showing the module is uninstalled. """
        with environment() as env:
            module = env['ir.module.module'].search([('name', '=', MODULE)])
            assert len(module) == 1
            module.button_uninstall()
        Registry.new(common.get_db_name(), update_module=True)

        with environment() as env:
            self.assertNotIn('test_uninstall.model', env.registry)
            self.assertFalse(env['ir.model.data'].search([('module', '=', MODULE)]))
            self.assertFalse(env['ir.model.fields'].search([('model', '=', MODEL)]))
Пример #6
0
    def test_02_uninstall(self):
        """ Check a few things showing the module is uninstalled. """
        with environment() as env:
            module = env['ir.module.module'].search([('name', '=', MODULE)])
            assert len(module) == 1
            module.button_uninstall()
        Registry.new(common.get_db_name(), update_module=True)

        with environment() as env:
            self.assertNotIn('test_uninstall.model', env.registry)
            self.assertFalse(env['ir.model.data'].search([('module', '=',
                                                           MODULE)]))
            self.assertFalse(env['ir.model.fields'].search([('model', '=',
                                                             MODEL)]))
Пример #7
0
    def _fcm_send_notification(self,
                               subscription_ids,
                               payload,
                               dbname,
                               uid,
                               fcm_api_key,
                               attempt=1):
        res = None
        if not fcm_api_key:
            _logger.exception("You need a FCM API key to send notification")
            return

        headers = {
            "Content-Type": "application/json",
            "Authorization": "key=" + fcm_api_key,
        }
        data = {'data': payload, 'registration_ids': subscription_ids}
        res = {}

        try:
            response = requests.post(FCM_END_POINT,
                                     headers=headers,
                                     data=json.dumps(data))
            if response.status_code == 200:
                res = self._fcm_process_response(response, subscription_ids)
            elif response.status_code == 401:
                _logger.warning(
                    "FCM Authentication: Provide valid FCM api key")
            elif response.status_code == 400:
                _logger.warning("Invalid JSON: Invalid payload format")
            else:
                retry = self._fcm_calculate_retry_after(response.headers)
                if retry and attempt <= FCM_RETRY_ATTEMPT:
                    _logger.warning("FCM Service Unavailable: retrying")
                    time.sleep(retry)
                    attempt = attempt + 1
                    self._send_fcm_notification(subscription_ids,
                                                payload,
                                                dbname,
                                                uid,
                                                fcm_api_key,
                                                attempt=attempt)
                else:
                    _logger.warning(
                        "FCM service not available try after some time")
        except ConnectionError:
            _logger.warning("No Internet connection")
        except Exception:
            _logger.warning("Failed processing FCM queue")

        if res.get('errors') or res.get('canonical'):
            with api.Environment.manage():
                with Registry(dbname).cursor() as cr:
                    env = api.Environment(cr, uid, {})
                    if res.get('errors'):
                        self._fcm_process_errors(res['errors'], env)
                    if res.get('canonical'):
                        self._fcm_process_canonical(res['canonical'], env)
Пример #8
0
	def GetUpdate(self, req,db=None,activity_id=None,user_id=None,dow=None,daylight=None,idview=None):
		
		registry = Registry(db)
		with registry.cursor() as cr:

			query = cr.execute('''
				SELECT id from sales_activity_plan where activity_id=%s and user_id=%s and dow=%s and daylight=%s order by year_p DESC, week_no DESC, dow DESC, user_id, daylight, not_planned_actual limit 1
				''',[activity_id,user_id,dow,daylight])
			
			ids_sales_act = cr.fetchall()
			ids_sales_act=ids_sales_act[0][0]
			
			
			query = cr.execute("""
				SELECT * from sales_activity_plan where id < %s order by year_p DESC, week_no DESC, dow DESC, user_id, daylight, not_planned_actual limit 600
				""",(ids_sales_act,))
			values = cr.fetchall()
			
		
		return values
Пример #9
0
    def __new__(cls, cr, uid, context):
        assert context is not None
        args = (cr, uid, context)

        # if env already exists, return it
        env, envs = None, cls.envs
        for env in envs:
            if env.args == args:
                return env

        # otherwise create environment, and add it in the set
        self = object.__new__(cls)
        self.cr, self.uid, self.context = self.args = (cr, uid,
                                                       frozendict(context))
        self.registry = Registry(cr.dbname)
        self.cache = defaultdict(dict)  # {field: {id: value, ...}, ...}
        self._protected = defaultdict(frozenset)  # {field: ids, ...}
        self.dirty = defaultdict(set)  # {record: set(field_name), ...}
        self.all = envs
        envs.add(self)
        return self
Пример #10
0
	def GetSearch(self, req,params=None):
		condition= params['condition']
		
		registry = Registry(params['db'])
		
		if len(condition)>1:
			cond4query= " where "
			index=0
			for idx_c,key in enumerate(condition):
				# print key,"iniiii idx_c ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????"
				if len(condition[key]) >1 :
					
					for idx,qry in enumerate(condition[key]):
					
						try:
							if condition[key][idx+1]:
								if type(qry)==int:
									cond4query=cond4query+key+"="+str(qry)+" "+params['AndOr'][index]+" "
								else:
									cond4query=cond4query+key+"="+"'"+qry+"'"+" "+params['AndOr'][index]+" "
									index+=1
						except IndexError:
							print "sini"
							cond4query=cond4query+key+"="+"'"+qry+"'"
				else:

					try:
						
						print "ok"
						if type(condition[key][0])==int:
							cond4query=cond4query+key+"="+str(condition[key][0])+" "+params['AndOr'][index]+" " 
							index+=1
						else:
							cond4query=cond4query+key+"="+"'"+condition[key][0]+"'"+" "+params['AndOr'][index]+" " 
							index+=1
					except IndexError:
						print "sana"
						if type(condition[key][0])==int:
							cond4query=cond4query+key+"="+str(condition[key][0])
								
						else:
							cond4query=cond4query+key+"="+"'"+condition[key][0]+"'" 
						
						
						
		else:
			cond4query= " where "
			for key in condition:
				
				if len(condition[key]) >1 :
					
					for idx,qry in enumerate(condition[key]):
					
						try:
							if condition[key][idx+1]:
								if type(qry)==int:
									cond4query=cond4query+key+"="+str(qry)+" "+params['AndOr'][index]+" "
								else:
									cond4query=cond4query+key+"="+"'"+qry+"'"+" "+params['AndOr'][index]+" "
									index+=1
						except IndexError:
							if type(qry)==int:
									cond4query=cond4query+key+"="+str(qry)
							else:
								cond4query=cond4query+key+"="+"'"+qry+"'"
				else:
					print condition[key][0] ,"ggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg"
					if type(condition[key][0])==int:
						cond4query=cond4query+key+"="+str(condition[key][0])
					else:
						cond4query=cond4query+key+"="+"'"+condition[key][0]+"'"
			
			
							
				
		print cond4query,"ini cond4query "
	
		with registry.cursor() as cr:

			query = cr.execute("""
				SELECT """+params['fields']+""" from """+params['table']+""" """+cond4query+""" """+params['order']+""" limit %s offset %s
				""",(params['limit'],params['offset'],))
			values = cr.fetchall()
		return values