def _send_asset_to_sii(self): for asset in self.filtered(lambda a: a.state in ['validated']): company = asset.company_id wsdl = self.env['ir.config_parameter'].get_param( 'l10n_es_aeat_sii.wsdl_pi', False) port_name = 'SuministroBienesInversion' if company.sii_test: port_name += 'Pruebas' client = self._connect_sii(wsdl) serv = client.bind('siiService', port_name) if asset.sii_state == 'not_sent': tipo_comunicacion = 'A0' else: tipo_comunicacion = 'A1' header = asset._get_sii_header(tipo_comunicacion) asset_vals = { 'sii_header_sent': json.dumps(header, indent=4), } try: asset_dict = asset._get_sii_asset_dict() asset_vals['sii_content_sent'] = json.dumps(asset_dict, indent=4) res = serv.SuministroLRBienesInversion(header, asset_dict) res_line = res['RespuestaLinea'][0] if res['EstadoEnvio'] == 'Correcto': asset_vals.update({ 'sii_state': 'sent', 'sii_csv': res['CSV'], 'sii_send_failed': False, }) elif res['EstadoEnvio'] == 'ParcialmenteCorrecto' and \ res_line['EstadoRegistro'] == 'AceptadoConErrores': asset_vals.update({ 'sii_state': 'sent_w_errors', 'sii_csv': res['CSV'], 'sii_send_failed': True, }) else: asset_vals['sii_send_failed'] = True asset_vals['sii_return'] = res send_error = False if res_line['CodigoErrorRegistro']: send_error = u"{} | {}".format( unicode(res_line['CodigoErrorRegistro']), unicode(res_line['DescripcionErrorRegistro'])[:60]) asset_vals['sii_send_error'] = send_error asset.write(asset_vals) except Exception as fault: new_cr = RegistryManager.get(self.env.cr.dbname).cursor() env = api.Environment(new_cr, self.env.uid, self.env.context) asset = env['account.investment.assets'].browse(self.id) asset_vals.update({ 'sii_send_failed': True, 'sii_send_error': fault, 'sii_return': fault, }) asset.write(asset_vals) new_cr.commit() new_cr.close() raise
def import_(ctx, language, db_name, overwrite): context = { 'overwrite': overwrite } from odoo.modules.registry import RegistryManager from odoo.api import Environment from odoo.tools import trans_load with tempfile.NamedTemporaryFile(suffix='.po', delete=False) as t: registry = RegistryManager.get(db_name) # Read from stdin while True: chunk = sys.stdin.read(CHUNK_SIZE) if not chunk: break t.write(chunk) t.close() with Environment.manage(): with registry.cursor() as cr: trans_load(cr, t.name, language, context=context) os.unlink(t.name)
def __init__(self, dbname, model_name, res_id, uid=0): assert isinstance(uid, (int, long)), 'uid should be an integer' self._logger = logging.getLogger('smile_log') db = RegistryManager.get(dbname)._db pid = 0 try: cr = db.cursor() cr.autocommit(True) cr.execute( "select relname from pg_class where relname='smile_log_seq'") if not cr.rowcount: cr.execute("create sequence smile_log_seq") cr.execute("select nextval('smile_log_seq')") res = cr.fetchone() pid = res and res[0] or 0 finally: cr.close() self._logger_start = datetime.datetime.now() self._logger_args = { 'dbname': dbname, 'model_name': model_name, 'res_id': res_id, 'uid': uid, 'pid': pid }
def import_data(self, f): with_error = False with api.Environment.manage(): with RegistryManager.get(self.env.cr.dbname).cursor() as new_cr: new_env = api.Environment(new_cr, self.env.uid, self.env.context) #Se hace browse con un env diferente para guardar cambios doc_ = self.with_env(new_env).browse(self.id) try: invoice_vals = {} invoice_line_vals = {} partner = False for line in f.readlines(): line_type = line[14] company_code = line[:6] company = self.sudo().env["res.company"].\ search([('a3_company_code', '=', company_code)]) if line_type == "1": # factura de venta invoice_vals = doc_.import_invoice(line, company) elif line_type == "2": # factura rectificativa venta invoice_vals = doc_.\ import_invoice(line, company, True) elif line_type == "9": # detalle de factura invoice_line_vals = doc_.\ import_invoice_line(line, company) elif line_type == "C": partner = doc_.import_partner(line, company) else: raise exceptions.\ UserError(_("Line type %s has not a parser") % line_type) if partner: invoice_vals['partner_id'] = partner.id invoice_vals['account_id'] = \ partner.property_account_receivable_id.id invoice_vals['fiscal_position_id'] = \ partner.property_account_position_id.id invoice_vals['payment_mode_id'] = \ partner.customer_payment_mode_id.id invoice_vals['user_id'] = partner.user_id.id invoice = self.with_env(new_env).\ env["account.invoice"].create(invoice_vals) invoice_line_vals['invoice_id'] = invoice.id self.with_env(new_env).\ env["account.invoice.line"].\ create(invoice_line_vals) invoice.compute_taxes() invoice.action_invoice_open() invoice_vals = {} invoice_line_vals = {} partner = False except Exception as e: self.errors = '\n%s' % str(e) self.state = 'error' new_env.cr.rollback() with_error = True if not with_error: self.state = 'imported' new_env.cr.commit()
def _get_cursor(self, dbname): cr = self._dbname_to_cr.get(dbname) if not cr or (cr and cr.closed): db = RegistryManager.get(dbname)._db cr = db.cursor() cr.autocommit(True) self._dbname_to_cr[dbname] = cr return cr
def connect(dbname='trunk', uid=1, context=None): from odoo.modules.registry import RegistryManager from odoo.api import Environment r = RegistryManager.get(dbname) cr = r.cursor() Environment.reset() env = Environment(cr, uid, context or {}) print('Connected to %s with user %s %s' % (dbname, env.uid, env.user.name)) return env
def setUp(self): super(TestAdvisoryLock, self).setUp() self.registry2 = RegistryManager.get(common.get_db_name()) self.cr2 = self.registry2.cursor() self.env2 = api.Environment(self.cr2, self.env.uid, {}) @self.addCleanup def reset_cr2(): # rollback and close the cursor, and reset the environments self.env2.reset() self.cr2.rollback() self.cr2.close()
def newdbuuid(ctx, db_name): config = ( ctx.obj['config'] ) from odoo.modules.registry import RegistryManager from odooku.api import environment registry = RegistryManager.get(db_name) with registry.cursor() as cr: with environment(cr) as env: env['ir.config_parameter'].init(force=True)
def authenticate(token): try: a = 4 - len(token) % 4 if a != 0: token += '==' if a == 2 else '=' SERVER,db,login,uid,ts = base64.urlsafe_b64decode(str(token)).split(',') if int(ts) + 60*60*24*7*10 < time.time(): return False registry = RegistryManager.get(db) cr = registry.cursor() env = api.Environment(cr, int(uid), {}) except Exception,e: return str(e)
def import_(ctx, db_name, fake, strict, config_file): config = (ctx.obj['config']) from odoo.modules.registry import RegistryManager registry = RegistryManager.get(db_name) from odooku_data.importer import Importer from odooku_data.config import DataConfig importer = Importer( registry, config=config_file and DataConfig.from_file(config_file) or DataConfig.defaults(), strict=strict, ) importer.import_(sys.stdin, fake=fake)
def shell(ctx, input_file, db_name): from odoo.modules.registry import RegistryManager from odooku.api import environment registry = RegistryManager.get(db_name) with registry.cursor() as cr: with environment(cr) as env: context = {'env': env, 'self': env.user} args = [] if input_file is not None: args = [input_file] bpython.embed(context, args=args, banner='Odooku shell')
def db_list(self): db_list = http.db_list() or [] db_list_by_mobile = [] for db in db_list: db_manager = RegistryManager.get(db) with closing(db_manager.cursor()) as cr: cr.execute(''' SELECT id FROM ir_module_module WHERE state = 'installed' AND name = 'mobile' ''') if cr.fetchall(): db_list_by_mobile.append(db) return db_list_by_mobile
def authenticate(token): try: a = 4 - len(token) % 4 if a != 0: token += '==' if a == 2 else '=' SERVER, db, login, uid, ts = base64.urlsafe_b64decode( str(token)).split(',') if int(ts) + 60 * 60 * 24 * 7 * 10 < time.time(): return False registry = RegistryManager.get(db) cr = registry.cursor() env = api.Environment(cr, int(uid), {}) except Exception, e: return str(e)
def export(ctx, db_name, strict, link, config_file=None): config = (ctx.obj['config']) from odoo.modules.registry import RegistryManager registry = RegistryManager.get(db_name) from odooku_data.exporter import factory from odooku_data.config import DataConfig exporter = factory()( registry, config=config_file and DataConfig.from_file(config_file) or DataConfig.defaults(), link=link, strict=strict, ) exporter.export(sys.stdout)
def signin(self, **kw): kw = simplejson.loads(simplejson.dumps(kw).replace('+', '')) state = simplejson.loads(kw['state']) dbname = state['d'] provider = state['p'] context = state.get('c', {}) registry = RegistryManager.get(dbname) with registry.cursor() as cr: try: env = api.Environment(cr, SUPERUSER_ID, context) credentials = env['res.users'].sudo().auth_oauth(provider, kw) print credentials # u = registry.get('res.users') # credentials = u.auth_oauth(provider, kw) cr.commit() action = state.get('a') menu = state.get('m') redirect = werkzeug.url_unquote_plus( state['r']) if state.get('r') else False url = '/web' if redirect: url = redirect elif action: url = '/web#action=%s' % action elif menu: url = '/web#menu_id=%s' % menu return login_and_redirect(*credentials, redirect_url=url) except AttributeError: # auth_signup is not installed _logger.error( "auth_signup not installed on database %s: oauth sign up cancelled." % (dbname, )) url = "/web/login?oauth_error=1" except odoo.exceptions.AccessDenied: # oauth credentials not valid, user could be on a temporary session _logger.info( 'OAuth2: access denied, redirect to main page in case a valid session exists, without setting cookies' ) url = "/web/login?oauth_error=3" redirect = werkzeug.utils.redirect(url, 303) redirect.autocorrect_location_header = False return redirect except Exception, e: # signup error _logger.exception("OAuth2: %s" % str(e)) url = "/web/login?oauth_error=2"
def setUp(self): super(TestConcurrentSync, self).setUp() self.registry2 = RegistryManager.get(common.get_db_name()) self.cr2 = self.registry2.cursor() self.env2 = api.Environment(self.cr2, self.env.uid, {}) @self.addCleanup def reset_cr2(): # rollback and close the cursor, and reset the environments self.env2.reset() self.cr2.rollback() self.cr2.close() backend2 = mock.MagicMock(name='Backend Record') backend2._name = 'magento.backend' backend2.id = self.backend.id backend2.env = self.env2 self.backend2 = backend2
def login(self, db_choose=''): db_list = http.db_list() or [] db_list_by_mobile = [] for db in db_list: db_manager = RegistryManager.get(db) with closing(db_manager.cursor()) as cr: cr.execute(''' SELECT id FROM ir_module_module WHERE state = 'installed' AND name = 'mobile' ''') if cr.fetchall(): db_list_by_mobile.append(db) template = env.get_template('login.html') return template.render({ 'db_list': db_list_by_mobile, 'db_choose': db_choose })
def export(ctx, language, db_name, module): modules = module or ['all'] from odoo.modules.registry import RegistryManager from odoo.api import Environment from odoo.tools import trans_export with tempfile.TemporaryFile() as t: registry = RegistryManager.get(db_name) with Environment.manage(): with registry.cursor() as cr: trans_export(language, modules, t, 'po', cr) t.seek(0) # Pipe to stdout while True: chunk = t.read(CHUNK_SIZE) if not chunk: break sys.stdout.write(chunk)
def update(ctx, db_name, module, language, overwrite): context = { 'overwrite': overwrite } from odoo.modules.registry import RegistryManager from odooku.api import environment domain = [('state', '=', 'installed')] if module: domain = [('name', 'in', module)] for db in db_name: registry = RegistryManager.get(db) with registry.cursor() as cr: with environment(cr) as env: mods = env['ir.module.module'].search(domain) mods.with_context(overwrite=overwrite).update_translations(language)
def _send_simplified_to_sii(self): for order in self.filtered(lambda i: i.state in ['done', 'paid']): wsdl = self.env['ir.config_parameter'].get_param( 'l10n_es_aeat_sii.wsdl_out', False) port_name = 'SuministroFactEmitidas' if not order.sii_sent: tipo_comunicacion = 'A0' else: tipo_comunicacion = 'A1' header = order._get_header(tipo_comunicacion) try: orders = order._get_simplified() except Exception as fault: new_cr = RegistryManager.get(self.env.cr.dbname).cursor() env = api.Environment(new_cr, self.env.uid, self.env.context) self.with_env(env).sii_send_error = fault new_cr.commit() new_cr.close() raise try: serv = order._connect_wsdl(wsdl, port_name) res = serv.SuministroLRFacturasEmitidas( header, orders) if res['EstadoEnvio'] in ['Correcto', 'ParcialmenteCorrecto']: self.sii_sent = True self.sii_csv = res['CSV'] else: self.sii_sent = False self.env['aeat.sii.result'].create_result( order, res, 'normal', False, 'pos.order') send_error = False res_line = res['RespuestaLinea'][0] if res_line['CodigoErrorRegistro']: send_error = u"{} | {}".format( unicode(res_line['CodigoErrorRegistro']), unicode(res_line['DescripcionErrorRegistro'])[:60]) self.sii_send_error = send_error except Exception as fault: self.env['aeat.sii.result'].create_result( order, False, 'normal', fault, 'pos.order') self.sii_send_error = fault
def _cancel_asset_to_sii(self): for asset in self.filtered(lambda a: a.state in ['cancel']): company = asset.company_id wsdl = self.env['ir.config_parameter'].get_param( 'l10n_es_aeat_sii.wsdl_pi', False) port_name = 'SuministroBienesInversion' if company.sii_test: port_name += 'Pruebas' client = self._connect_sii(wsdl) serv = client.bind('siiService', port_name) header = asset._get_sii_header(cancellation=True) try: asset_dict = asset._get_sii_asset_dict(cancel=True) res = serv.AnulacionLRBienesInversion(header, asset_dict) if res['EstadoEnvio'] == 'Correcto': asset.sii_state = 'cancelled' asset.sii_csv = res['CSV'] asset.sii_send_failed = False else: asset.sii_send_failed = True asset.sii_return = res send_error = False res_line = res['RespuestaLinea'][0] if res_line['CodigoErrorRegistro']: send_error = u"{} | {}".format( unicode(res_line['CodigoErrorRegistro']), unicode(res_line['DescripcionErrorRegistro'])[:60]) asset.sii_send_error = send_error except Exception as fault: new_cr = RegistryManager.get(self.env.cr.dbname).cursor() env = api.Environment(new_cr, self.env.uid, self.env.context) asset = env['account.investment.assets'].browse(self.id) asset.sii_send_error = fault asset.sii_send_failed = True asset.sii_return = fault new_cr.commit() new_cr.close() raise
def authenticate(token): try: # 补齐位数 token += '==' if 4 - len(token) % 4 == 2 else '=' token_str = base64.urlsafe_b64decode(str(token)) ts, b64_ts, db, uid = token_str.split(',') #有效时间验证 if float(ts) < time.time(): return EXPIRED # 摘要对比 validate_ts = hmac.new(SECRET, ts, hashlib.sha1).hexdigest() if b64_ts != validate_ts: return UNVALIDATE registry = RegistryManager.get(db) cr = registry.cursor() env = api.Environment(cr, int(uid), {}) except Exception, e: return UNVALIDATE
def _cancel_transaction_to_sii(self): for transaction in self.filtered(lambda t: t.state in ['cancel']): company = transaction.company_id wsdl = self.env['ir.config_parameter'].get_param('l10n_es_aeat_sii.wsdl_ic', False) port_name = 'SuministroOpIntracomunitarias' if company.sii_test: port_name += 'Pruebas' client = self._connect_sii(wsdl) serv = client.bind('siiService', port_name) header = transaction._get_sii_header(cancellation=True) try: transaction_dict = transaction._get_sii_transaction_dict(cancel=True) res = serv.AnulacionLRDetOperacionIntracomunitaria(header, transaction_dict) if res['EstadoEnvio'] == 'Correcto': transaction.sii_state = 'cancelled' transaction.sii_csv = res['CSV'] transaction.sii_send_failed = False else: transaction.sii_send_failed = True transaction.sii_return = res send_error = False res_line = res['RespuestaLinea'][0] if res_line['CodigoErrorRegistro']: send_error = u"{} | {}".format( unicode(res_line['CodigoErrorRegistro']), unicode(res_line['DescripcionErrorRegistro'])[:60] ) transaction.sii_send_error = send_error except Exception as fault: new_cr = RegistryManager.get(self.env.cr.dbname).cursor() env = api.Environment(new_cr, self.env.uid, self.env.context) transaction = env['account.specific.intracommunity.transactions'].browse(self.id) transaction.sii_send_error = fault transaction.sii_send_failed = True transaction.sii_return = fault new_cr.commit() new_cr.close() raise
def migrate(cr, version): registry = RegistryManager.get(cr.dbname) from odoo.addons.account.models.chart_template import migrate_set_tags_and_taxes_updatable migrate_set_tags_and_taxes_updatable(cr, registry, 'l10n_de_skr04')
def migrate(cr, version): registry = RegistryManager.get(cr.dbname) from odoo.addons.account.models.chart_template import migrate_set_tags_and_taxes_updatable migrate_set_tags_and_taxes_updatable(cr, registry, 'l10n_cl')
def connect(uid=1, context=None): reg = RegistryManager.get(config.get('db_name')) cr = reg.cursor() Environment.reset() env = Environment(cr, uid, context or {}) return env
def migrate(cr, version): registry = RegistryManager.get(cr.dbname) from odoo.addons.account.models.chart_template import migrate_tags_on_taxes migrate_tags_on_taxes(cr, registry)
def migrate(cr, version): registry = RegistryManager.get(cr.dbname) from odoo.addons.account.models.chart_template import migrate_tags_on_taxes migrate_tags_on_taxes(cr, registry)