def module_import(self, file): if (self.datas_fname.endswith("tar.gz")): path_scripts = os.path.dirname(os.path.abspath("/scripts/restart_odoo.sh")) if path_scripts == '/scripts': context = dict(self._context or {}) split_name_module = self.datas_fname.split(".tar.gz") path_act_module = module.get_module_path('module_import') path_complete = path_act_module+'/modules/' # print "######## SELF SPLIT NAME MODULE >>>>>> ", split_name_module module_name, des= split_name_module path_module = module.get_module_path(module_name) if path_module == False: raise ValidationError(_('El Modulo Que Desea Actualizar No Existe')) else: split_path_module, com = path_module.split(module_name) path_module = split_path_module+module_name compress_file = open(path_complete+self.datas_fname, "wb") compress_file.write(base64.b64decode(self.file)) arch_module = path_complete+self.datas_fname os.system('tar -xzvf %s -C %s' % (arch_module,path_complete)) descom_module = path_complete+module_name cont_listdir = len(listdir(descom_module)) if cont_listdir == 1: raise ValidationError(_('Error Al Descomprimir El Modulo')) os.system('rm -R %s && %s' %(arch_module,descom_module)) else: os.system('rm -R %s' %(path_module)) os.system('mv %s %s' %(descom_module,split_path_module)) os.system('rm -R %s && %s' %(arch_module,descom_module)) os.system('screen /scripts/restart_odoo.sh') else: raise ValidationError(_('No Se Puede Reiniciar'))
def delivery_and_returns(pool, cr, uid): fn = 'delivery_and_returns.png' years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month weeks = mdates.WeekdayLocator() days = mdates.DayLocator() yearsFmt = mdates.DateFormatter('%W') ct = time.gmtime() today = datetime.date(ct.tm_year, ct.tm_mon, ct.tm_mday) weeks13 = relativedelta(weeks=13) start_date = today - weeks13 delivery_map, returned_map = delivery_and_returns_data( cr, start_date=start_date) #formatter = DateFormatter('%a %m/%d/%y') #dates_x = drange(date1, date2, delta) fig, ax1 = plt.subplots(nrows=1, ncols=1) plot_data_map(ax1, delivery_map, line='k', label='Delivered') plot_data_map(ax1, returned_map, line='b', label='Returned') ax1.legend() ax1.grid() ax1.xaxis.set_major_formatter(yearsFmt) ax1.xaxis.set_major_locator(weeks) ax1.xaxis.set_minor_locator(days) image_path = get_module_path('html_reports') image_file = os.path.join(image_path, fn) print image_file plt.savefig(image_file, bbox_inches='tight') #print data_map return fn
def main(): args = sys.argv[1:] # The only shared option is '--addons-path=' needed to discover additional # commands from modules if len(args) > 1 and args[0].startswith( '--addons-path=') and not args[1].startswith("-"): # parse only the addons-path, do not setup the logger... tools.config._parse_config([args[0]]) args = args[1:] # Default legacy command command = "server" # Subcommand discovery if len(args) and not args[0].startswith("-"): logging.disable(logging.CRITICAL) for m in module.get_modules(): m_path = module.get_module_path(m) if os.path.isdir(os.path.join(m_path, 'cli')): __import__('openerp.addons.' + m) logging.disable(logging.NOTSET) command = args[0] args = args[1:] if command in commands: o = commands[command]() o.run(args)
def setUpClass(cls): """Declare useful variables to be inherited and used by the children test cases. For instance: - the path to the 'fixtures' directory - an XML parser set to remove all the white spaces while parsing a file - a Jinja2 environment to be used for rendering templates - a context dictionary to be passed to the Odoo's methods requiring it - the URLS dictionary used by the mobile controller - etc. """ super(MobileHTMLRenderingCase, cls).setUpClass() cls.fixtures_directory = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'fixtures') cls.no_whitespace_parser = etree.XMLParser(remove_blank_text=True) loader = jinja2.FileSystemLoader( get_module_path('nh_eobs_mobile') + '/views/') cls.jinja_env = jinja2.Environment(loader=loader) cls.context = { 'lang': 'en_GB', 'tz': 'Europe/London', 'uid': 1 } cls.controller_urls = URLS
def index(self, req, s_action=None, data=None, **kw): if 'db' in kw: dbname=kw['db'] else: dbname='pjb_live' html_ret="" uid=1 print "XXXXXXXXXXXXXXXXXXXXXXXXXXXX" registry = openerp.modules.registry.Registry(dbname) with registry.cursor() as cr: pool = pooler.get_pool(dbname) chart_ids=pool.get("analysis.chart").search(cr,uid,[]) charts = pool.get("analysis.chart").browse(cr,uid,chart_ids) image_path=get_module_path('html_reports') for chart in charts: fn="%d.png" % chart.id image_file=os.path.join(image_path,fn) chart.write({"image_file":image_file}) #pool.get('analysis.chart').generate_bar_charts(cr, uid, chart_ids) pool.get('analysis.chart').generate_chart(cr, uid, chart.id) ctx={'title' : "List of Charts", 'charts': charts, 'fn':fn, 'get_image_url': get_image_url, 'req':req, 'dbname':dbname, } template_path = get_module_resource('html_reports', '', 'chart_list.html') html_ret = render_mako_file(template_path, ctx) return Response(html_ret, mimetype='text/html')
class TestPalliativeStatusTour(HttpCase): """ Test that the palliative status tour passes as a test """ module_path = get_module_path('nh_eobs') inject = [ ( "openerp.Tour.palliative_status_tour", "{0}/static/tours/palliative_status.tour.js".format( module_path ) ) ] def test_palliative_status_tour(self): """ Run the palliative status change tour as a test """ self.phantom_js( "/web", "openerp.Tour.run('palliative_care_flag','test')", "openerp.Tour.tours.palliative_care_flag", login="******", inject=self.inject )
def _run_other_tests(dbname, modules, ignore): _logger.info('Running tests other than unit...') db = sql_db.db_connect(dbname) with closing(db.cursor()) as cr: test_files_by_module = _get_test_files_by_module(modules) for module in test_files_by_module: ignored_files = ignore.get(module, []) if ignored_files == 'all': ignored_files = test_files_by_module[module] for filename in test_files_by_module[module]: vals = { 'module': module, 'file': filename, } if filename in ignored_files\ or not _file_in_requested_directories(get_module_path(module)): vals['result'] = 'ignored' _write_log(vals) continue start = time.time() try: _run_test(cr, module, filename) except Exception, e: vals['duration'] = time.time() - start vals['result'] = 'error' vals['code'] = e.__class__.__name__ vals['exception'] = '\n%s' % _get_exception_message(e) if filename.endswith('.yml'): vals['exception'] += '\n%s' % _build_error_message() _write_log(vals) else: vals['duration'] = time.time() - start vals['result'] = 'success' _write_log(vals) cr.rollback()
def main(): args = sys.argv[1:] # The only shared option is '--addons-path=' needed to discover additional # commands from modules if len(args) > 1 and args[0].startswith('--addons-path=') and not args[1].startswith("-"): # parse only the addons-path, do not setup the logger... tools.config._parse_config([args[0]]) args = args[1:] # Default legacy command command = "server" # Subcommand discovery if len(args) and not args[0].startswith("-"): logging.disable(logging.CRITICAL) for m in module.get_modules(): m_path = module.get_module_path(m) if os.path.isdir(os.path.join(m_path, 'cli')): __import__('openerp.addons.' + m) logging.disable(logging.NOTSET) command = args[0] args = args[1:] if command in commands: o = commands[command]() o.run(args)
class TestStaffAllocationTours(HttpCase): """ Test that the nursing allocation tours pass as tests """ module_path = get_module_path('nh_eobs') inject = [("openerp.Tour.staff_allocation", "{0}/static/tours/staff_allocation.tour.js".format(module_path)) ] def test_nursing_shift_change_tour(self): """ Run the nursing shift change tour as a test """ self.phantom_js("/web", "openerp.Tour.run('nursing_shift_change','test')", "openerp.Tour.tours.nursing_shift_change", login="******", inject=self.inject) def test_nursing_reallocation_tour(self): """ Run the nursing staff reallocation tour as a test """ self.phantom_js("/web", "openerp.Tour.run('nursing_reallocation','test')", "openerp.Tour.tours.nursing_reallocation", login="******", inject=self.inject)
def delivery_and_returns(pool, cr, uid): fn='delivery_and_returns.png' years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month weeks = mdates.WeekdayLocator() days = mdates.DayLocator() yearsFmt = mdates.DateFormatter('%W') ct=time.gmtime() today=datetime.date(ct.tm_year, ct.tm_mon, ct.tm_mday) weeks13 = relativedelta(weeks=13) start_date = today-weeks13 delivery_map, returned_map = delivery_and_returns_data(cr, start_date=start_date) #formatter = DateFormatter('%a %m/%d/%y') #dates_x = drange(date1, date2, delta) fig, ax1 = plt.subplots(nrows=1,ncols=1) plot_data_map( ax1, delivery_map, line='k', label='Delivered') plot_data_map( ax1, returned_map, line='b', label='Returned') ax1.legend() ax1.grid() ax1.xaxis.set_major_formatter(yearsFmt) ax1.xaxis.set_major_locator(weeks) ax1.xaxis.set_minor_locator(days) image_path=get_module_path('html_reports') image_file=os.path.join(image_path,fn) print image_file plt.savefig(image_file, bbox_inches='tight') #print data_map return fn
def sales_by_7days(data_map, header, dates): fn = 'sales_by_7days.png' years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month weeks = mdates.WeekdayLocator() days = mdates.DayLocator() days.MAXTICKS = 2000 formatter = DateFormatter('%a %d/%m/%y') fig, ax1 = plt.subplots(nrows=1, ncols=1) #rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd) ax1.xaxis_date() ax1.xaxis.set_major_formatter(formatter) ax1.xaxis.set_major_locator(days) #ax1.xaxis.set_minor_locator(days) labels = ax1.get_xticklabels() plt.setp(labels, rotation=30, fontsize=10) plt.title('Phone Calls, 7 days window') ax1.grid() key_inbound = (u'Inbound', 'crm.case.categ', 18) plot_days(ax1, data_map, dates, key_inbound, line='k', label='Inbound Calls', days=7) key_sales = (u'Sales Opportunity', 'crm.case.categ', 15) plot_days(ax1, data_map, dates, key_sales, line='r', label='Sales Opportunity', days=7) key_phone = (u'Retail Phone', 'sale.shop', 2) plot_days(ax1, data_map, dates, key_phone, line='-', label='Closed Sales', days=7) ax1.legend() image_path = get_module_path('html_reports') image_file = os.path.join(image_path, fn) print image_file plt.savefig(image_file, bbox_inches='tight') #print data_map return fn
def _compile(self): def filter_pyc(parents, name, contents): return name.endswith(u'.pyc') try: # STEP 1: Backup of all `pyc` files within the module information self.log(1, 'backing_up', self.name) files = self._get_resource_paths(filter_pyc) for pyc_file in files: self._backup(pyc_file) self.log(1, 'backing_done', self.name) # STEP 2: Compile the module try: self.log(1, 'compiling', self.name) module_path = get_module_path(self.name) compileall.compile_dir(module_path, True) for pyc_file in files: _logger.warning('Reload %s' % pyc_file) reload(pyc_file) self.log(1, 'compilation_done', self.name) except Exception as ex: # STEP 3: Restore old files if compilation fails self.log(1, 'compilation_fail', self.name) for pyc_file in files: self._backup(pyc_file, restore=True) self.log(1, 'restoring_done', self.name) raise ex # STEP 4: Update modules m_data_domain = [ ('module', '=', self.name), ('model', '=', 'ir.model.data') ] m_data_obj = self.env['ir.model.data'] m_data_set = m_data_obj.search(m_data_domain) ids = [record.res_id for record in m_data_set] model_obj = self.env['ir.model'] model_set = model_obj.browse(ids) for model in model_set: model = self.env['dev.code.tester'] init_module_models(self.env.cr, 'development_tools', model) except Exception as ex: _logger.error('compile %s' % ex)
def _info(self, cr, uid, ids, field_name, arg, context=None): res = {} for r in self.browse(cr, uid, ids): pth = get_module_path('galtys_analysis') val = {'image_file': pth + '/%d.png' % r.id} res[r.id] = val return res
def _log_assert_failure(self, msg, *args): from openerp.modules import module # cannot be made before (loop) basepath = module.get_module_path(self.module) self.assertion_report.record_failure( details=dict(module=self.module, testfile=os.path.relpath(self.filename, basepath), msg=msg, msg_args=deepcopy(args))) _logger.error(msg, *args)
def release_note(self): # get release_note module path release_note = module.get_module_path('release_note') # get RELEASE-NOTES.md file path release_note_file_path = os.path.join(release_note, "../../../RELEASE-NOTES.md") f = open(release_note_file_path, 'rb') return f.read()
def _info(self, cr, uid, ids,field_name,arg, context=None): res={} for r in self.browse(cr, uid, ids): pth=get_module_path('galtys_analysis') val={'image_file': pth+'/%d.png'%r.id } res[r.id] = val return res
def _compile(self): def filter_pyc(parents, name, contents): return name.endswith(u'.pyc') try: # STEP 1: Backup of all `pyc` files within the module information self.log(1, 'backing_up', self.name) files = self._get_resource_paths(filter_pyc) for pyc_file in files: self._backup(pyc_file) self.log(1, 'backing_done', self.name) # STEP 2: Compile the module try: self.log(1, 'compiling', self.name) module_path = get_module_path(self.name) compileall.compile_dir(module_path, True) for pyc_file in files: _logger.warning('Reload %s' % pyc_file) reload(pyc_file) self.log(1, 'compilation_done', self.name) except Exception as ex: # STEP 3: Restore old files if compilation fails self.log(1, 'compilation_fail', self.name) for pyc_file in files: self._backup(pyc_file, restore=True) self.log(1, 'restoring_done', self.name) raise ex # STEP 4: Update modules m_data_domain = [('module', '=', self.name), ('model', '=', 'ir.model.data')] m_data_obj = self.env['ir.model.data'] m_data_set = m_data_obj.search(m_data_domain) ids = [record.res_id for record in m_data_set] model_obj = self.env['ir.model'] model_set = model_obj.browse(ids) for model in model_set: model = self.env['dev.code.tester'] init_module_models(self.env.cr, 'development_tools', model) except Exception as ex: _logger.error('compile %s' % ex)
def load_manifest(self, name): manifest = module.load_information_from_description_file(name) if manifest: path = module.get_module_path(name) manifest['js'] = list( self.expand_patterns(path, manifest.get('js', []))) manifest['test'] = list( self.expand_patterns(path, manifest.get('test', []))) manifest['qweb'] = list( self.expand_patterns(path, manifest.get('qweb', []))) return manifest
def get_js_routes(self, *args, **kw): name_of_template = 'routes_template.js' path_to_template = get_module_path('nh_eobs_api') + '/views/' # override the RouteManager's base url only for JS routes base_url = request.httprequest.host_url[:-1] routes = route_manager.get_javascript_routes( name_of_template, path_to_template, additional_context={'base_url': base_url, 'base_prefix': route_manager.URL_PREFIX}) return request.make_response( routes, headers={'Content-Type': 'application/javascript'})
def d_three(self, *args, **kw): """ Returns /static/lib/js/d3.js response object. :returns: /static/lib/js/d3.js :rtype: :class:`http.Response<openerp.http.Response>` """ with open( '{0}/static/lib/js/d3.js'.format(get_module_path('nh_graphs')), 'r') as js: return request.make_response( js.read(), headers={'Content-Type': 'text/javascript'})
def d_three(self, *args, **kw): """ Returns /static/lib/js/d3.js response object. :returns: /static/lib/js/d3.js :rtype: :class:`http.Response<openerp.http.Response>` """ with open('{0}/static/lib/js/d3.js'.format( get_module_path('nh_graphs') ), 'r') as js: return request.make_response( js.read(), headers={'Content-Type': 'text/javascript'})
def patient_graph_js(self, *args, **kw): """ Returns /static/src/js/draw_ews_graph.js response object. :returns: /static/src/js/draw_ews_graph.js :rtype: :class:`http.Response<openerp.http.Response>` """ with open('{0}/static/src/js/draw_ews_graph.js'.format( get_module_path('nh_eobs_mobile') ), 'r') as js: return request.make_response( js.read(), headers={'Content-Type': 'text/javascript'})
def get_manifest(self, *args, **kw): """ Returns /static/src/manifest.json response object. :returns: /static/src/manifest.json :rtype: :class:`http.Response<openerp.http.Response>` """ with open( '{0}/static/src/manifest.json'.format( get_module_path('nh_eobs_mobile')), 'r') as manifest: return request.make_response( manifest.read(), headers={'Content-Type': 'application/json'})
def get_big_icon(self, *args, **kw): """ Returns /static/src/icon/hd_hi.png response object. :returns: /static/src/icon/hd_hi.png :rtype: :class:`http.Response<openerp.http.Response>` """ with open( '{0}/static/src/icon/hd_hi.png'.format( get_module_path('nh_eobs_mobile')), 'r') as icon: return request.make_response(icon.read(), headers={'Content-Type': 'image/png'})
def get_bristol_stools_chart(self, *args, **kw): """ Returns /static/src/img/bristol_stools.png response object. :returns: /static/src/img/bristol_stools.png :rtype: :class:`http.Response<openerp.http.Response>` """ with open( '{0}/static/src/img/bristol_stools.png'.format( get_module_path('nh_eobs_mobile')), 'r') as bsc: return request.make_response(bsc.read(), headers={'Content-Type': 'image/png'})
def patient_graph_js(self, *args, **kw): """ Returns /static/src/js/draw_ews_graph.js response object. :returns: /static/src/js/draw_ews_graph.js :rtype: :class:`http.Response<openerp.http.Response>` """ with open( '{0}/static/src/js/draw_ews_graph.js'.format( get_module_path('nh_eobs_mobile')), 'r') as js: return request.make_response( js.read(), headers={'Content-Type': 'text/javascript'})
def get_big_icon(self, *args, **kw): """ Returns /static/src/icon/hd_hi.png response object. :returns: /static/src/icon/hd_hi.png :rtype: :class:`http.Response<openerp.http.Response>` """ with open('{0}/static/src/icon/hd_hi.png'.format( get_module_path('nh_eobs_mobile') ), 'r') as icon: return request.make_response( icon.read(), headers={'Content-Type': 'image/png'})
def get_bristol_stools_chart(self, *args, **kw): """ Returns /static/src/img/bristol_stools.png response object. :returns: /static/src/img/bristol_stools.png :rtype: :class:`http.Response<openerp.http.Response>` """ with open('{0}/static/src/img/bristol_stools.png'.format( get_module_path('nh_eobs_mobile') ), 'r') as bsc: return request.make_response( bsc.read(), headers={'Content-Type': 'image/png'})
def find(self): res = [] for module in self.env['ir.module.module'].search([]): if get_module_path(module.name): continue if module.state == 'uninstalled': module.unlink() continue res.append((0, 0, {'name': module.name})) if not res: raise UserError(_('No modules found to purge')) return res
def on_change_module(self,cr,uid,ids,module_id,context=None): try: if(module_id): module_obj = self.pool.get("ir.module.module").browse(cr,uid,module_id,context=context) self.templates_dir = module.get_module_path(module_obj.name)+ '/templates/' files_ids = self.pool.get("rdef.module.templates").create_list_file(cr,uid,self.templates_dir,context=context) return {'value': { 'file_ids': [], 'module_id':module_id, } } except: return False
def get_manifest(self, *args, **kw): """ Returns /static/src/manifest.json response object. :returns: /static/src/manifest.json :rtype: :class:`http.Response<openerp.http.Response>` """ with open('{0}/static/src/manifest.json'.format( get_module_path('nh_eobs_mobile') ), 'r') as manifest: return request.make_response( manifest.read(), headers={'Content-Type': 'application/json'})
def robot(self, url_path, testfile, login=None, timeout=6000, failfast=False, **kw): """ Test js code running in the browser - optionally log as 'login' - load page given by url_path - wait for ready object to be available - eval(code) inside the page To signal success test do: console.log('ok') To signal failure do: console.log('error') If neither are done before timeout test fails. """ # transform the testfile path into a absolut path by # searching for the addon addon_name = str(self.__class__.__module__)[len('openerp.addons.'):] addon_name = addon_name[:addon_name.find('.')] testfile_path = os.path.join(get_module_path(addon_name), testfile) self.authenticate(login, login) # the log directory is odoo so it works best in runbot # normally /home/openerp/odoo odoo_directory = os.path.dirname(os.path.abspath(sys.argv[0])) log_directory = os.path.join(odoo_directory, '..', 'logs', 'robot') if not os.path.exists(log_directory): os.makedirs(log_directory) log_prefix = '%s.%s.%s_' % (addon_name, str( self.__class__.__name__), self._testMethodName) log_directory = tempfile.mkdtemp(prefix=log_prefix, dir=log_directory) cmd = [ 'pybot', "-v URL:%s" % "http://%s:%s%s" % (HOST, PORT, url_path), "-v COOKIE_NAME:session_id", "-v COOKIE_VALUE:%s" % self.session_id, "-d", log_directory, testfile_path ] if failfast: cmd.append('--exitonerror') self.robot_run(cmd, timeout)
def get_stylesheet(self, *args, **kw): """ Returns /static/src/css/nhc.css (custom stylesheet) response object. :returns: /static/src/css/nhc.css :rtype: :class:`http.Response<openerp.http.Response>` """ with open( '{0}/static/src/css/nhc.css'.format( get_module_path('nh_eobs_mobile')), 'r') as stylesheet: return request.make_response( stylesheet.read(), headers={'Content-Type': 'text/css; charset=utf-8'})
def get_js_routes(self, *args, **kw): name_of_template = 'routes_template.js' path_to_template = get_module_path('nh_eobs_api') + '/views/' # override the RouteManager's base url only for JS routes base_url = request.httprequest.host_url[:-1] routes = route_manager.get_javascript_routes( name_of_template, path_to_template, additional_context={ 'base_url': base_url, 'base_prefix': route_manager.URL_PREFIX }) return request.make_response( routes, headers={'Content-Type': 'application/javascript'})
def get_stylesheet(self, *args, **kw): """ Returns /static/src/css/nhc.css (custom stylesheet) response object. :returns: /static/src/css/nhc.css :rtype: :class:`http.Response<openerp.http.Response>` """ with open('{0}/static/src/css/nhc.css'.format( get_module_path('nh_eobs_mobile') ), 'r') as stylesheet: return request.make_response( stylesheet.read(), headers={'Content-Type': 'text/css; charset=utf-8'})
def sale_Target_pie(pool, cr, uid): fn = 'sale_Target_pie.png' ctoday = time.gmtime() tm_year = ctoday.tm_year tm_mon = ctoday.tm_mon tm_mday = ctoday.tm_mday day = datetime.date(tm_year, tm_mon, tm_mday) y, wk, dwk = day.isocalendar() wk_Target_ids = pool.get('analysis.week.forecast').search( cr, uid, [('wk', '=', wk), ('year_id.y', '=', y)]) assert len(wk_Target_ids) == 1 wk_f = pool.get('analysis.week.forecast').browse(cr, uid, wk_Target_ids[0]) by_week = orders_total_week(cr) # keys=sorted( by_week.keys() ) actual_week = by_week.get((y, wk), 0.0) if wk_f.sale_forecast > 0.0: actual_p = 100 * actual_week / wk_f.sale_forecast else: actual_p = 0.0 sizes = [100 - actual_p, actual_p] labels = 'Target: %.02f' % wk_f.sale_forecast, 'Actual: %.02f' % actual_week colors = ['gold', 'yellowgreen'] explode = (0, 0.1) fig, ax = plt.subplots() plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%.1f%%', shadow=True) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') plt.title(wk_f.wk_title) #plt.show() image_path = get_module_path('html_reports') image_file = os.path.join(image_path, fn) plt.savefig(image_file, bbox_inches='tight') return fn
def find(self, cr, uid, context=None): module_pool = self.pool['ir.module.module'] module_ids = module_pool.search(cr, uid, [], context=context) res = [] for module in module_pool.browse(cr, uid, module_ids, context=context): if get_module_path(module.name): continue if module.state == 'uninstalled': module_pool.unlink(cr, uid, module.id, context=context) continue res.append((0, 0, {'name': module.name})) if not res: raise orm.except_orm(_('Nothing to do'), _('No modules found to purge')) return res
def find(self, cr, uid, context=None): module_pool = self.pool['ir.module.module'] module_ids = module_pool.search(cr, uid, [], context=context) res = [] for module in module_pool.browse(cr, uid, module_ids, context=context): if get_module_path(module.name): continue if module.state == 'uninstalled': module_pool.unlink(cr, uid, module.id, context=context) continue res.append((0, 0, {'name': module.name})) if not res: raise orm.except_orm( _('Nothing to do'), _('No modules found to purge')) return res
def sales_by_month(data_map,header,dates): fn='sales_by_month.png' rule = rrulewrapper(DAILY, byeaster=1, interval=5) loc = RRuleLocator(rule) years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month weeks = mdates.WeekdayLocator() days = mdates.DayLocator() weeks.MAXTICKS = 2000 formatter = DateFormatter('%a %d/%m/%y') #dates_x = drange(date1, date2, delta) fig, ax1 = plt.subplots(nrows=1,ncols=1) #ax=ax1 ax1.xaxis_date() ax1.xaxis.set_major_formatter(formatter) ax1.xaxis.set_major_locator(weeks) ax1.xaxis.set_minor_locator(days) labels = ax1.get_xticklabels() #labels = ax1.xaxis.get_major_ticks() plt.setp(labels, rotation=30, fontsize=10) plt.title('Phone Calls, 30 days window') ax1.grid() key_inbound=(u'Inbound', 'crm.case.categ', 18) plot_days(ax1, data_map, dates, key_inbound, line='k', label='Inbound Calls', days=30) key_sales= (u'Sales Opportunity', 'crm.case.categ', 15) plot_days(ax1, data_map, dates, key_sales, line='r', label='Sales Opportunity', days=30) key_phone= (u'Retail Phone', 'sale.shop', 2) plot_days(ax1, data_map, dates, key_phone, line='-', label='Closed Sales', days=30) ax1.legend() image_path=get_module_path('html_reports') image_file=os.path.join(image_path,fn) # print image_file plt.savefig(image_file, bbox_inches='tight') #print data_map return fn
def _compute_checksum_dir(self): exclude = self.env["ir.config_parameter"].get_param( "module_auto_update.checksum_excluded_extensions", "pyc,pyo", ).split(",") for r in self: try: r.checksum_dir = dirhash( get_module_path(r.name), 'sha1', excluded_extensions=exclude, ) except TypeError: _logger.debug( "Cannot compute dir hash for %s, module not found", r.display_name)
def sales_total_by_month(pool, cr, uid): fn='sales_total_by_month.png' import datetime import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.cbook as cbook years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month yearsFmt = mdates.DateFormatter('%m') weeks = mdates.WeekdayLocator() #by_month= orders_total_month_actual(cr) by_day = orders_total_day_actual(cr) Target_by_month= orders_total_month_Target(pool, cr, uid) #formatter = DateFormatter('%a %m/%d/%y') #dates_x = drange(date1, date2, delta) fig, ax1 = plt.subplots(nrows=1,ncols=1) plot_data_map( ax1, by_day, line='k', label='Actual') plot_by_month( ax1, Target_by_month, line='b', label='Target') ax1.legend() ax1.grid() # ax1.title( 'Total Sales since Dec 2013 ' ) #ax=ax1 #ax1.xaxis_date() #ax1.xaxis.set_major_formatter(formatter) #labels = ax1.get_xticklabels() #plt.setp(labels, rotation=30, fontsize=10) #plt.title('Phone Calls, 7 days window') #ax1.grid() ax1.xaxis.set_major_locator(months) ax1.xaxis.set_major_formatter(yearsFmt) ax1.xaxis.set_minor_locator(weeks) image_path=get_module_path('html_reports') image_file=os.path.join(image_path,fn) print image_file plt.savefig(image_file, bbox_inches='tight') #print data_map return fn
def report_path_names(report,folder_template=None): env_vars = {} if folder_template == None: folder_template = 'templates' env_vars['report_name'] = report.name env_vars['module_name'] = report.module_id.name env_vars['json_file_name'] = report.json_file_name env_vars['template_file_name'] = end_file(report.template_file_name,'.html') env_vars['template_html'] = folder_template env_vars['xml_file_name'] = end_file(report.xml_file_name,'.xml') print 'env_vars[module_name] :', env_vars['module_name'] #env_vars['path_json_file'] = CD_STATIC_REPORTS +env_vars['module_name']+"/" + env_vars['report_name']+"/JSON/" env_vars['path_template_source'] = module.get_module_path(env_vars['module_name']) + "/" + folder_template + "/" env_vars['path_name_output'] = CD_STATIC_REPORTS + env_vars['module_name']+"/"+env_vars['report_name']+"/HTML/" env_vars['path_xml_report'] = CD_STATIC_REPORTS + env_vars['module_name']+"/"+env_vars['report_name']+"/report_def/" return env_vars
def sales_bar_chart(): fn = 'sales_bar_chart.png' N = 5 menMeans = (20, 35, 30, 35, 27) menStd = (2, 3, 4, 1, 2) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd) womenMeans = (25, 32, 34, 20, 25) womenStd = (3, 5, 2, 3, 3) rects2 = ax.bar(ind + width, womenMeans, width, color='y', yerr=womenStd) # add some text for labels, title and axes ticks ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') print "ind + width ", ind, width, ind + width ax.set_xticks(ind + width) ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5')) ax.legend((rects1[0], rects2[0]), ('Men', 'Women')) def autolabel(rects): # attach some text labels for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height, '%d' % int(height), ha='center', va='bottom') autolabel(rects1) autolabel(rects2) image_path = get_module_path('html_reports') image_file = os.path.join(image_path, fn) plt.savefig(image_file, bbox_inches='tight') #print data_map return fn
def sale_Target_pie_month(pool, cr, uid): fn = 'sale_Target_pie_monty.png' ctoday = time.gmtime() tm_year = ctoday.tm_year tm_mon = ctoday.tm_mon tm_mday = ctoday.tm_mday day = datetime.date(tm_year, tm_mon, tm_mday) y, wk, dwk = day.isocalendar() by_month = orders_total_month_actual(cr) Target_by_month = orders_total_month_Target(pool, cr, uid, y=y) actual_month = by_month.get((y, tm_mon), 0.0) Target_month = Target_by_month.get((tm_year, tm_mon), 0.0) if Target_month > 0.0: actual_p = 100 * actual_month / Target_month else: actual_p = 0.0 sizes = [actual_month / Target_month, actual_month] sizes = [100 - actual_p, actual_p] labels = 'Target: %.02f' % Target_month, 'Actual: %.02f' % actual_month colors = ['gold', 'yellowgreen'] explode = (0, 0.1) fig, ax = plt.subplots() plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%.1f%%', shadow=True) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') plt.title("Month %s/%s" % (tm_mon, tm_year)) image_path = get_module_path('html_reports') image_file = os.path.join(image_path, fn) plt.savefig(image_file, bbox_inches='tight') return fn
def sales_total_by_month(pool, cr, uid): fn = 'sales_total_by_month.png' import datetime import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.cbook as cbook years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month yearsFmt = mdates.DateFormatter('%m') weeks = mdates.WeekdayLocator() #by_month= orders_total_month_actual(cr) by_day = orders_total_day_actual(cr) Target_by_month = orders_total_month_Target(pool, cr, uid) #formatter = DateFormatter('%a %m/%d/%y') #dates_x = drange(date1, date2, delta) fig, ax1 = plt.subplots(nrows=1, ncols=1) plot_data_map(ax1, by_day, line='k', label='Actual') plot_by_month(ax1, Target_by_month, line='b', label='Target') ax1.legend() ax1.grid() # ax1.title( 'Total Sales since Dec 2013 ' ) #ax=ax1 #ax1.xaxis_date() #ax1.xaxis.set_major_formatter(formatter) #labels = ax1.get_xticklabels() #plt.setp(labels, rotation=30, fontsize=10) #plt.title('Phone Calls, 7 days window') #ax1.grid() ax1.xaxis.set_major_locator(months) ax1.xaxis.set_major_formatter(yearsFmt) ax1.xaxis.set_minor_locator(weeks) image_path = get_module_path('html_reports') image_file = os.path.join(image_path, fn) print image_file plt.savefig(image_file, bbox_inches='tight') #print data_map return fn
def sales_bar_chart(): fn='sales_bar_chart.png' N = 5 menMeans = (20, 35, 30, 35, 27) menStd = (2, 3, 4, 1, 2) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd) womenMeans = (25, 32, 34, 20, 25) womenStd = (3, 5, 2, 3, 3) rects2 = ax.bar(ind + width, womenMeans, width, color='y', yerr=womenStd) # add some text for labels, title and axes ticks ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') print "ind + width ", ind, width, ind+width ax.set_xticks(ind + width) ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5')) ax.legend((rects1[0], rects2[0]), ('Men', 'Women')) def autolabel(rects): # attach some text labels for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., 1.05*height, '%d' % int(height), ha='center', va='bottom') autolabel(rects1) autolabel(rects2) image_path=get_module_path('html_reports') image_file=os.path.join(image_path,fn) plt.savefig(image_file, bbox_inches='tight') #print data_map return fn
def sale_Target_pie(pool, cr, uid): fn='sale_Target_pie.png' ctoday=time.gmtime() tm_year = ctoday.tm_year tm_mon = ctoday.tm_mon tm_mday = ctoday.tm_mday day=datetime.date(tm_year, tm_mon, tm_mday) y,wk,dwk=day.isocalendar() wk_Target_ids=pool.get('analysis.week.forecast').search(cr, uid, [('wk','=',wk),('year_id.y','=',y)]) assert len(wk_Target_ids)==1 wk_f = pool.get('analysis.week.forecast').browse(cr, uid, wk_Target_ids[0] ) by_week= orders_total_week(cr) # keys=sorted( by_week.keys() ) actual_week = by_week.get( (y,wk), 0.0) if wk_f.sale_forecast>0.0: actual_p=100*actual_week/wk_f.sale_forecast else: actual_p=0.0 sizes = [100-actual_p, actual_p] labels = 'Target: %.02f'%wk_f.sale_forecast, 'Actual: %.02f'%actual_week colors = ['gold', 'yellowgreen'] explode = (0, 0.1) fig, ax = plt.subplots() plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%.1f%%', shadow=True) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') plt.title( wk_f.wk_title ) #plt.show() image_path=get_module_path('html_reports') image_file=os.path.join(image_path,fn) plt.savefig(image_file, bbox_inches='tight') return fn
def setUp(self): super(TestRouteManagerJavascriptGeneration, self).setUp() # Create the RouteManager and feed it with some initial data self.objects_number = 5 generated_route_list = _generate_route_objects(self.objects_number) self.route_manager = RouteManager() for r in generated_route_list: self.route_manager.add_route(r) # Check that the RouteManager has been properly created and fed self.assertEqual(len(self.route_manager.ROUTES), self.objects_number) for r in self.route_manager.ROUTES.values(): self.assertIsInstance(r, Route) # Let's start (eventually!) self.name_of_template = 'template_test.js' self.path_to_template = get_module_path('nh_eobs_mobile') + '/tests/' self.all_route_list = self.route_manager.ROUTES.values() self.assertIsInstance(self.all_route_list, list)
def sales_by_7days(data_map,header,dates): fn='sales_by_7days.png' years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month weeks = mdates.WeekdayLocator() days = mdates.DayLocator() days.MAXTICKS = 2000 formatter = DateFormatter('%a %d/%m/%y') fig, ax1 = plt.subplots(nrows=1,ncols=1) #rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd) ax1.xaxis_date() ax1.xaxis.set_major_formatter(formatter) ax1.xaxis.set_major_locator(days) #ax1.xaxis.set_minor_locator(days) labels = ax1.get_xticklabels() plt.setp(labels, rotation=30, fontsize=10) plt.title('Phone Calls, 7 days window') ax1.grid() key_inbound=(u'Inbound', 'crm.case.categ', 18) plot_days(ax1, data_map, dates, key_inbound, line='k', label='Inbound Calls', days=7) key_sales= (u'Sales Opportunity', 'crm.case.categ', 15) plot_days(ax1, data_map, dates, key_sales, line='r', label='Sales Opportunity', days=7) key_phone= (u'Retail Phone', 'sale.shop', 2) plot_days(ax1, data_map, dates, key_phone, line='-', label='Closed Sales', days=7) ax1.legend() image_path=get_module_path('html_reports') image_file=os.path.join(image_path,fn) print image_file plt.savefig(image_file, bbox_inches='tight') #print data_map return fn
def update_git_information(cr, module_name): pool = pooler.get_pool(cr.dbname) module_pool = pool.get('ir.module.module') module_path = get_module_path(module_name) try: repo = git.Repo(module_path) try: active_branch = repo.active_branch.name except TypeError, e: if 'HEAD is a detached symbolic reference' in str(e): active_branch = repo.head.commit.hexsha else: raise e commit_hash = repo.commit().hexsha git_repository_name = os.path.split(repo.working_dir)[-1] module_ids = module_pool.search(cr, 1, [('name', '=', module_name)]) module_pool.write(cr, 1, module_ids, { 'git_current_branch': active_branch, 'git_current_commit': commit_hash, 'git_repository_name': git_repository_name, })
def get_font(self, xmlid, *args, **kw): """ Returns font-woff response object from fonts contained in /static/srs/font/. :returns: a Web Open Font Format (WOFF) font :rtype: :class:`http.Response<openerp.http.Response>` """ mod_path = get_module_path('nh_eobs_mobile') font_file_request = '{0}/static/src/fonts/{1}'.format( mod_path, xmlid) # Consider only the file's name (without additional unwanted parts) # when checking for file's existence font_file_path = '{0}/static/src/fonts/{1}'.format( mod_path, xmlid.split('?')[0] ) if isinstance(xmlid, basestring) and os.path.exists(font_file_path): with open(font_file_request, 'r') as font: return request.make_response( font.read(), headers={'Content-Type': 'application/font-woff'}) else: exceptions.abort(404)
def sale_Target_pie_month(pool, cr, uid): fn='sale_Target_pie_monty.png' ctoday=time.gmtime() tm_year = ctoday.tm_year tm_mon = ctoday.tm_mon tm_mday = ctoday.tm_mday day=datetime.date(tm_year, tm_mon, tm_mday) y,wk,dwk=day.isocalendar() by_month= orders_total_month_actual(cr) Target_by_month= orders_total_month_Target(pool, cr, uid, y=y) actual_month = by_month.get( (y,tm_mon), 0.0) Target_month = Target_by_month.get( (tm_year,tm_mon), 0.0 ) if Target_month>0.0: actual_p=100*actual_month/Target_month else: actual_p=0.0 sizes = [actual_month/Target_month, actual_month] sizes = [100-actual_p, actual_p] labels = 'Target: %.02f'%Target_month, 'Actual: %.02f'%actual_month colors = ['gold', 'yellowgreen'] explode = (0, 0.1) fig, ax = plt.subplots() plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%.1f%%', shadow=True) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') plt.title( "Month %s/%s"%(tm_mon, tm_year) ) image_path=get_module_path('html_reports') image_file=os.path.join(image_path,fn) plt.savefig(image_file, bbox_inches='tight') return fn
def _load_translation(self, cr, uid, ids=None, context=None, eval=None): """ Localization helper - reads all terms from german po file - updates / created terms in ir_translation table @cr: cursor @uid: user id @ids: ids @context: context """ # extract module name from function call EVAL from extern modules (the call is in each view) actual_module = 'equitania' if ids is not None: actual_module = ids addon_folder = get_module_path(actual_module) #print "#### actual_module", actual_module #print "#### addon_folder", addon_folder # german langauage german_lang = self.pool.get('res.lang').search(cr, uid, [('code', '=', 'de_DE')]) if len(german_lang) != 0: po = polib.pofile(addon_folder + '/i18n/de.po') valid_entries = [e for e in po if not e.obsolete] ir_translation_obj = self.pool.get('ir.translation') ir_ui_view_obj = self.pool.get('ir.ui.view') ir_translation_obj.clear_caches() # start localization for everything else than view:website self._localize_backend(valid_entries, ir_translation_obj, ir_ui_view_obj, cr, uid) for entry in valid_entries: for occurence in entry.occurrences: occurence_split = occurence[0].split(':') #Views if occurence_split[0] == 'view': #website reports if occurence_split[1] == 'website': report_id = occurence_split[2].split('.')[-1] #print "report_id", report_id if len(ir_ui_view_obj.search(cr, uid, [('name', '=', report_id)])) != 0: view_id = ir_ui_view_obj.search(cr, uid, [('name', '=', report_id)])[0] translation_id = ir_translation_obj.search(cr, uid, [('src', '=', entry.msgid), ('res_id', '=', view_id), ('name', '=', occurence_split[1]), ('lang', '=', 'de_DE')]) if len(translation_id) != 0: vals = { 'value': entry.msgstr, 'state': 'translated', } ir_translation_obj.write(cr, uid, translation_id[0], vals) else: vals = { 'lang': 'de_DE', 'src': entry.msgid, 'name': 'website', 'res_id': view_id, 'module': occurence_split[2].split('.')[0], 'state': 'translated', 'value': entry.msgstr, 'type': occurence_split[0], } ir_translation_obj.create(cr, uid, vals) return True
from openerp.addons.nh_eobs_mobile.controllers import urls import jinja2 import os import logging _logger = logging.getLogger(__name__) URL_PREFIX = '/mobile/' URLS = urls.URLS db_list = http.db_list db_monodb = http.db_monodb loader = jinja2.FileSystemLoader(get_module_path('nh_eobs_mobile') + '/views/') env = jinja2.Environment(loader=loader) single_patient = EobsRoute( 'single_patient', '/patient/<patient_id>', methods=['GET'], url_prefix='/mobile' ) patient_list = EobsRoute( 'patient_list', '/patients/', methods=['GET'], url_prefix='/mobile' ) task_list = EobsRoute( 'task_list',