Пример #1
0
def _post_process(db,
                  uid,
                  passwd,
                  object,
                  method,
                  steps,
                  type='execute',
                  *args):
    security.check(db, uid, passwd)
    pool = pooler.get_pool(db)
    res = False
    if pool.get('game.scenario') and steps:
        cr = pooler.get_db_only(db).cursor()
        for step in steps:
            _execute(cr, uid, object, method, step, type, 'post', *args)
        ids = ','.join(map(lambda x: str(x['id']), steps))
        cr.execute(
            'update game_scenario_step set state=%s where id in (' + ids + ')',
            ('done', ))
        cr.execute(
            'update game_scenario_step set state=%s where id in (select next_step_id from next_step_rel where step_id in ('
            + ids + ')) and state=%s', ('running', 'draft'))
        cr.commit()
        cr.close()
    return res
Пример #2
0
    def report_get(self, db, uid, passwd, report_id):
        security.check(db, uid, passwd)

        cr = pooler.get_db(db).cursor()
        pool = pooler.get_pool(cr.dbname)
        report = pool.get('printjob.job').browse(cr, uid, report_id)

        if not report:
            cr.close()
            raise Exception, 'ReportNotFound'

        if report.create_uid.id != uid:
            cr.close()
            raise Exception, 'AccessDenied'

        res = {'state': report.state in ('ready', 'done')}
        if res['state']:
            res['result'] = report.result
            res['format'] = report.format
            if report.state == 'ready':
                pool.get('printjob.job').write(cr, uid, report_id, {
                    'state': 'done',
                })
                cr.commit()
        cr.close()
        return res
    def indexedModels(self, db, uid, passwd, context=None):
        security.check(db, uid, passwd)
        conn = sql_db.db_connect(db)
        cr = conn.cursor()

        result = self.exp_indexedModels(cr, uid, context)
        cr.close()
        return result
Пример #4
0
	def search(self, db, uid, passwd, model, filter, offset=0, limit=None, order=None, context=None, count=False, group=False):
		security.check(db, uid, passwd)
		conn = sql_db.db_connect(db)
		cr = conn.cursor()
		try:
			return self.exp_search(cr, uid, model, filter, offset, limit, order, context, count, group)
		finally:
			cr.close()
 def kill(self, dbname, uid, passwd, transaction_id):
     """Kill WSCursor by transaction_id.
     """
     security.check(dbname, uid, passwd)
     cursor = self.get_cursor(uid, transaction_id)
     self.log(netsvc.LOG_INFO, 'Killing WSCursor %s...' % transaction_id)
     cursor.rollback()
     cursor.close()
Пример #6
0
 def kill(self, dbname, uid, passwd, transaction_id):
     """Kill WSCursor by transaction_id.
     """
     security.check(dbname, uid, passwd)
     cursor = self.get_cursor(uid, transaction_id)
     self.log(netsvc.LOG_INFO, 'Killing WSCursor %s...' % transaction_id)
     cursor.rollback()
     cursor.close()
 def commit(self, dbname, uid, passwd, transaction_id):
     """Commit XML-RPC transaction.
     """
     security.check(dbname, uid, passwd)
     sync_cursor = self.get_cursor(uid, transaction_id)
     self.log(
         netsvc.LOG_INFO, 'Commiting transaction ID: %s TID: %s PID: %s' %
         (transaction_id, sync_cursor.psql_tid, sync_cursor.psql_pid))
     return sync_cursor.commit()
 def rollback(self, dbname, uid, passwd, transaction_id):
     """Rollbacks XML-RPC transaction.
     """
     security.check(dbname, uid, passwd)
     sync_cursor = self.get_cursor(uid, transaction_id)
     self.log(
         netsvc.LOG_INFO,
         'Rolling back transaction ID: %s TID: %s PID: %s' %
         (transaction_id, sync_cursor.psql_tid, sync_cursor.psql_pid))
     return sync_cursor.rollback()
Пример #9
0
 def rollback(self, dbname, uid, passwd, transaction_id):
     """Rollbacks XML-RPC transaction.
     """
     security.check(dbname, uid, passwd)
     sync_cursor = self.get_cursor(uid, transaction_id)
     self.log(netsvc.LOG_INFO,
         'Rolling back transaction ID: %s TID: %s PID: %s'
         % (transaction_id, sync_cursor.psql_tid, sync_cursor.psql_pid)
     )
     return sync_cursor.rollback()
Пример #10
0
 def commit(self, dbname, uid, passwd, transaction_id):
     """Commit XML-RPC transaction.
     """
     security.check(dbname, uid, passwd)
     sync_cursor = self.get_cursor(uid, transaction_id)
     self.log(netsvc.LOG_INFO,
         'Commiting transaction ID: %s TID: %s PID: %s'
         % (transaction_id, sync_cursor.psql_tid, sync_cursor.psql_pid)
     )
     return sync_cursor.commit()
Пример #11
0
def async_report_report(db, uid, passwd, object, ids, datas=None, context=None):
    from oorq.oorq import setup_redis_connection
    from oorq.tasks import report
    from rq import Queue
    from jinja2 import Template
    if not datas:
        datas = {}
    if not context:
        context={}
    security.check(db, uid, passwd)
    self = netsvc.SERVICES['report']

    self.id_protect.acquire()
    self.id += 1
    id = self.id
    self.id_protect.release()

    self._reports[id] = {
        'uid': uid,
        'result': False,
        'state': False,
        'exception': None
    }
    redis_conn = setup_redis_connection()
    q = Queue('report', default_timeout=86400,
              connection=redis_conn)
    # Pass OpenERP server config to the worker
    conf_attrs = dict(
        [(attr, value) for attr, value in config.options.items()]
    )
    job = q.enqueue(report, conf_attrs, db, uid, object, ids, datas, context)
    job.result_ttl = 86400
    job.save()
    # Check the configured timeout for the report. If the timeout is reached
    # then return a html report which redirects to the job info page.
    timeout = int(config.get('report_timeout', 5))
    protocol = 'http'
    if config['secure']:
        protocol = 'https'
    result = job.result
    while not result:
        time.sleep(0.1)
        result = job.result
        timeout -= 0.1
        if timeout <= 0:
            tmpl = Template(get_template('async_reports.html'))
            result = (tmpl.render(protocol=protocol,
                                  host=config['interface'],
                                  port=config['port'],
                                  job=job.id),
                      'html')
    self._reports[id]['result'] = result[0]
    self._reports[id]['format'] = result[1]
    self._reports[id]['state'] = True
    return id
Пример #12
0
 def close(self, dbname, uid, passwd, transaction_id):
     """Closes XML-RPC transaction.
     """
     security.check(dbname, uid, passwd)
     sync_cursor = self.get_cursor(uid, transaction_id)
     self.log(
         netsvc.LOG_INFO, 'Closing transaction ID: %s TID: %s PID: %s' %
         (transaction_id, sync_cursor.psql_tid, sync_cursor.psql_pid))
     res = sync_cursor.close()
     del self.cursors[uid][transaction_id]
     return res
Пример #13
0
 def close(self, dbname, uid, passwd, transaction_id):
     """Closes XML-RPC transaction.
     """
     security.check(dbname, uid, passwd)
     sync_cursor = self.get_cursor(uid, transaction_id)
     self.log(netsvc.LOG_INFO,
         'Closing transaction ID: %s TID: %s PID: %s'
         % (transaction_id, sync_cursor.psql_tid, sync_cursor.psql_pid)
     )
     res = sync_cursor.close()
     del self.cursors[uid][transaction_id]
     return res
Пример #14
0
def _post_process(db,uid,passwd,object,method,steps,type='execute',*args):
    security.check(db, uid, passwd)
    pool = pooler.get_pool(db)
    res=False
    if  pool.get('game.scenario') and steps:
        cr = pooler.get_db_only(db).cursor()
        for step in steps:
           _execute(cr, uid, object, method,step,type, 'post',*args)
        ids = ','.join(map(lambda x: str(x['id']), steps))
        cr.execute('update game_scenario_step set state=%s where id in ('+ids+')', ('done',))
        cr.execute('update game_scenario_step set state=%s where id in (select next_step_id from next_step_rel where step_id in ('+ids+')) and state=%s', ('running','draft'))
        cr.commit()
        cr.close()
    return res
Пример #15
0
 def begin(self, dbname, uid, passwd, transaction_id=None):
     """Starts a transaction for XML-RPC.
     """
     security.check(dbname, uid, passwd)
     self.cursors.setdefault(uid, {})
     user_cursors = self.cursors[uid]
     if not transaction_id:
         self.tid_protect.acquire()
         self.tid += 1
         transaction_id = self.tid
         self.tid_protect.release()
     if transaction_id not in user_cursors:
         transaction = self.get_transaction(dbname, uid, transaction_id)
         self.cursors[uid].update(transaction)
     return transaction_id
Пример #16
0
def _pre_process(db,uid,passwd,object,method,type='execute',*args):
    security.check(db, uid, passwd)
    pool = pooler.get_pool(db)
    steps=False
    if pool.get('game.scenario'):
        cr = pooler.get_db_only(db).cursor()
        cr.execute('select s.* from game_scenario_step s left join game_scenario g on (s.scenario_id=g.id) where g.state=%s and s.state=%s', ('running', 'running'))
        steps_orig = cr.dictfetchall()
        steps=[]
        for step in steps_orig:
            res = _execute(cr, uid, object, method, step, type,'pre',*args)
            if res:
                steps.append(step)
        cr.close()
    return steps
Пример #17
0
 def begin(self, dbname, uid, passwd, transaction_id=None):
     """Starts a transaction for XML-RPC.
     """
     security.check(dbname, uid, passwd)
     self.cursors.setdefault(uid, {})
     user_cursors = self.cursors[uid]
     if not transaction_id:
         self.tid_protect.acquire()
         self.tid += 1
         transaction_id = self.tid
         self.tid_protect.release()
     if transaction_id not in user_cursors:
         transaction = self.get_transaction(dbname, uid, transaction_id)
         self.cursors[uid].update(transaction)
     return transaction_id
Пример #18
0
 def begin(self, dbname, uid, passwd):
     """Starts a transaction for XML-RPC.
     """
     security.check(dbname, uid, passwd)
     self.cursors.setdefault(uid, {})
     database = pooler.get_db_and_pool(dbname)[0]
     cursor = database.cursor()
     sync_cursor = WSCursor(cursor)
     transaction_id = str(sync_cursor.psql_tid)
     self.log(
         netsvc.LOG_INFO,
         'Creating a new transaction ID: %s TID: %s PID: %s' % (
             transaction_id, transaction_id, sync_cursor.psql_pid
         )
     )
     self.cursors[uid].update({transaction_id: sync_cursor})
     return transaction_id
Пример #19
0
 def execute(self, dbname, uid, passwd, transaction_id, obj, method, *args,
             **kw):
     """Executes code with transaction_id.
     """
     security.check(dbname, uid, passwd)
     sync_cursor = self.get_cursor(uid, transaction_id)
     cursor = sync_cursor.cursor
     pool = pooler.get_db_and_pool(dbname)[1]
     try:
         self.log(netsvc.LOG_DEBUG,
             'Executing from transaction ID: %s TID: %s PID: %s'
             % (transaction_id, sync_cursor.psql_tid, sync_cursor.psql_pid)
         )
         res = pool.execute_cr(cursor, uid, obj, method, *args, **kw)
     except Exception, exc:
         self.rollback(dbname, uid, passwd, transaction_id)
         raise exc
Пример #20
0
 def begin(self, dbname, uid, passwd):
     """Starts a transaction for XML-RPC.
     """
     security.check(dbname, uid, passwd)
     self.cursors.setdefault(uid, {})
     database = pooler.get_db_and_pool(dbname)[0]
     cursor = database.cursor()
     sync_cursor = WSCursor(cursor)
     self.log(
         netsvc.LOG_INFO,
         'Creating a new transaction ID: %s TID: %s PID: %s' % (
             sync_cursor.psql_tid, sync_cursor.psql_tid,
             sync_cursor.psql_pid
         )
     )
     self.cursors[uid].update({sync_cursor.psql_tid: sync_cursor})
     return sync_cursor.psql_tid
Пример #21
0
 def execute(self, dbname, uid, passwd, transaction_id, obj, method, *args,
             **kw):
     """Executes code with transaction_id.
     """
     security.check(dbname, uid, passwd)
     sync_cursor = self.get_cursor(uid, transaction_id)
     cursor = sync_cursor.cursor
     pool = pooler.get_db_and_pool(dbname)[1]
     try:
         self.log(
             netsvc.LOG_DEBUG,
             'Executing from transaction ID: %s TID: %s PID: %s' %
             (transaction_id, sync_cursor.psql_tid, sync_cursor.psql_pid))
         res = pool.execute_cr(cursor, uid, obj, method, *args, **kw)
     except Exception, exc:
         self.rollback(dbname, uid, passwd, transaction_id)
         raise exc
Пример #22
0
def _pre_process(db, uid, passwd, object, method, type='execute', *args):
    security.check(db, uid, passwd)
    pool = pooler.get_pool(db)
    steps = False
    if pool.get('game.scenario'):
        cr = pooler.get_db_only(db).cursor()
        cr.execute(
            'select s.* from game_scenario_step s left join game_scenario g on (s.scenario_id=g.id) where g.state=%s and s.state=%s',
            ('running', 'running'))
        steps_orig = cr.dictfetchall()
        steps = []
        for step in steps_orig:
            res = _execute(cr, uid, object, method, step, type, 'pre', *args)
            if res:
                steps.append(step)
        cr.close()
    return steps
Пример #23
0
	def contacts(self, db, uid, passwd, model, ids, field, context={}):
		security.check(db, uid, passwd)
		conn = sql_db.db_connect(db)
		cr = conn.cursor()
		pool = pooler.get_pool(db)
		
		# Try to find if there's any relation with 'res.partner.address' (or 'res.partner')
		# in the given model:
		addressField = None
		partnerField = None
		columns = pool.get( model )._columns
		for key, value in columns.items():
			if value._type == 'many2one':
				if value._obj == 'res.partner.address':
					addressField = key
					break
				elif value._obj == 'res.parnter':
					partnerField = key
			elif value._type == 'one2many' and value._obj == 'res.partner.address':
					addressField = key
			elif value._type == 'many2many' and value._obj == 'res.partner.address':
					addressField = key

		# Now that we have which field relates to 'res.partner.address' (or 'res.partner')
		# browse all records and return a list of e-mails for each of them.
		res = {}
		for record in pool.get( model ).browse( cr, uid, ids, context=context ):
			emails = []
			if model == 'res.partner.address':
				if r.email:	
					emails = [r.email]
			elif addressField:
				value = record.__getattr__(addressField)
				if value and isinstance(value, osv.orm.browse_record):
					if value.email:
						emails = [value.email]
				elif value and isinstance(value, osv.orm.browse_record_list):
					emails = [x.email for x in record.address if x.email]
			elif partnerField:
				value = record.__getattr__(partnerField)
				if value:
					emails = [x.email for x in value.address if x.email]
			res[ str(record.id) ] = [ email.strip() for email in emails ]
		return res
Пример #24
0
	def setValue(self, db, uid, passwd, model, ids, fields, predicate, value, context={}):
		security.check(db, uid, passwd)
		conn = sql_db.db_connect(db)
		cr = conn.cursor()
		pool = pooler.get_pool(db)
		model = pool.get('ir.model').search(cr, uid, [('model','=',model)])[0]
		data = {
			'subject_model': model,
			'predicate': predicate,
			'object': value
		}
		for id in ids:
			data[ 'subject_id' ] = id
			data[ 'subject_field' ] = None
			pool.get('nan.semantic.triple').create(cr, uid, data )
			for field in fields:
				data[ 'subject_field' ] = field
				pool.get('nan.semantic.triple').create(cr, uid, data )
		return True
Пример #25
0
 def search(self,
            db,
            uid,
            passwd,
            text,
            limit,
            offset,
            model,
            context=None):
     security.check(db, uid, passwd)
     pool = pooler.get_pool(db)
     conn = sql_db.db_connect(db)
     cr = conn.cursor()
     try:
         return self.exp_search(cr, uid, text, limit, offset, model,
                                context)
     except Exception as e:
         print("EX: ", str(e))
     finally:
         cr.close()
Пример #26
0
	def value(self, db, uid, passwd, model, ids, field, predicate, context={}):
		security.check(db, uid, passwd)
		conn = sql_db.db_connect(db)
		cr = conn.cursor()
		pool = pooler.get_pool(db)
		modelId = pool.get('ir.model').search(cr, uid, [('model','=',model)])[0]
		query = [('subject_model','=',modelId),('subject_id','in',ids),('predicate','=',predicate)]
		if field:
			print("FIELD: ", field)
			fieldId = pool.get('ir.model.fields').search(cr, uid, [('model','=',modelId),('name','=',field)])[0]
			query.append( ('subject_field','=',fieldId) )
		tripleIds = pool.get('nan.semantic.triple').search(cr, uid, query)
		data = pool.get('nan.semantic.triple').read(cr, uid, tripleIds, ['subject_id','object'])
		d = {}
		for x in data:
			d[ str(x['subject_id']) ] = x['object']
		for x in ids:
			if str(x) not in d:
				d[ str(x) ] = -1
		return d
Пример #27
0
	def tags(self, db, uid, passwd, model, ids, field, context={}):
		security.check(db, uid, passwd)
		conn = sql_db.db_connect(db)
		cr = conn.cursor()
		pool = pooler.get_pool(db)

		mids = pool.get('ir.model').search(cr, uid, [('model','=',model)], context=context)
		modelName = pool.get('ir.model').read(cr, uid, mids, ['name'], context=context)[0]['name']

		commonTags = [ 'OpenERP', modelName ]

		res = {}
		for id in ids:
			ts = commonTags[:]
			if model == 'ir.attachment':
				modelName = pool.get('ir.attachment').read(cr, uid, id, ['res_model'], context=context)['res_model']
				mids = pool.get('ir.model').search(cr, uid, [('model','=',modelName)], context=context)
				modelName = pool.get('ir.model').read(cr, uid, mids, ['name'], context=context)[0]['name']
				ts.append( modelName )
			res[str(id)] = ts
		return res
Пример #28
0
	def description(self, db, uid, passwd, model, ids, field, context={}):
		security.check(db, uid, passwd)
		conn = sql_db.db_connect(db)
		cr = conn.cursor()
		pool = pooler.get_pool(db)
		
		descriptionField = None
		columns = pool.get( model )._columns
		possibleFields = ['description', 'notes', 'note', 'comment', 'comments']
		for f in possibleFields:
			if f in columns:
				descriptionField = f
		res = {}
		data = pool.get( model ).read(cr, uid, ids, ['id', descriptionField], context=context)
		for record in data:
			if descriptionField and record[descriptionField]:
				value = record[descriptionField]
			else:
				value = ''
			res[ str(record['id']) ] = value
		return res
    def report_get(self, db, uid, passwd, report_id):
        security.check(db, uid, passwd)

        cr = pooler.get_db(db).cursor()
        pool = pooler.get_pool(cr.dbname)
        report = pool.get('printjob.job').browse(cr, uid, report_id)

        if not report:
            cr.close()
            raise Exception, 'ReportNotFound'

        if report.create_uid.id != uid:
            cr.close()
            raise Exception, 'AccessDenied'

        if report.state == 'error':
            self.exceptions_protect.acquire()
            if report_id in self.exceptions:
                exception = self.exceptions.get(report_id)
                del self.exceptions[report_id]
            else:
                exception = False
            self.exceptions_protect.release()
            if exception:
                raise exception
            else:
                raise Exception, 'ExceptionNotFound'


        res = {'state': report.state in ('ready','done')}
        if res['state']:
            res['result'] = report.result
            res['format'] = report.format
            if report.state == 'ready':
                pool.get('printjob.job').write(cr,uid,report_id,{
                    'state': 'done',
                })
                cr.commit()
        cr.close()
        return res
Пример #30
0
 def execute(self, dbname, uid, passwd, transaction_id, obj, method, *args,
             **kw):
     """Executes code with transaction_id.
     """
     security.check(dbname, uid, passwd)
     sync_cursor = self.get_cursor(uid, transaction_id)
     cursor = sync_cursor.cursor
     pool = pooler.get_db_and_pool(dbname)[1]
     try:
         self.log(netsvc.LOG_DEBUG,
             'Executing from transaction ID: %s TID: %s PID: %s'
             % (transaction_id, sync_cursor.psql_tid, sync_cursor.psql_pid)
         )
         res = pool.execute_cr(cursor, uid, obj, method, *args, **kw)
     except Exception as exc:
         #self.rollback(dbname, uid, passwd, transaction_id)
         import traceback
         self.log(netsvc.LOG_ERROR,
             'Error within a transaction:\n'+
             traceback.format_exc())
         raise
     return res
Пример #31
0
 def execute(self, dbname, uid, passwd, transaction_id, obj, method, *args,
             **kw):
     """Executes code with transaction_id.
     """
     transaction_id = str(transaction_id)
     security.check(dbname, uid, passwd)
     sync_cursor = self.get_cursor(uid, transaction_id)
     cursor = sync_cursor.cursor
     pool = pooler.get_db_and_pool(dbname)[1]
     try:
         self.log(netsvc.LOG_DEBUG,
             'Executing from transaction ID: %s TID: %s PID: %s'
             % (transaction_id, sync_cursor.psql_tid, sync_cursor.psql_pid)
         )
         res = pool.execute_cr(cursor, uid, obj, method, *args, **kw)
     except Exception as exc:
         #self.rollback(dbname, uid, passwd, transaction_id)
         import traceback
         self.log(netsvc.LOG_ERROR,
             'Error within a transaction:\n'+
             traceback.format_exc())
         raise
     return res
Пример #32
0
    def report_get(self, db, uid, passwd, report_id):
        security.check(db, uid, passwd)

        cr = pooler.get_db(db).cursor()
        pool = pooler.get_pool(cr.dbname)
        report = pool.get("printjob.job").browse(cr, uid, report_id)

        if not report:
            cr.close()
            raise Exception, "ReportNotFound"

        if report.create_uid.id != uid:
            cr.close()
            raise Exception, "AccessDenied"

        res = {"state": report.state in ("ready", "done")}
        if res["state"]:
            res["result"] = report.result
            res["format"] = report.format
            if report.state == "ready":
                pool.get("printjob.job").write(cr, uid, report_id, {"state": "done"})
                cr.commit()
        cr.close()
        return res
Пример #33
0
    def report(self, db, uid, passwd, object, ids, datas=None, context=None):

        logger = netsvc.Logger()
        if not datas:
            datas = {}
        if not context:
            context = {}

        security.check(db, uid, passwd)
        logger.notifyChannel("report", netsvc.LOG_INFO, "request report '%s'" % str(object))
        # Reprint a printed job
        if object == "printjob.reprint":
            return ids[0]

        cr = pooler.get_db(db).cursor()
        pool = pooler.get_pool(cr.dbname)

        # First of all load report defaults: name, action and printer
        report_obj = pool.get("ir.actions.report.xml")
        report = report_obj.search(cr, uid, [("report_name", "=", object)])
        if report:
            report = report_obj.browse(cr, uid, report[0])
            name = report.name
            data = report.behaviour()[report.id]
            action = data["action"]
            printer = data["printer"]
        else:
            name = object
            action = "spool"
            printer = False

        # Detect if defaults are being overriden for this report call
        batch = False
        if "print_batch" in context:
            batch = context["print_batch"]
        if "print_batch" in datas:
            batch = datas["print_batch"]
        if "form" in datas:
            if "print_batch" in datas["form"]:
                batch = datas["form"]["print_batch"]

        if batch:
            action = "server"
            # Search default printer
            printer_id = False
            if "printer" in context:
                printer_id = context["printer"]
            if "printer" in datas:
                printer_id = datas["printer"]
            if "form" in datas:
                if "printer" in datas["form"]:
                    printer_id = datas["form"]["printer"]
            printer = False
            if printer_id:
                printer_ids = pool.get("printjob.printer").read(cr, uid, [printer_id], ["system_name"])
                if printer_ids:
                    printer = printer_ids[0]["system_name"]
            else:
                printer_id = pool.get("printjob.printer").get_default(cr, uid, context)
                if printer_id:
                    printer = pool.get("printjob.printer").browse(cr, uid, printer_id, context).system_name

        #
        # Create new printjob.job
        #
        job_id = pool.get("printjob.job").create(
            cr,
            uid,
            {
                "name": name,
                "report": object,
                "ids": str(ids),
                "data": str(datas),
                "context": str(context),
                "result": False,
                "action": action,
            },
            context,
        )
        cr.commit()
        #        cr.close()

        def print_thread(id, uid, ids, datas, context, printer):
            logger.notifyChannel("report", netsvc.LOG_DEBUG, "Printing thread started")

            cr = pooler.get_db(db).cursor()
            pool = pooler.get_pool(cr.dbname)

            service = netsvc.LocalService("report." + object)
            (result, format) = service.create(cr, uid, ids, datas, context)

            pool.get("printjob.job").write(
                cr, uid, id, {"result": base64.encodestring(result), "format": format, "state": "ready"}, context
            )

            if printer:
                pool.get("printjob.job").print_direct(cr, uid, id, printer, context)

            cr.commit()
            cr.close()
            return True

        if action != "server":
            printer = False
        thread.start_new_thread(print_thread, (job_id, uid, ids, datas, context, printer))

        if action == "spool":
            raise except_print(
                _("Report generated in background"),
                _("This report is generated in background. In a few minutes look at your print jobs."),
            )
        elif action == "server":
            raise except_print(
                _("Report sent to printer"), _("This report has been sent directly to printer: %s") % printer
            )
        return job_id
Пример #34
0
    def report(self, db, uid, passwd, object, ids, datas=None, context=None):

        logger = netsvc.Logger()
        if not datas:
            datas = {}
        if not context:
            context = {}

        security.check(db, uid, passwd)
        logger.notifyChannel("report", netsvc.LOG_INFO,
                             "request report '%s'" % str(object))
        # Reprint a printed job
        if object == 'printjob.reprint':
            return ids[0]

        cr = pooler.get_db(db).cursor()
        pool = pooler.get_pool(cr.dbname)

        # First of all load report defaults: name, action and printer
        report_obj = pool.get('ir.actions.report.xml')
        report = report_obj.search(cr, uid, [('report_name', '=', object)])
        if report:
            report = report_obj.browse(cr, uid, report[0])
            name = report.name
            data = report.behaviour()[report.id]
            action = data['action']
            printer = data['printer']
        else:
            name = object
            action = 'spool'
            printer = False

        # Detect if defaults are being overriden for this report call
        batch = False
        if 'print_batch' in context:
            batch = context['print_batch']
        if 'print_batch' in datas:
            batch = datas['print_batch']
        if 'form' in datas:
            if 'print_batch' in datas['form']:
                batch = datas['form']['print_batch']

        if batch:
            action = 'server'
            # Search default printer
            printer_id = False
            if 'printer' in context:
                printer_id = context['printer']
            if 'printer' in datas:
                printer_id = datas['printer']
            if 'form' in datas:
                if 'printer' in datas['form']:
                    printer_id = datas['form']['printer']
            printer = False
            if printer_id:
                printer_ids = pool.get('printjob.printer').read(
                    cr, uid, [printer_id], ['system_name'])
                if printer_ids:
                    printer = printer_ids[0]['system_name']
            else:
                printer_id = pool.get('printjob.printer').get_default(
                    cr, uid, context)
                if printer_id:
                    printer = pool.get('printjob.printer').browse(
                        cr, uid, printer_id, context).system_name

        #
        # Create new printjob.job
        #
        job_id = pool.get("printjob.job").create(
            cr, uid, {
                'name': name,
                'report': object,
                'ids': str(ids),
                'data': str(datas),
                'context': str(context),
                'result': False,
                'action': action,
            }, context)
        cr.commit()

        #        cr.close()

        def print_thread(id, uid, ids, datas, context, printer):
            logger.notifyChannel("report", netsvc.LOG_DEBUG,
                                 "Printing thread started")

            cr = pooler.get_db(db).cursor()
            pool = pooler.get_pool(cr.dbname)

            service = netsvc.LocalService('report.' + object)
            (result, format) = service.create(cr, uid, ids, datas, context)

            pool.get("printjob.job").write(
                cr, uid, id, {
                    'result': base64.encodestring(result),
                    'format': format,
                    'state': 'ready',
                }, context)

            if printer:
                pool.get('printjob.job').print_direct(cr, uid, id, printer,
                                                      context)

            cr.commit()
            cr.close()
            return True

        if action != 'server':
            printer = False
        thread.start_new_thread(print_thread,
                                (job_id, uid, ids, datas, context, printer))

        if action == 'spool':
            raise except_print(
                _('Report generated in background'),
                _('This report is generated in background. In a few minutes look at your print jobs.'
                  ))
        elif action == 'server':
            raise except_print(
                _('Report sent to printer'),
                _('This report has been sent directly to printer: %s') %
                printer)
        return job_id
    def report(self, db, uid, passwd, object, ids, datas=None, context=None):

        logger = netsvc.Logger()
        if not datas:
            datas={}
        if not context:
            context={}

        security.check(db, uid, passwd)
        logger.notifyChannel("report", netsvc.LOG_INFO,"request report '%s'" % str(object))
        # Reprint a printed job
        if object == 'printjob.reprint':
            return ids[0]

        cr = pooler.get_db(db).cursor()
        pool = pooler.get_pool(cr.dbname)

        # First of all load report defaults: name, action and printer
        report_obj = pool.get('ir.actions.report.xml')
        report = report_obj.search(cr,uid,[('report_name','=',object)])
        if report:
            report = report_obj.browse(cr,uid,report[0])
            name = report.name
            data = report.behaviour()[report.id]
            action = data['action']
            printer = data['printer']
        else:
            name = object
            action = 'client'
            printer = False

        # Detect if defaults are being overriden for this report call
        batch = False
        if 'print_batch' in context:
            batch = context['print_batch']
        if 'print_batch' in datas:
            batch = datas['print_batch']
        if 'form' in datas:
            if 'print_batch' in datas['form']:
                batch = datas['form']['print_batch']

        if batch:
            action = 'server'
            # Search default printer
            printer_id = False
            if 'printer' in context:
                printer_id = context['printer']
            if 'printer' in datas:
                printer_id = datas['printer']
            if 'form' in datas:
                if 'printer' in datas['form']:
                    printer_id = datas['form']['printer']
            printer = False
            if printer_id:
                printer_ids = pool.get('printjob.printer').read(cr, uid, [printer_id],['system_name'])
                if printer_ids:
                    printer = printer_ids[0]['system_name']
            else:
                printer_id = pool.get('printjob.printer').get_default(cr,uid,context)
                if printer_id:
                    printer = pool.get('printjob.printer').browse(cr,uid,printer_id,context).system_name

        #
        # Create new printjob.job
        #
        job_id = pool.get("printjob.job").create(cr,uid,{
            'name': name,
            'report': object,
            'ids': str(ids),
            'data': str(datas),
            'context': str(context),
            'result': False,
            'action': action,
        }, context)
        cr.commit()

        def print_thread(id, uid, ids, datas, context, printer):
            logger = netsvc.Logger()
            logger.notifyChannel("report", netsvc.LOG_DEBUG, "Printing thread started")

            cr = pooler.get_db(db).cursor()
            pool = pooler.get_pool(cr.dbname)

            exception_string = False
            exception_backtrace = False
            state = 'ready'
            result = False
            format = False

            service = netsvc.LocalService('report.'+object)
            try:
                (result, format) = service.create(cr, uid, ids, datas, context)
                result = base64.encodestring(result)
            except Exception, exception:
                import traceback
                import sys
                tb = sys.exc_info()
                tb_s = "".join(traceback.format_exception(*tb))
                logger = netsvc.Logger()
                logger.notifyChannel('web-services', netsvc.LOG_ERROR, 'Exception: %s\n%s' % (str(exception), tb_s))

                exception = ExceptionWithTraceback(tools.exception_to_unicode(exception), tb)
                self.exceptions_protect.acquire()
                self.exceptions[id] = exception
                self.exceptions_protect.release()

                state = 'error'

            pool.get("printjob.job").write( cr, uid, id, {
                'result': result,
                'format': format,
                'state': state,
                'exception_string': exception_string,
                'exception_backtrace': exception_backtrace,
            }, context)

            if printer:
                pool.get('printjob.job').print_direct(cr, uid, id, printer.system_name, context)

            cr.commit()
            cr.close()
            return True