def fetch(self, rows, page=1, sidx='calldate', sord='desc', _search='false', searchOper=None, searchField=None, searchString=None, **kw): ''' Called by Grid JavaScript component ''' if not in_any_group('admin', 'APPELS', 'CDS', 'utilisateurs'): flash(u'Accès interdit') redirect('/') # Try and use grid preference grid_rows = session.get('grid_rows', None) if rows=='-1': # Default value rows = grid_rows if grid_rows is not None else 25 # Save grid preference session['grid_rows'] = rows session.save() rows = int(rows) try: page = int(page) offset = (page-1) * rows except: offset = 0 page = 1 global filtered_cdrs cdrs = filtered_cdrs total = cdrs.count()/rows + 1 column = getattr(CDR, sidx) cdrs = cdrs.order_by(getattr(column,sord)()).offset(offset).limit(rows) data = [] for cdr in cdrs.all(): src = cdr.src if src and in_any_group('admin', 'APPELS', 'CDS') and hide_numbers: src = src[:-3] + '***' dst = cdr.dst if dst and in_any_group('admin', 'APPELS', 'CDS') and hide_numbers: dst = cdr.dst[:-3] + '***' data.append({ 'id' : cdr.acctid, 'cell': [ cdr.calldate, src, dst, f_disp(cdr.disposition), f_bill(cdr.billsec), rec_link(cdr) ] }) return dict(page=page, total=total, rows=data)
def index(self, **kw): log.debug('index') if Globals.manager is None: flash(u'Vérifier la connexion Asterisk', 'error') else: Globals.manager.send_action({'Action': 'QueueStatus'}) for k in ('custom1', 'member', 'queue', 'date', 'hour'): if k in session.keys(): del(session[k]) session.save() # User must be admin or queue supervisor sv = ['admin'] for q in Globals.asterisk.queues: sv.append('SV ' + q) if not in_any_group(*sv): tmpl_context.grid = None flash(u'Accès interdit !', 'error') else: tmpl_context.grid = grid tmpl_context.form = search_form # Use tabs ui_tabs_js.inject() return dict(title=u"Liste des enregistrements", debug='', values={})
def list(self, cmp_id, cmp_name): ''' Display the list of customers ''' # User must be admin or queue supervisor or queue member sv = ['admin'] for q in Globals.asterisk.queues: sv.append('SV ' + q) sv.append('AG ' + q) if not in_any_group(*sv): tmpl_context.grid = None flash(u'Accès interdit !', 'error') else: tmpl_context.grid = MyJqGrid( id='grid', url='customer_fetch', caption=u'Clients', colNames = [u'Nom', u'Code', u'Téléphone(s)'], colModel = [ { 'name': 'name', 'width': 160 }, { 'name': 'code', 'width': 60, }, { 'name': 'phone', 'width': 160, 'sortable': False, 'search': False }, ], postData = {'cmp_id': cmp_id}, sortname = 'lastname', navbuttons_options = {'view': False, 'edit': False, 'add': False, 'del': False, 'search': False, 'refresh': True, }, ) tmpl_context.form = None return dict(title=u'Clients pour la campagne "%s"' % cmp_name, debug='')
def index2(self, custom1=None, member=None, queue=None, date=None, hour=None): ''' List records ''' log.debug('index2: custom1=%s (%s), member=%s (%s), queue=%s (%s), date=%s (%s), hour=%s (%s).' % ( custom1, type(custom1), member, type(member), queue, type(queue), date, type(date), hour, type(hour))) session['custom1'] = custom1 if custom1 is not None and custom1!='' else None session['member'] = member if member is not None and member!=-1 else None session['queue'] = queue if queue is not None and queue!=-1 else None session['date'] = date if date is not None else None session['hour'] = hour if hour is not None and hour!='' else None session.save() # User must be admin or queue supervisor sv = ['admin'] for q in Globals.asterisk.queues: sv.append('SV ' + q) if not in_any_group(*sv): tmpl_context.grid = None flash(u'Accès interdit !', 'error') else: tmpl_context.grid = grid tmpl_context.form = search_form # Use tabs ui_tabs_js.inject() return dict( title=u"Liste des enregistrements", debug='', values={'custom1': custom1, 'member': member, 'queue': queue, 'date': date, 'hour': hour})
class AdminController(StandardController): allow_only = in_any_group(Group.TIM_MANAGER_GROUPNAME, Group.TIM_ADMIN_GROUPNAME) # FIXME - Check rights workspaces = WorkspaceRestController() users = UserRestController()
def delete(self, id, **kw): ''' Delete call forward ''' exten, cf, to = kw['_id'].split(':') try: p = DBSession.query(Phone).filter(Phone.exten==exten).one() except: log.warning('No phone for extension %s' % exten) flash(u'Poste %s inexistant, renvoi non supprimé' % exten, 'error') redirect('/forwards/') log.info('delete %s %s %s' % (p.sip_id, cf, to)) if in_any_group('admin', 'CDS'): man = Globals.manager.command('database del %s %s' % ( cf, p.sip_id)) log.debug('admin: database delete %s %s returns %s' % ( cf_types, p.sip_id, man)) else: u = DBSession.query(User).get(request.identity['user'].user_id) for p in u.phone: man = Globals.manager.command('database del %s %s' % ( cf, p.sip_id)) log.debug('database delete %s %s returns %s' % ( cf, p.sip_id, man)) # flash(u'Une erreur est survenue', 'error') redirect('/forwards/')
class RootController(TGController): allow_only = in_any_group( 'voter', 'managers', msg=l_('Only for people with the "manage" permission')) invitation = InvitationController(model, model.DBSession, config_type=TGAdminConfig) voter = VoterController(model, model.DBSession, config_type=TGAdminConfig) publication = PublicationController(model, model.DBSession, config_type=TGAdminConfig) project = ProjectController(model, model.DBSession, config_type=TGAdminConfig) account = AccountController(model, model.DBSession, config_type=TGAdminConfig) script = LoadDataControllers(model, model.DBSession, config_type=TGAdminConfig) def __init__(self): self.utility = Utility() @expose('managepoll.templates.index') def index(self): flash(_("Hello World!")) return dict(page='index', idproject=None)
def check_access(): '''Check access rights / group: admin=full access, boss=users from same department, user. Returns SA Query object for selected CDRs ''' if in_any_group('admin', 'APPELS'): cdrs = DBSession.query(CDR) elif in_group('CDS'): # Find list of phones from the user's list of phones # user_phones -> departments -> phones phones = [] for p in request.identity['user'].phone: log.info('CDS phone %s -> department %s' % (p, p.department)) for d in [d.department for d in request.identity['user'].phone]: log.info('CDS department <%s>' % (d)) for p in d.phones: phones.append(p) src = [prefix_src + p.exten for p in phones] dst = [p.exten for p in phones] cdrs = DBSession.query(CDR).filter( (CDR.src.in_(src)) | (CDR.dst.in_(dst)) ) log.info('CDS phone <%s> -> source <%s>, destination <%s>' % ( request.identity['user'].phone, src, dst)) elif in_group('utilisateurs'): src = [prefix_src + p.exten for p in request.identity['user'].phone] dst = [p.exten for p in request.identity['user'].phone] cdrs = DBSession.query(CDR).filter( (CDR.src.in_(src)) | (CDR.dst.in_(dst)) ) else: flash(u'Accès interdit') redirect('/') return cdrs
def csv(self, cmp_id): # User must be admin or queue supervisor sv = ['admin'] for q in Globals.asterisk.queues: sv.append('SV ' + q) if not in_any_group(*sv): tmpl_context.grid = None flash(u'Accès interdit !', 'error') return '' csvdata = StringIO.StringIO() writer = csv.writer(csvdata) p = DBSession.query(Campaign).get(cmp_id) # File name + write header today = datetime.today() name = p.name filename = 'statistiques-campagne-%s-%s.csv' % (name.replace(' ', '_'), today.strftime('%Y%m%d-%H%M%S')) writer.writerow(('Campagne', name.encode('utf-8'))) writer.writerow(('Statistiques au', today.strftime('%d/%m/%Y-%Hh%Mh%Ss'))) writer.writerow(()) colnames = ((-1, u'Agent'), (0, u'RDV Call Center'), (1, u'\u00C0 rappeler'), (2, u'\u00C0 rappeler une deuxième fois'), (3, u'Dernier rappel'), (4, u'Contacte directement son cc/réfléchi'), (5, u'Pas intéressé / coupe court'), (6, u'Absent pendant la campagne'), (7, u'Décédé'), (8, u'Faux numéro / Aucun numéro'), (9, u'Injoignable'), (10, u'Hors cible'), (11, u'Réclamation')) writer.writerow([c[1].encode('utf-8') for c in colnames]) members, total = stats_compute(cmp_id) # Write CSV data for k,v in members.iteritems(): writer.writerow([k, v['r0'], v['r1'], v['r2'], v['r3'], v['r4'], v['r5'], v['r6'], v['r7'], v['r8'], v['r9'], v['r10'], v['r11']]) rh = response.headers rh['Content-Type'] = 'text/csv; charset=utf-8' rh['Content-Disposition'] = str( (u'attachment; filename="%s"' % ( filename)).encode('utf-8') ) rh['Pragma'] = 'public' # for IE rh['Cache-Control'] = 'max-age=0' #for IE return csvdata.getvalue()
class UserPasswordAdminRestController(TIMRestController): """CRUD Controller allowing to manage password of a given user.""" allow_only = predicates.in_any_group( Group.TIM_MANAGER_GROUPNAME, Group.TIM_ADMIN_GROUPNAME, ) def _before(self, *args, **kw): """ Instantiate the current workspace in tg.tmpl_context. :param args: :param kw: :return: """ super(self.__class__, self)._before(args, kw) api = UserApi(tg.tmpl_context.current_user) user_id = tg.request.controller_state.routing_args.get('user_id') user = api.get_one(user_id) tg.tmpl_context.user_id = user_id tg.tmpl_context.user = user @tg.expose('tracim.templates.admin.user_password_edit') def edit(self): current_user = tmpl_context.current_user api = UserApi(current_user) dictified_user = Context(CTX.USER).toDict(tmpl_context.user, 'user') return DictLikeClass(result=dictified_user) @tg.expose() def put(self, new_password1, new_password2, next_url=''): # FIXME - Manage current_user = tmpl_context.current_user user = tmpl_context.user if not next_url: next_url = tg.lurl('/admin/users/{}'.format(user.user_id)) if not new_password1 or not new_password2: tg.flash(_('Empty password is not allowed.'), CST.STATUS_ERROR) tg.redirect(next_url) if new_password1 != new_password2: tg.flash(_('New passwords do not match.'), CST.STATUS_ERROR) tg.redirect(next_url) user.password = new_password1 pm.DBSession.flush() tg.flash(_('The password has been changed'), CST.STATUS_OK) tg.redirect(next_url)
def fetch_hourly(self, page, rows, sidx, sord='asc', _search='false', searchOper=None, searchField=None, searchString=None, **kw): ''' Function called on AJAX request made by FlexGrid Fetch data from DB, return the list of rows + total + current page ''' if not in_any_group('admin','STATS'): return dict(page=0, total=0, rows=[]) try: page = int(page) rows = int(rows) offset = (page-1) * rows except: page = 1 rows = 24 offset = 0 log.info('fetch_hourly : page=%d, rows=%d, offset=%d, sidx=%s, sord=%s' % ( page, rows, offset, sidx, sord)) # Initialize data, in case no data is available for that time slice data = [{'id': x, 'cell': ['%d h 00 < %d h 00' % (x, x+1), 0, None]} for x in range(24)] # Count calls by hour if db_engine=='oracle': req = func.to_char(CDR.calldate, 'HH24') else: # PostgreSql req = func.date_trunc('hour', cast(CDR.calldate, TIME)) cdrs = DBSession.query(req, func.count(req), func.sum(CDR.billsec)) if self.stats_type: # Monthly stats d = datetime.datetime.strptime(self.stats_type, '%m/%d/%Y') if db_engine=='oracle': cdrs = cdrs.filter(func.trunc(CDR.calldate, 'month') == \ func.trunc(d, 'month')) else: # PostgreSql cdrs = cdrs.filter(func.date_trunc('month', CDR.calldate) == \ func.date_trunc('month', d)) cdrs = cdrs.group_by(req) # cdrs = cdrs.order_by(func.sum(CDR.billsec)) for i, c in enumerate(cdrs): if db_engine=='oracle': j = int(c[0]) else: # PostgreSql j = c[0].seconds / 3600 data[j] = {'id': j, 'cell': ['%d h 00 < %d h 00' % (j,j+1), c[1], hms(c[2])]} return dict(page=page, total=24, rows=data[offset:offset+page*rows])
def index(self): ''' Display Stats form ''' if Globals.manager is None: flash(u'Vérifier la connexion Asterisk', 'error') else: Globals.manager.send_action({'Action': 'QueueStatus'}) sv = ['admin'] for q in Globals.asterisk.queues: sv.append('SV ' + q) if not in_any_group(*sv): tmpl_context.form = TableForm(submit_text=None) flash(u'Accès interdit !', 'error') else: tmpl_context.form = stats_form return dict( title=u'Statistiques des groupes d\'appels', debug='', values='')
def get_all(self): ''' Display the list of existing campaigns ''' # User must be admin or queue supervisor sv = ['admin'] for q in Globals.asterisk.queues: sv.append('SV ' + q) if not in_any_group(*sv): tmpl_context.grid = None flash(u'Accès interdit !', 'error') else: tmpl_context.grid = grid tmpl_context.form = None return dict(title=u"Liste des campagnes", debug='')
def new(self, **kw): ''' Display new forward form ''' if in_any_group('admin', 'CDS'): tmpl_context.form = new_forward_cds_form log.debug('admin / CDS -> tmpl_context.form = new_forward_CDS_form') elif in_group('Renvoi externe'): tmpl_context.form = new_forward_external_form log.debug('tmpl_context.form = new_forward_external_form') else: tmpl_context.form = new_forward_form log.debug('tmpl_context.form = new_forward_form') return dict(title = u'Nouveau renvoi', debug='', values=None)
def csv(self, report_type='group', message=None): ''' Export data ''' if not in_any_group('admin', 'DG', 'COMPTA', 'CDS', 'Utilisateurs'): flash(u'Accès interdit') redirect('/') today = datetime.datetime.today() filename = 'telephone-' + today.strftime('%Y%m%d') + '.csv' import StringIO import csv csvdata = StringIO.StringIO() writer = csv.writer(csvdata) # Global header if report_type=='detail': rt = 'détaillé' else: rt = 'récapitulatif par poste' writer.writerow(['Consommation téléphonique']) writer.writerow(['Date', today.strftime('%d/%m/%Y')]) writer.writerow(['Type de rapport', rt]) if message: writer.writerow([unicode(message).encode('utf-8')]) writer.writerow([]) row = ['Service', 'Nom (poste)', 'Durée', 'CFP HT', 'CFP TTC'] if report_type=='detail': row.insert(2, 'Date') row.insert(3, 'Appelé') writer.writerow(row) # Add data lines for cdr in fetch(report_type, 1, 1000000)['rows']: cdr['cell'][0] = unicode(cdr['cell'][0]).encode('utf-8') \ if cdr['cell'][0] else None cdr['cell'][1] = unicode(cdr['cell'][1]).encode('utf-8') \ if cdr['cell'][1] else None writer.writerow(cdr['cell']) # Send response rh = response.headers rh['Content-Type'] = 'text/csv; charset=utf-8' rh['Content-Disposition'] = str( (u'attachment; filename="%s"' % ( filename)).encode('utf-8') ) rh['Pragma'] = 'public' # for IE rh['Cache-Control'] = 'max-age=0' #for IE return csvdata.getvalue()
def index(self): ''' ''' if Globals.manager is None: flash(u'Vérifier la connexion Asterisk', 'error') else: Globals.manager.send_action({'Action': 'QueueStatus'}) sv = ['admin'] for q in Globals.asterisk.queues: sv.append('SV ' + q) sv.append('AG ' + q) if not in_any_group(*sv): auth = 0 flash(u'Accès interdit !', 'error') redirect('/') else: auth=1 return dict( title=u'\u00C9tat des groupes d\'appels', debug='', auth=auth)
def index(self, **kw): ''' Display closed form ''' sv = ['admin'] for q in Globals.asterisk.queues: sv.append('SV ' + q) if not in_any_group(*sv): tmpl_context.form = TableForm(submit_text=None) flash(u'Accès interdit !', 'error') redirect('/') checked = None man = Globals.manager.command('database show closed') checked = [] for i,r in enumerate(man.response[3:-2]): match = re_db.search(r) if match: k, v = match.groups() log.debug('Line %d match: %s -> %s' % (i, k, v)) if v == '1': checked.append(k) else: log.debug('Line %d no match: %s' % (i, r)) tmpl_context.form = TableForm( name = 'close_form', fields = [ CheckBoxList('checked', options = [(k,v) for k,v in sorted(closed.iteritems())], label_text = u'Agences fermées', help_text = u'Cochez une agence'), ], submit_text = u'Valider...', action = 'modify', # hover_help = True, ) return dict(title='Fermeture d\'agence', debug='', values={'checked': checked})
def check_access(cdrs): '''Check access rights / group: admin=full access, boss=users from same department, user. Returns SA Query object for selected CDRs ''' if in_any_group('admin', 'DG', 'COMPTA'): return cdrs elif in_group('CDS'): # Find list of departments from the user's phones deps = [p.department.dptm_id for p in request.identity['user'].phone] log.info('CDS departments <%s>' % (deps)) cdrs = cdrs.filter(CDR.department.in_(deps)) elif in_group('Utilisateurs'): cdrs = cdrs.filter(CDR.user==request.identity['user'].user_id) else: flash(u'Accès interdit') redirect('/') return cdrs
class CCTVController(BaseController): """ allow_only = Any( has_permission('manage'), has_permission('marketingmanage'), has_permission('marketing'), msg=l_('Only for people with the "marketing" permission') ) """ @expose('jistdocstore.templates.cctv.cctvindex') def index(self): return dict(page="Index", form=test_form) @expose('jistdocstore.templates.cctv.cctvindex') def menu(self): cam1 = camsmobotix[0] cam1_stream_src = "http://%s/control/faststream.jpg?stream=full&fps=10.0&dummy=1804289385" % cam1 cams = self.setup5camtopbar() return dict(page='Camera Views', cam1=cam1_stream_src, cam2=cams[0], cam3=cams[1], cam4=cams[2], cam5=cams[3], cam6=cams[4], selfname="getfastframe") @expose('jistdocstore.templates.cctv.cctvgridviewresponsive') def cctvgridviewresponsive(self): return dict(page="CCTV Grid View Responsive") @expose('jistdocstore.templates.cctv.cctvcarousel') def cctvcarousel(self): return dict(page="CCTV Carousel") @expose('jistdocstore.templates.cctv.cctvinternalcams_grid') def cctvinternalcams_grid(self): return dict(page="CCTV Grid View") @expose('jistdocstore.templates.cctv.cctvinternalcams_carousel') def cctvinternalcams_carousel(self): return dict(page="CCTV Carousel") @expose() #@validate(test_form, error_handler=form_show) def form_submit(self, **kw): return 'Thanks: {name} {surname}'.format(**kw) @expose('jistdocstore.templates.cctv.jistcams_single') def view_single_cam_jist(self, **kw): #for k, w in kw.iteritems(): # print k, w #return imgtag = "<img class='cctv_img_small' src=" httptag = "http://*****:*****@" iptag = "jisttrading.no-ip.org:10091" cgitag = "/cgi-bin/faststream.jpg?" pic_cgi = "/cgi-bin/image.jpg?size=100x75&quality=60" #imgsrc = imgtag + httptag + iptag + cgitag + params html1 = '' camimglist = [] for cam in camsmobotix: rnd = random.random() rnd = str(rnd).split('.')[1] iptag = cam params = "stream=full&fps=1.0&error=picture&dummy=" + str( rnd) valuetag = httptag + iptag + cgitag + params imgsrc = httptag + iptag + pic_cgi camimglist.append({ 'src': imgsrc, 'value': httptag + iptag + cgitag }) return dict(page='Single Camera View', camimg_srclist=camimglist) @expose('jistdocstore.templates.cctv.jistcams_single') def view_single_cam_jistfamily_home(self, **kw): #for k, w in kw.iteritems(): # print k, w #return imgtag = "<img class='cctv_img_small' src=" httptag = "http://*****:*****@" iptag = "jistfamily.dyndns.org:10090" cgitag = "/cgi-bin/faststream.jpg?" pic_cgi = "/cgi-bin/image.jpg?size=100x75&quality=60" #imgsrc = imgtag + httptag + iptag + cgitag + params html1 = '' camimglist = [] for cam in camsjistfamily: rnd = random.random() rnd = str(rnd).split('.')[1] iptag = cam params = "stream=full&fps=1.0&error=picture&dummy=" + str( rnd) valuetag = httptag + iptag + cgitag + params imgsrc = httptag + iptag + pic_cgi camimglist.append({ 'src': imgsrc, 'value': httptag + iptag + cgitag }) return dict(page='JIST Family Home Camera View', camimg_srclist=camimglist) @expose() def view_single_cam_jist_ajax(self, **kw): #for k, w in kw.iteritems(): #print k, w rnd = random.random() rnd = str(rnd).split('.')[1] src = kw['src'] imgtag = "<img class='cctv_main' src=" + src #httptag = "http://*****:*****@" #iptag = "jisttrading.no-ip.org:10091" cgitag = "/cgi-bin/faststream.jpg?" #pic_cgi = "/cgi-bin/image.jpg?size=100x75&quality=60" #imgsrc = imgtag + httptag + iptag + cgitag + params params = "stream=full&fps=1.0&error=picture&dummy=" + str( rnd) html = imgtag + cgitag + params + '/>' return html @expose() def indexold(self): redirect('cctvcont/menu') @expose('jistdocstore.templates.cctv.camconnected') def view_connect_came_dir(self, **named): """Handle the 'cam connected' page.""" from tg.decorators import paginate return dict( selfname='view_connected_came_dir', src='192.168.0.11:8080', page='View Connected Server Directory', ) @expose('jistdocstore.templates.cctv.viewaxiscam') @require(in_any_group("managers", )) def viewaxiscam(self): cam1 = camsaxis[0] cam1_stream_src = "http://%s/control/faststream.jpg?stream=full&fps=10.0&dummy=1804289385" % cam1 cams = self.setup5camtopbar() return dict(page='Axis Camera View', cam1=cam1_stream_src, cam2=cams[0], cam3=cams[1], cam4=cams[2], cam5=cams[3], cam6=cams[4], selfname="viewaxiscam") @expose('jistdocstore.templates.cctv.viewvivotekcam') @require(in_any_group("managers", )) def viewvivotekcam(self): cam1 = camsvivotek[0] cam1_stream_src = "http://%s/control/faststream.jpg?stream=full&fps=10.0&dummy=1804289385" % cam1 cams = self.setup5camtopbar() return dict(page='Vivotek Camera View', cam1=cam1_stream_src, cam2=cams[0], cam3=cams[1], cam4=cams[2], cam5=cams[3], cam6=cams[4], selfname="viewvivotekcam") @expose('jistdocstore.templates.cctv.fastframe') @require(in_any_group("managers", )) def getfastframe(self): cam1 = camsmobotix[0] cam1_stream_src = "http://%s/control/faststream.jpg?stream=full&fps=10.0&dummy=1804289385" % cam1 cams = self.setup5camtopbar() return dict(page='Mobotix Camera View', cam1=cam1_stream_src, cam2=cams[0], cam3=cams[1], cam4=cams[2], cam5=cams[3], cam6=cams[4], selfname="getfastframe") @expose('jistdocstore.templates.cctv.getanycam') @require(in_any_group("managers", )) def getanycam(self, thiscamip=None, cambrand=None): if not thiscamip: cam1 = camsmobotix[0] cam1_stream_src = "http://%s/control/faststream.jpg?stream=full&fps=10.0&dummy=1804289385" % cam1 else: cam1 = thiscamip if cambrand == "mob": cam1_stream_src = "http://%s/control/faststream.jpg?stream=full&fps=10.0&dummy=1804289385" % cam1 elif cambrand == "axi": cam1_stream_src = "http://%s/axis-cgi/mjpg/video.cgi?" % cam1 elif cambrand == "viv": cam1_stream_src = "http://%s/video.mjpg" % cam1 else: pass cams = self.setup5camtopbar() return dict(page='Mobotix,Axis,Vivotek Camera View', cam1=cam1_stream_src, cam2=cams[0], cam3=cams[1], cam4=cams[2], cam5=cams[3], cam6=cams[4], selfname="getanycam") expose() def setup5sidebarbar(self): cam2 = camsmobotix[1] cam2_stream_src = "http://%s/control/faststream.jpg?stream=full&fps=10.0&dummy=1804289385" % cam2 cam3 = camsmobotix[2] cam3_stream_src = "http://%s/control/faststream.jpg?stream=full&fps=10.0&dummy=1804289385" % cam3 cam4 = camsmobotix[3] cam4_stream_src = "http://%s/control/faststream.jpg?stream=full&fps=10.0&dummy=1804289385" % cam4 cam5 = camsaxis[0] cam5_stream_src = "http://%s/axis-cgi/mjpg/video.cgi?" % cam5 cam6 = camsvivotek[0] cam6_stream_src = "http://%s/video.mjpg" % cam6 return (cam2_stream_src, cam3_stream_src, cam4_stream_src, cam5_stream_src, cam6_stream_src) expose() def setup5camtopbar(self): cam2 = camsmobotix[1] cam2_stream_src = "http://%s/control/faststream.jpg?stream=full&fps=10.0&dummy=1804289385" % cam2 cam3 = camsmobotix[2] cam3_stream_src = "http://%s/control/faststream.jpg?stream=full&fps=10.0&dummy=1804289385" % cam3 cam4 = camsmobotix[3] cam4_stream_src = "http://%s/control/faststream.jpg?stream=full&fps=10.0&dummy=1804289385" % cam4 cam5 = camsaxis[0] cam5_stream_src = "http://%s/axis-cgi/mjpg/video.cgi?" % cam5 cam6 = camsvivotek[0] cam6_stream_src = "http://%s/video.mjpg" % cam6 return (cam2_stream_src, cam3_stream_src, cam4_stream_src, cam5_stream_src, cam6_stream_src)
class LoadDataControllers(TGController): allow_only = in_any_group( 'voter', 'managers', msg=l_('Only for people with the "manage" permission')) #has_any_permission('manage','creator', msg=l_('Only for people with the "manage" permission')) def __init__(self, models, session, config_type=None, translations=None): self.utility = Utility() self.model = models # self.SearchGridObject = SearchGridObject(**kw) # search=self.SearchGridObject.searchPhrase @expose('json') def getdatainvittation(self, **kw): user = request.identity['user'] self.SearchGridObject = SearchGridObject(**kw) values, total = self.model.Invitation.getByUser( search=self.SearchGridObject.searchPhrase, userid=user.user_id, page=(int(kw['current']) - 1), page_size=int(kw['rowCount'])) return dict(current=kw['current'], rowCount=kw['rowCount'], total=total, rows=values) @expose('json') def getdataproject(self, **kw): user = request.identity['user'] self.SearchGridObject = SearchGridObject(**kw) values, total = self.model.QuestionProject.getFieldByUser( search=self.SearchGridObject.searchPhrase, userid=user.user_id, page=(int(kw['current']) - 1), page_size=int(kw['rowCount'])) return dict(current=kw['current'], rowCount=kw['rowCount'], total=total, rows=values) @expose('json') def getdatapublication(self, **kw): self.SearchGridObject = SearchGridObject(**kw) values, total = self.model.QuestionOption.getByProject( search=self.SearchGridObject.searchPhrase, idProject=kw['id'], page=(int(kw['current']) - 1), page_size=int(kw['rowCount'])) return dict(current=kw['current'], rowCount=kw['rowCount'], total=total, rows=values) @expose('json') def getdatavoter(self, **kw): user = request.identity['user'] self.SearchGridObject = SearchGridObject(**kw) print user.user_id data, total = self.model.Voter.getListVoterByOwner( search=self.SearchGridObject.searchPhrase, user_id_owner=user.user_id, page=(int(kw['current']) - 1), page_size=int(kw['rowCount'])) return dict(current=kw['current'], rowCount=kw['rowCount'], total=total, rows=data)
def can_be_administered(self): return predicates.in_any_group(self.admin).check_authorization(request.environ)
def fetch(report_type, page, rows): ''' Fetch data, group by department, user Called (indirectly) by jqGrid Returns JSON ''' if not in_any_group('admin', 'DG', 'COMPTA', 'CDS', 'Utilisateurs'): flash(u'Accès interdit') redirect('/') # Try and use grid preference grid_rows = session.get('grid_rows', None) if rows=='-1': # Default value rows = grid_rows if grid_rows is not None else 25 # Save grid preference session['grid_rows'] = rows session.save() rows = int(rows) try: page = int(page) rows = int(rows) offset = (page-1) * rows except: offset = 0 page = 1 rows = 25 global phones_dict global filtered_cdrs cdrs = filtered_cdrs log.debug('fetch ' + str(filtered_cdrs)) total = cdrs.count() / rows + 1 cdrs = cdrs.order_by(CDR.department, CDR.user) if report_type=='detail': cdrs = cdrs.order_by(CDR.calldate.desc()) cdrs = cdrs.offset(offset).limit(rows) old_u = old_d = '' sec_tot = ht_tot = ttc_tot = 0 data = [] d_id2name = dict([(d.dptm_id, u'%s (%s)' % (d.name, d.comment)) \ for d in DBSession.query(Department)]) u_id2name = dict([(u.user_id, u'%s (%s)' % (u.display_name, u.phone[0].exten if u.phone else '')) \ for u in DBSession.query(User)]) for cdr in cdrs.all(): d = d_id2name.get(cdr.department, u'Inconnu') u = u_id2name.get(cdr.user, u'Inconnu') if u==old_u: u='' else: old_u=u if d!=old_d: # Next departement if old_d: # Add sub total per department data.append({ 'id': 'total_%s' % d, 'cell': [None, u'TOTAL SERVICE', f_bill(sec_tot), f_cost(ht_tot), f_cost(ttc_tot) ]}) if report_type=='detail': data[-1]['cell'].insert(2, None) data[-1]['cell'].insert(3, None) old_d=d sec_tot = ht_tot = ttc_tot = 0 # Header for new department data.append({ 'id': d, 'cell': [old_d, None, None, None, None] }) if report_type=='detail': data[-1]['cell'].insert(2, None) data[-1]['cell'].insert(3, None) sec_tot += cdr.billsec ht_tot += cdr.ht or 0 ttc_tot += cdr.ttc or 0 data.append({ 'id': cdr.user, 'cell': [None, u, f_bill(cdr.billsec), f_cost(cdr.ht), f_cost(cdr.ttc) ] }) if report_type=='detail': # Hide destination for privacy data[-1]['cell'].insert(2, cdr.calldate) data[-1]['cell'].insert(3, cdr.dst[:3] + '***') data.append({ 'id': 'total_%s' % old_d, 'cell': [None, u'TOTAL SERVICE', f_bill(sec_tot), f_cost(ht_tot), f_cost(ttc_tot) ]}) if report_type=='detail': data[-1]['cell'].insert(2, None) data[-1]['cell'].insert(3, None) return dict(page=page, total=total, rows=data)
def stats(self, cmp_id): p = DBSession.query(Campaign).get(cmp_id) # User must be admin or queue supervisor sv = ['admin'] for q in Globals.asterisk.queues: sv.append('SV ' + q) if not in_any_group(*sv): tmpl_context.grid = None flash(u'Accès interdit !', 'error') else: tmpl_context.grid = MyJqGrid( id='grid', url='stats_fetch', caption=u'Statitiques', colNames = [ u'Agent', u'RDV', u'\u00C0 rappeler', u'Contact direct. son CC / réflechit', u'Pas intéressé coupe court', u'Appels aboutis', u'Absent', u'Décédé', u'Faux numéro/ Aucun numéro', u'Injoi- gnable', u'Appels non aboutis', u'Hors cible', u'Réclam.', u'Total fiches clients traitées'], colModel = [ { 'width': 40, 'sortable': False, 'search': False }, { 'width': 40, 'sortable': False, 'search': False }, { 'width': 40, 'sortable': False, 'search': False }, { 'width': 40, 'sortable': False, 'search': False }, { 'width': 40, 'sortable': False, 'search': False }, { 'width': 40, 'sortable': False, 'search': False }, { 'width': 40, 'sortable': False, 'search': False }, { 'width': 40, 'sortable': False, 'search': False }, { 'width': 40, 'sortable': False, 'search': False }, { 'width': 40, 'sortable': False, 'search': False }, { 'width': 40, 'sortable': False, 'search': False }, { 'width': 40, 'sortable': False, 'search': False }, { 'width': 40, 'sortable': False, 'search': False }, { 'width': 40, 'sortable': False, 'search': False }, ], # sortname = 'name', postData = {'cmp_id': cmp_id}, navbuttons_options = {'view': False, 'edit': False, 'add': False, 'del': False, 'search': False, 'refresh': True, } ) first = datetime(2222, 12, 31) last = datetime(2000, 1, 1) for c in p.customers: # For all customers in this campaign for o in c.outcalls: # For all calls to these customers if first > o.created: first = o.created if last < o.created: last = o.created tmpl_context.form = None return dict(title=u"Statistiques campagne %s" % p.name, debug='', csv_href = {'href': 'csv?cmp_id=%s' % cmp_id}, first_last=u'Premier appel %s, dernier appel %s.' % ( first.strftime('%A %d %B %Y à %Hh%Mm%Ss').decode('utf-8'), last.strftime('%A %d %B %Y à %Hh%Mm%Ss').decode('utf-8')))
class PublicationController(TGController): allow_only = in_any_group( 'voter', 'managers', msg=l_('Only for people with the "manage" permission')) #has_any_permission('manage','creator', msg=l_('Only for people with the "manage" permission')) def __init__(self, models, session, config_type=None, translations=None): self.utility = Utility() self.model = models print "call init LoadDataControllers" print self.model @expose('managepoll.templates.publication.index') def index(self, **kw): print kw return dict(page='index', idproject=kw['idproject']) @expose() def deletepublication(self, **kw): print kw status, message = self.model.QuestionOption.deleteById(kw['idoption']) print status print message redirect('/managepoll/publication/indextest', params={'idproject': kw['idproject']}) @expose('managepoll.templates.publication.publication') def publication(self, **kw): reload(sys).setdefaultencoding( 'utf8') #set ค่า เป็น utf8 สำหรับฟังชั่นนี้ user = request.identity['user'] questionoption = self.model.QuestionOption() questionoption.id_question_project = kw['idproject'] questionoption.activate_date = datetime.today() #today for add option questionoption.expire_date = self.utility.plusDate( datetime.today(), 30) #plusDate30day for add option emailtemplate = self.model.Invitation() randomtype = self.model.RandomType() closetype = self.model.CloseType() questionthem = self.model.QuestionTheme() if ('idoption' in kw): print "Edit option" questionoption = self.model.QuestionOption.getId(kw['idoption']) questionthem = self.model.QuestionTheme.getAll(act=1) closetype = self.model.CloseType.getAll(active=1) randomtype = self.model.RandomType.getAll(active=1) emailtemplate, total = self.model.Invitation.getByUser(user.user_id) return dict(page='publication', questionoption=questionoption, emailtemplate=emailtemplate, randomtype=randomtype, closetype=closetype, questionthem=questionthem, idproject=kw['idproject']) @expose() def savepublication(self, **kw): print kw reload(sys).setdefaultencoding('utf8') questionoption = self.model.QuestionOption(**kw) print questionoption.show_navigator print questionoption.show_score print questionoption.random_answer questionoption.activate_date = self.utility.startDate( questionoption.activate_date) questionoption.expire_date = self.utility.finishDate( questionoption.expire_date) questionoption.show_score = self.utility.convertToBit( questionoption.show_score) questionoption.show_navigator = self.utility.convertToBit( questionoption.show_navigator) questionoption.id_question_option = self.utility.setIfEmpty( questionoption.id_question_option) questionoption.random_answer = self.utility.convertToBit( questionoption.random_answer) print "show_navigator : %s" % questionoption.show_navigator print "show_score : %s" % questionoption.show_score print "random_answer : %s" % questionoption.random_answer if self.utility.isEmpty(questionoption.id_question_option): questionoption.save() else: questionoption.updateall() redirect('/managepoll/publication/indextest', params={'idproject': questionoption.id_question_project}) @expose('managepoll.templates.publication.indextest') def indextest(self, **kw): print kw return dict(page='indextest', idproject=kw['idproject']) @expose('managepoll.templates.publication.publicationtest') def publicationtest(self, **kw): reload(sys).setdefaultencoding( 'utf8') #set ค่า เป็น utf8 สำหรับฟังชั่นนี้ user = request.identity['user'] questionoption = self.model.QuestionOption() questionoption.id_question_project = kw['idproject'] questionoption.activate_date = datetime.today() #today for add option questionoption.expire_date = self.utility.plusDate( datetime.today(), 30) #plusDate30day for add option emailtemplate = self.model.Invitation() randomtype = self.model.RandomType() closetype = self.model.CloseType() questionthem = self.model.QuestionTheme() if ('idoption' in kw): print "Edit option" questionoption = self.model.QuestionOption.getId(kw['idoption']) questionthem = self.model.QuestionTheme.getAll(act=1) closetype = self.model.CloseType.getAll(active=1) randomtype = self.model.RandomType.getAll(active=1) emailtemplate, total = self.model.Invitation.getByUser( userid=user.user_id) return dict(page='publicationtest', questionoption=questionoption, emailtemplate=emailtemplate, randomtype=randomtype, closetype=closetype, questionthem=questionthem, idproject=kw['idproject'])
def test_user_belongs_to_groups(self): environ = make_environ('gustavo', ['developers', ' admins']) p = predicates.in_any_group('developers', 'admins') self.eval_met_predicate(p, environ)
class UserRestController(TIMRestController): """ CRUD Controller allowing to manage Users """ allow_only = predicates.in_any_group(Group.TIM_MANAGER_GROUPNAME, Group.TIM_ADMIN_GROUPNAME) password = UserPasswordAdminRestController() profile = UserProfileAdminRestController() workspaces = UserWorkspaceRestController() @classmethod def current_item_id_key_in_context(cls): return 'user_id' @tg.require(predicates.in_group(Group.TIM_MANAGER_GROUPNAME)) @tg.expose('tracim.templates.admin.user_getall') def get_all(self, *args, **kw): current_user = tmpl_context.current_user api = UserApi(current_user) users = api.get_all() current_user_content = Context(CTX.CURRENT_USER).toDict(current_user) fake_api = Context(CTX.USERS).toDict( {'current_user': current_user_content}) dictified_users = Context(CTX.USERS).toDict(users, 'users', 'user_nb') return DictLikeClass(result=dictified_users, fake_api=fake_api) @tg.require(predicates.in_group(Group.TIM_MANAGER_GROUPNAME)) @tg.expose() def post( self, name: str, email: str, password: str, is_tracim_manager: str = 'off', is_tracim_admin: str = 'off', send_email: str = 'off', ): is_tracim_manager = h.on_off_to_boolean(is_tracim_manager) is_tracim_admin = h.on_off_to_boolean(is_tracim_admin) send_email = h.on_off_to_boolean(send_email) current_user = tmpl_context.current_user if current_user.profile.id < Group.TIM_ADMIN: # A manager can't give large rights is_tracim_manager = False is_tracim_admin = False api = UserApi(current_user) if api.user_with_email_exists(email): tg.flash( _('A user with email address "{}" already exists.').format( email), CST.STATUS_ERROR) tg.redirect(self.url()) user = api.create_user() user.email = email user.display_name = name if password: user.password = password elif send_email: # Setup a random password to send email at user password = str(uuid.uuid4()) user.password = password user.webdav_left_digest_response_hash = '%s:/:%s' % (email, password) api.save(user) # Now add the user to related groups group_api = GroupApi(current_user) user.groups.append(group_api.get_one(Group.TIM_USER)) if is_tracim_manager: user.groups.append(group_api.get_one(Group.TIM_MANAGER)) if is_tracim_admin: user.groups.append(group_api.get_one(Group.TIM_ADMIN)) api.save(user) if send_email: email_manager = get_email_manager() email_manager.notify_created_account(user, password=password) tg.flash( _('User {} created.').format(user.get_display_name()), CST.STATUS_OK) tg.redirect(self.url()) @tg.expose('tracim.templates.admin.user_getone') def get_one(self, user_id): current_user = tmpl_context.current_user api = UserApi(current_user) # role_api = RoleApi(tg.tmpl_context.current_user) # user_api = UserApi(tg.tmpl_context.current_user) user = api.get_one(user_id) # FIXME role_api = RoleApi(tg.tmpl_context.current_user) role_list = role_api.get_roles_for_select_field() dictified_user = Context(CTX.ADMIN_USER).toDict(user, 'user') current_user_content = Context(CTX.CURRENT_USER).toDict( tmpl_context.current_user) fake_api_content = DictLikeClass(current_user=current_user_content, role_types=role_list) fake_api = Context(CTX.ADMIN_USER).toDict(fake_api_content) return DictLikeClass(result=dictified_user, fake_api=fake_api) @tg.expose('tracim.templates.admin.user_edit') def edit(self, id): current_user = tmpl_context.current_user api = UserApi(current_user) user = api.get_one(id) dictified_user = Context(CTX.USER).toDict(user, 'user') return DictLikeClass(result=dictified_user) @tg.require(predicates.in_group(Group.TIM_MANAGER_GROUPNAME)) @tg.expose() def put(self, user_id, name, email, next_url=''): api = UserApi(tmpl_context.current_user) user = api.get_one(int(user_id)) api.update(user, name, email, True) tg.flash( _('User {} updated.').format(user.get_display_name()), CST.STATUS_OK) if next_url: tg.redirect(next_url) tg.redirect(self.url()) @tg.require(predicates.in_group(Group.TIM_ADMIN_GROUPNAME)) @tg.expose() def enable(self, id, next_url=None): current_user = tmpl_context.current_user api = UserApi(current_user) user = api.get_one(id) user.is_active = True api.save(user) tg.flash( _('User {} enabled.').format(user.get_display_name()), CST.STATUS_OK) if next_url == 'user': tg.redirect(self.url(id=user.user_id)) tg.redirect(self.url()) @tg.require(predicates.in_group(Group.TIM_ADMIN_GROUPNAME)) @tg.expose() def disable(self, id, next_url=None): id = int(id) current_user = tmpl_context.current_user api = UserApi(current_user) if current_user.user_id == id: tg.flash(_('You can\'t de-activate your own account'), CST.STATUS_ERROR) else: user = api.get_one(id) user.is_active = False api.save(user) tg.flash( _('User {} disabled').format(user.get_display_name()), CST.STATUS_OK) if next_url == 'user': tg.redirect(self.url(id=user.user_id)) tg.redirect(self.url()) @tg.require(predicates.in_group(Group.TIM_USER_GROUPNAME)) @tg.expose('tracim.templates.user_profile') def me(self): current_user = tmpl_context.current_user current_user_content = Context(CTX.CURRENT_USER).toDict(current_user) fake_api = Context(CTX.ADMIN_WORKSPACE).toDict( {'current_user': current_user_content}) return DictLikeClass(fake_api=fake_api)
class InvitationController(TGController): allow_only = in_any_group( 'voter', 'managers', msg=l_('Only for people with the "manage" permission')) #has_any_permission('manage','creator',msg=l_('Only for people with the "manage" permission')) def __init__(self, models, session, config_type=None, translations=None): self.utility = Utility() self.model = models #@require(predicates.in_any_group('creator','managers', msg=l_('Only for creator'))) @expose('managepoll.templates.invitation.index') def index(self, **kw): user = request.identity['user'] print user.user_id return dict(page='index', idproject=None) @expose('managepoll.templates.invitation.invitation') def invitation(self, **kw): print kw reload(sys).setdefaultencoding("utf-8") invitation = self.model.Invitation() self.emailtemplate = self.model.EmailTemplate() if ('idinvitation' in kw): print kw['idinvitation'] # invitation = self.model.Invitation.getId(kw['idinvitation']) else: self.emailtemplate = self.model.EmailTemplate.getTemplateBy(5) invitation.name_content = self.emailtemplate.sender invitation.from_name = self.emailtemplate.sender invitation.subject = self.emailtemplate.subject invitation.content = self.emailtemplate.content_template return dict(page='invitation', invitation=invitation, idproject=None) @expose() def saveinvitation(self, **kw): user = request.identity['user'] reload(sys).setdefaultencoding('utf8') invitation = self.model.Invitation(**kw) invitation.user_id = user.user_id invitation.id_question_invitation = self.utility.setIfEmpty( invitation.id_question_invitation) if self.utility.isEmpty(invitation.id_question_invitation): print "save" invitation.save() else: print "update" invitation.updateall() redirect('/managepoll/invitation/indextest') @expose('managepoll.templates.invitation.indextest') def indextest(self, **kw): user = request.identity['user'] print user.user_id return dict(page='invitation', idproject=None) @expose('managepoll.templates.invitation.invitationtest') def invitationtest(self, **kw): print kw reload(sys).setdefaultencoding("utf-8") invitation = self.model.Invitation() self.emailtemplate = self.model.EmailTemplate() if ('idinvitation' in kw): print kw['idinvitation'] # invitation = self.model.Invitation.getId(kw['idinvitation']) else: self.emailtemplate = self.model.EmailTemplate.getTemplateBy(5) invitation.name_content = self.emailtemplate.sender invitation.from_name = self.emailtemplate.sender invitation.subject = self.emailtemplate.subject invitation.content = self.emailtemplate.content_template return dict(page='invitationtest', invitation=invitation, idproject=None) @expose() def deleteinvitation(self, **kw): print kw self.model.Invitation.deleteById(kw['idinvitation']) redirect('/managepoll/invitation/indextest')
class ProjectController(TGController): allow_only = in_any_group( 'voter', 'managers', msg=l_('Only for people with the "manage" permission')) def __init__(self, models, session, config_type=None, translations=None): super(ProjectController, self).__init__() self.model = models self.utility = Utility() @expose('managepoll.templates.project.index') def index(self, **kw): questionprojecttype = self.model.QuestionProjectType.getAll(1) return dict(page='index', projecttype=questionprojecttype, idproject=None) @expose() def saveproject(self, **kw): user = request.identity['user'] questionproject = self.model.QuestionProject(**kw) questionproject.user_id = user.user_id questionproject.save() redirect('/managepoll/project/edit', params={'idproject': questionproject.id_question_project}) @expose() def delete(self, **kw): print 'Delete : Project ID :', kw['idproject'] self.models.QuestionProject.deleteById(kw['idproject']) redirect('/index') @expose('managepoll.templates.project.manageproject') def edit(self, **kw): print '......................' print kw questionproject = self.model.QuestionProject() if ('idproject' in kw): questionproject = self.model.QuestionProject.getId(kw['idproject']) else: print "don't have kw" #g = model.QuestionProjectType.getAll(act = 1) questionType = self.model.QuestionType.getAll(act=1) return dict(page='edit', questionproject=questionproject, questionType=questionType, idproject=kw['idproject']) @expose('json') def savequestion(self, **kw): projectObject = ProjectObject() projectObject.checkQuestion(**kw) return dict(idproject=projectObject.idproject) @expose('managepoll.templates.project.indextest') def indextest(self, **kw): questionprojecttype = self.model.QuestionProjectType.getAll(1) return dict(page='indextest', projecttype=questionprojecttype, idproject=None) @expose('managepoll.templates.project.edittest') def edittest(self, **kw): print '......................' print kw questionproject = self.model.QuestionProject() if ('idproject' in kw): questionproject = self.model.QuestionProject.getId(kw['idproject']) else: print "don't have kw" #g = model.QuestionProjectType.getAll(act = 1) questionType = self.model.QuestionType.getAll(act=1) return dict(page='edittest', questionproject=questionproject, questionType=questionType, idproject=kw['idproject'])
def test_user_doesnt_belong_to_one_group(self): environ = make_environ('gustavo', ['designers']) p = predicates.in_any_group('developers', 'designers') self.eval_met_predicate(p, environ)
def test_user_belongs_to_groups(self): environ = make_environ('gustavo', ['developers',' admins']) p = predicates.in_any_group('developers', 'admins') self.eval_met_predicate(p, environ)
def index(self, selected=None, daily=None): if not in_any_group('admin','STATS'): flash(u'Accès interdit !', 'error') redirect('/') if daily: log.info('stats_type <- %s' % daily) self.stats_type = daily (m,d,y) = daily.split('/') title = u'Statistiques quotidiennes de %s %s' % (month_name[int(m)-1], y) flot_label = u'Appels quotidiens (%s %s)' % (month_name[int(m)-1], y) last_day = monthrange(int(y),int(m))[1] row_list = [last_day, 15, 10, 5] else: self.stats_type = None title = u'Statistiques mensuelles' flot_label = u'Appels mensuels' row_list = [12, 18, 24, 30, 36, 48, 60, 120] # Data grid tmpl_context.data_grid = MyJqGrid( id='data_grid', url='/stats/fetch', caption=u"Valeurs", sortname='name', sortorder='desc', colNames = [u'Jour' if daily else u'Mois', u'Appels', u'Durée'], colModel = [ { 'name': 'date', 'width': 60, 'sortable': True}, { 'name': 'calls', 'width': 40, 'align': 'right', 'sortable': True}, { 'name': 'billsec', 'width': 40, 'align': 'right', 'sortable': True} ], navbuttons_options = {'view': False, 'edit': False, 'add': False, 'del': False, 'search': False, 'refresh': True, }, loadComplete = js_callback('load_complete'), rowNum = row_list[0], rowList = row_list, ) # Hidden form for daily stats tmpl_context.form = Form( name = 'stats_form', submit_text = None, hover_help = True, fields = [ HiddenField(name='daily',default=self.stats_type), ] ) log.info('stats_type -> %s' % self.stats_type) # Plot: data are gathered from the grid, through javscript, cf. stats.html tmpl_context.data_flot = FlotWidget( data = [ { 'data': [], 'label': u'Appels mensuels' }, ], options = { 'grid': { 'backgroundColor': '#fffaff', 'clickable': True, 'hoverable': True}, 'xaxis': { 'ticks': []} }, height = '300px', width = '600px', label = flot_label, id='data_flot' ) # Hourly grid tmpl_context.hourly_grid = MyJqGrid( id='hourly_grid', url='/stats/fetch_hourly', caption=u'Valeurs horaires', sortname='name', sortorder='desc', colNames = [u'Tranche horaire', u'Appels', u'Durée'], colModel = [ { 'name': 'date', 'width': 60, 'sortable': False}, { 'name': 'calls', 'width': 40, 'align': 'right', 'sortable': False}, { 'name': 'billsec', 'width': 40, 'align': 'right', 'sortable': False} ], navbuttons_options = {'view': False, 'edit': False, 'add': False, 'del': False, 'search': False, 'refresh': True, }, loadComplete = js_callback('load_hourly_complete'), rowNum = 24, rowList = [12,24], ) # Plot: data are gathered from the grid, through javscript, cf. stats.html tmpl_context.hourly_flot = FlotWidget( data = [ { 'data': [], 'label': u'Distribution horaire' }, ], options = { 'grid': { 'backgroundColor': '#fffaff', 'clickable': True, 'hoverable': True}, 'xaxis': { 'ticks': []} }, height = '300px', width = '600px', label = flot_label, id='hourly_flot' ) # Inject javascript for tabs from tw.jquery.ui import ui_tabs_js ui_tabs_js.inject() return dict( title=title, debug=False, values={})
def csv(self, **kw): if not in_any_group('admin', 'STATS'): flash(u'Accès interdit') redirect('/') today = datetime.datetime.today() filename = 'statistiques-' + today.strftime('%Y%m%d') + '.csv' import StringIO import csv csvdata = StringIO.StringIO() writer = csv.writer(csvdata) # Global headers if self.stats_type: rt = 'quotidien ' + self.stats_type[0:2] + self.stats_type[5:] col1 = 'Jour' else: rt = 'mensuel' col1 = 'Mois' writer.writerow(['Statistiques SVI']) writer.writerow(['Date', today.strftime('%d/%m/%Y')]) writer.writerow(['Type de rapport', rt]) writer.writerow([]) cols = [col1] if self.stats_type: # Daily stats d = datetime.datetime.strptime(self.stats_type, '%m/%d/%Y') if db_engine=='oracle': req = func.trunc(CDR.calldate, 'J') else: # PostgreSql req = func.date_trunc('day', CDR.calldate) else: # Monthly stats if db_engine=='oracle': req = func.trunc(CDR.calldate, 'month') else: # PostgreSql req = func.date_trunc('month', CDR.calldate) # Order by date cdrs = self.stats_req cdrs = cdrs.order_by(req) cols.append( (u'Appels\n(nombre)').encode('utf-8') ) cols.append( (u'Appels\n(durée)').encode('utf-8') ) writer.writerow(cols) for c in cdrs.all(): row = [] if self.stats_type: row.append(c[0].strftime('%d')) else: row.append(c[0].strftime('%m/%Y')) row.append(c[1]) row.append(hms(c[2])) writer.writerow(row) rh = response.headers rh['Content-Type'] = 'text/csv; charset=utf-8' rh['Content-Disposition'] = str( (u'attachment; filename="%s"' % ( filename)).encode('utf-8') ) rh['Pragma'] = 'public' # for IE rh['Cache-control'] = 'max-age=0' #for IE return csvdata.getvalue()
class VoterController(TGController): allow_only = in_any_group('voter', 'managers', msg=l_('Only for people with the "manage" permission')) #has_any_permission('manage','creator', msg=l_('Only for people with the "manage" permission')) def __init__(self, models, session, config_type=None, translations=None): print "call VoterController(managepoll)" self.utility = Utility() self.model = models @expose('managepoll.templates.voter.index') def index(self): return dict(page = 'index',idproject=None) @expose('managepoll.templates.voter.voter') def voters(self,*args,**kw): reload(sys).setdefaultencoding('utf8') voterObject = VoterObject() print kw if('idvoter' in kw): print kw print "Edit voter" voter = self.model.Voter.getId(kw['idvoter']) voterObject.setVoter(voter) #employment = model.EmploymentDetail.getId(kw['idvoter']) print "voters : lang" self.lang = self.model.Languages.getAll() print self.lang self.marriageStatus = self.model.MarriageStatus.getAll(act=1) self.gender = self.model.Gender.getAll(act=1) self.tel = self.model.TelephoneType.getAll(act=1) self.religion = self.model.ReligionType.getAll(act=1) self.national = self.model.NationalityType.getAll(act=1) self.race = self.model.RaceType.getAll(act=1) self.condition = self.model.LivingConditionType.getAll(act=1) self.employmentstatus = self.model.EmploymentType.getAll(act=1) self.listConutry = self.model.FixCountry.getAll(active=1) self.telephone = self.model.TelephoneType.getAll(act=1) self.education = self.model.EducationType.getAll(act=1) self.addresstype = self.model.AddressType.getAll(act=1) return dict(page = 'voters', lang = self.lang, marriageStatus = self.marriageStatus, gender = self.gender, tel = self.tel, religion = self.religion, national = self.national, race = self.race, condition = self.condition, employmentstatus = self.employmentstatus, listConutry = self.listConutry, telephone = self.telephone, education = self.education, addresstype = self.addresstype, voter = voterObject, idproject=None) @expose() def savevoter(self,**kw): print kw user = request.identity['user']; print "********************" print kw['id_voter'] print kw['id_voter_map_type'] print kw['id_telephone'] print kw['id_address'] print kw['id_employment'] print "********************" voter = self.model.Voter.getId(kw['id_voter']) if voter is None : print "voter is none" voter = self.model.Voter() voter.email = kw['email'] voter.prefix = kw['prefix'] voter.firstname = kw['firstname'] voter.lastname = kw['lastname'] voter.id_marriage_status = kw['id_marriage_status'] #voter.birthdate = kw['birthdate'] voter.birthdate = self.utility.convertToDateTime(kw['birthdate'], '%d/%m/%Y') voter.id_gender = kw['id_gender'] voter.id_living_condition = kw['id_living_condition'] voter.size_family = kw['size_family'] voter.id_language = kw['id_language'] voter.id_religion = kw['id_religion'] voter.id_nationality = kw['id_nationality'] voter.id_race = kw['id_race'] voter.salary = kw['salary'] voter.id_education = kw['id_education'] voter.user_id_owner = user.user_id print "va %s" % (str( len(kw['id_voter']))) if (len(kw['id_voter']) == 0) : voter.save() print "Voter id : %s" %voter.id_voter votermaptype = self.model.VoterMapType.getId(kw['id_voter_map_type']) if votermaptype is None : votermaptype = self.model.VoterMapType() votermaptype.id_voter = voter.id_voter votermaptype.id_voter_type = 5 if (len(kw['id_voter_map_type'] ) == 0): votermaptype.save() print "voter map type id : %s" %votermaptype.id_voter_map_type votertelephone = self.model.Telephone.getId(kw['id_telephone']) if votertelephone is None: votertelephone = self.model.Telephone() votertelephone.id_telephone_type = kw['id_telephone_type'] votertelephone.description = kw['telephone'] votertelephone.id_voter = voter.id_voter if (len(kw['id_telephone'] ) == 0): votertelephone.save() print "telephone : %s" %votertelephone.id_telephone voteraddress = self.model.Address.getId(kw['id_address']) if voteraddress is None: voteraddress = self.model.Address() voteraddress.id_address_type = kw['id_address_type'] voteraddress.id_voter = voter.id_voter voteraddress.country = kw['id_country'] voteraddress.province = kw['province'] voteraddress.city = kw['city'] voteraddress.county = kw['county'] if (len(kw['id_address'] ) == 0): voteraddress.save() voteremployment = self.model.EmploymentDetail.getId(kw['id_employment']) if voteremployment is None: voteremployment = self.model.EmploymentDetail() voteremployment.id_voter = voter.id_voter voteremployment.id_employment_status_type = kw['id_employment_status_type'] voteremployment.intructry_type = kw['intructry_type'] voteremployment.job_catagory = kw['job_catagory'] if (len(kw['id_employment'] ) == 0): voteremployment.save() redirect('/managepoll/voter/indextest') @expose('managepoll.templates.voter.indextest') def indextest(self): return dict(page = 'voter',idproject=None) @expose('managepoll.templates.voter.votertest') def votertest(self,*args,**kw): print kw reload(sys).setdefaultencoding('utf8') voterObject = VoterObject() print kw if('idvoter' in kw): print kw print "Edit voter" voter = self.model.Voter.getId(kw['idvoter']) voterObject.setVoter(voter) #employment = model.EmploymentDetail.getId(kw['idvoter']) print "voters : lang" self.lang = self.model.Languages.getAll() print self.lang self.marriageStatus = self.model.MarriageStatus.getAll(act=1) self.gender = self.model.Gender.getAll(act=1) self.tel = self.model.TelephoneType.getAll(act=1) self.religion = self.model.ReligionType.getAll(act=1) self.national = self.model.NationalityType.getAll(act=1) self.race = self.model.RaceType.getAll(act=1) self.condition = self.model.LivingConditionType.getAll(act=1) self.employmentstatus = self.model.EmploymentType.getAll(act=1) self.listConutry = self.model.FixCountry.getAll(active=1) self.telephone = self.model.TelephoneType.getAll(act=1) self.education = self.model.EducationType.getAll(act=1) self.addresstype = self.model.AddressType.getAll(act=1) print "***************" print voterObject.birthdate return dict(page = 'votertest', lang = self.lang, marriageStatus = self.marriageStatus, gender = self.gender, tel = self.tel, religion = self.religion, national = self.national, race = self.race, condition = self.condition, employmentstatus = self.employmentstatus, listConutry = self.listConutry, telephone = self.telephone, education = self.education, addresstype = self.addresstype, voter = voterObject, idproject=None) @expose() def deletevoter(self,**kw): print kw self.model.Invitation.deleteById(kw['idinvitation']) redirect('/managepoll/invitation/indextest')
class ExtractionsController(BaseController): filter = ExtractionFilterController() @expose('etl.templates.extractions.index') @require(predicates.not_anonymous()) def index(self, **kw): categories = DBSession.query(app_model.Category).all() uncategorised = DBSession.query(Extraction).filter_by( category_id=None).all() categories += [Bunch(extractions=uncategorised, name="No Category")] return dict(categories=categories, has_validation_errors=request.validation.errors, new_form=CreateExtractionForm) @expose() @require(predicates.in_group('managers')) @validate(CreateExtractionForm, error_handler=index) def create(self, name, **kw): DBSession.add(Extraction(name=name)) flash('New Extraction successfully created', 'ok') return redirect('./index') @expose() @require(predicates.in_any_group('manager', 'admin')) def delete(self, uid): extraction = DBSession.query(Extraction).get(uid) or abort(404) DBSession.delete(extraction) flash('Extraction correctly deleted') return redirect(tg.url('/extractions')) @expose('etl.templates.extractions.view') @expose(content_type="text/csv") @expose(content_type='application/json') @require(predicates.Any(predicates.not_anonymous(), is_api_authenticated())) @validate( { 'extraction': Convert( lambda v: DBSession.query(Extraction).filter_by(uid=v).one()) }, error_handler=abort(404, error_handler=True)) def view(self, extraction, extraction_filter=None, **kw): try: result = extraction.perform() except Exception as e: log.exception('Failed to Retrieve Data') flash('ERROR RETRIEVING DATA: %s' % e, 'error') return redirect('/error') e_filter = None try: if extraction_filter: if int(extraction_filter ) != -1: # -1 = original extraction requested by user e_filter = DBSession.query(ExtractionFilter).get( extraction_filter) if not e_filter: return abort(404) result = e_filter.perform(result) else: default = DBSession.query(ExtractionFilter).filter( ExtractionFilter.default == True, ExtractionFilter.extraction_id == extraction.uid).first() if default: e_filter = default result = default.perform(result) except Exception as e: log.exception('Failed to Retrieve Data') flash('ERROR RETRIEVING DATA: %s' % e, 'error') result = DataFrame() if request.response_type == 'text/csv': return dateframe_to_csv(result) elif request.response_type == 'application/json': return dateframe_to_json(result) visualizations = dict( (name, None) for name in extraction.visualization.split('+')) axis = [] if extraction.graph_axis: axis = [x.strip() for x in extraction.graph_axis.split(',')] visualizations = get_graph(result, axis, visualizations) if config.get("extraction.max_elements") is None: log.warn( "Cannot find max elements to render in config file. Using default 10000" ) if len(result) * len(result.columns) > int( config.get("extraction.max_elements", 10000)): flash( "There are too many data to extract, please add some filters", "error") filters = DBSession.query(ExtractionFilter).filter_by( extraction_id=extraction.uid).all() return dict(extraction=extraction, visualizations=visualizations, columns=result.columns, results=result.itertuples(), count=len(result), filters=filters, extraction_filter=e_filter, py2=py_version < 3) @expose() def reload_data(self, extraction): extraction = DBSession.query(Extraction).get(extraction) or abort(404) for dts in extraction.datasets: empty_cache(dts.dataset.cache_key()) empty_cache(dts.dataset.cache_key(DEFAULT_LIMIT_FOR_PERFORMANCE)) flash('Data reloaded') return redirect('/extractions/view/' + str(extraction.uid))
class RootController(BaseController): """ The root controller for the jistdocstore application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() admin = AdminController(model, DBS_ContractData, config_type=TGAdminConfig) mngntcont = ManagementController() topmngntcont = TopManagementController() labourcont = LabourController() logisticscont = LogisticsController() marketingcont = MarketingController() productioncont = ProductionController() contractscont = ContractsController() estimatingcont = EstimatingController() vettingcont = VettingController() manufacturecont = ManufacturingController() transportcont = TransportController() fleetcont = FleetController() accountscont = AccountsController() invoicingcont = InvoicingController() receptioncont = ReceptionController() cctvcont = CCTVController() est5yreskomfencingcont = Estimating_5yr_Eskom_Fencing_Controller() est3yresspalisadecont = Estimating_3yr_Ess_Palisade_Controller() est3yresshsfcont = Estimating_3yr_Ess_HSF_Controller() error = ErrorController() def _before(self, *args, **kw): tmpl_context.project_name = "Jistdocstore" @expose('jistdocstore.templates.index') def index(self): """Handle the front-page.""" redirect('/myjistconsole') #return dict(page='index') @require( in_any_group("managers", "production", "marketing", "healthsafety", "logistics", "stores", "estimates")) @expose('jistdocstore.templates.myjistconsole') def myjistconsole(self, **named): """Handle the 'myjistconsole'.""" username = request.identity['repoze.who.userid'] usernow = User.by_user_name(username) myid = usernow.user_id activeusers = DBS_ContractData.query(User).filter( User.active_status == 1).all() contracts = DBS_ContractData.query(JistContracts).filter(JistContracts.completed=="False"). \ order_by(desc(JistContracts.jno)).all() pointlist = [] productionlist = [] accountslist = [] for point in activeusers: if point: if point.user_id == 1: pointlist.append({ 'user_id': point.user_id, 'user_name': point.user_name, 'display_name': point.display_name }) user = User.by_user_id(point.user_id) userpermissions = user.permissions for permis in userpermissions: #print permis.permission_name if permis.permission_name == 'productionmanage': pointlist.append({ 'user_id': point.user_id, 'user_name': point.user_name, 'display_name': point.display_name }) return dict(page='My JIST Console', contracts=contracts, users=activeusers, myjistid=myid, points=pointlist) @require( in_any_group("managers", "production", "marketing", "healthsafety", "logistics", "stores", "estimates")) @expose('jistdocstore.templates.mypoints') def mypoints(self, **named): """Handle the 'mypoints' page.""" tmpl_context.widget = spx_contracts_table value = mycontracts_filler.get_value(values={}, offset=0, order_by='jno', desc=True) count = len(value) page = int(named.get('page', '1')) currentPage = paginate.Page( value, page, item_count=count, items_per_page=15, ) items = currentPage.items #print currentPage #print currentPage.page #print currentPage.previous_page return dict(page='myjist', wip=items, thiscurrentPage=currentPage, count=count) @require( in_any_group("managers", "production", "marketing", "healthsafety", "logistics", "stores", "estimates")) @expose('jistdocstore.templates.mysiteagentspages') def my_site_agent_contracts(self, **named): """Handle the 'site_agent_contracts' page.""" tmpl_context.widget = spx_contracts_table value = contracts_siteagent_filler.get_value(values={}, offset=0, order_by='jno', desc=True) count = len(value) page = int(named.get('page', '1')) currentPage = paginate.Page( value, page, item_count=count, items_per_page=15, ) items = currentPage.items #print currentPage #print currentPage.page #print currentPage.previous_page return dict(page='myjist', wip=items, thiscurrentPage=currentPage, count=count) @require( in_any_group("managers", "production", "marketing", "healthsafety", "logistics", "stores", "estimates")) @expose('jistdocstore.templates.myjistpages') def myjist(self, **named): """Handle the 'myjistpages'.""" return dict(page='My JIST Main Menu') ################################################################################# #############Boiler Plate Code Starts############################################ @expose('jistdocstore.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('jistdocstore.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(page='environ', environment=request.environ) @expose('jistdocstore.templates.data') @expose('json') def data(self, **kw): """This method showcases how you can use the same controller for a data page and a display page""" return dict(page='data', params=kw) @expose('jistdocstore.templates.index') #@require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('jistdocstore.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('jistdocstore.templates.login') def login(self, came_from=lurl('/')): """Start the user login.""" login_counter = request.environ.get('repoze.who.logins', 0) if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from) @expose() def post_login(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ.get('repoze.who.logins', 0) + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) redirect(came_from) @expose() def post_logout(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) redirect(came_from)
class TopManagementController(BaseController): """Sample controller-wide authorization""" # The predicate that must be met for all the actions in this controller: allow_only = has_permission( 'manage', msg=l_('Only for people with the "manage" permission')) @require( in_any_group("managers", "production", "marketing", "healthsafety", "logistics", "stores", "estimates")) @expose() def index(self): redirect('topmngntcont/menu') @expose('jistdocstore.templates.topmanagement') def menu(self): #flash(_("Secure Controller here")) return dict(page='refreshpage') @expose('jistdocstore.templates.managepoints') def managepoints(self, usrid=0, **kw): """Handle the 'managepoints' page.""" if not usrid: usrid = '1' wip = DBS_ContractData.query(JistContracts).join(JistContractStatus). \ filter(JistContracts.completed=='False'). \ filter(JistContractStatus.pointperson==usrid). \ all() wip1 = [] tmpl_context.widget = status_point_changer for w in wip: statusall = DBS_ContractData.query(JistContractStatus).filter( JistContractStatus.jno == w.jno).one() statcode = DBS_ContractData.query(JistContractStatusCodes).filter( JistContractStatusCodes.id == statusall.statuscode).one() wip1.append({ 'jno': w.jno, 'client': w.client, 'site': w.site, 'description': w.description, 'status': statcode.status, 'pointperson': statusall.pointperson }) count = len(wip1) page = int(kw.get('page', '1')) currentPage = paginate.Page( wip1, page, item_count=count, items_per_page=15, ) items = currentPage.items return dict(page='managepoints', wip=items, thiscurrentPage=currentPage, point=usrid, count=count) @expose() def getmanagedpoints(self, *args, **kw): if not kw['point']: point = 1 else: point = kw['point'] redirect('/topmngntcont/managepoints/' + str(point)) @expose() def exportsinglepointpdf(self, point): import random rnd = random.random() rnd = str(rnd).split('.')[1] fname = str(datetime.now()).split(' ')[0] + rnd + '.pdf' filename = os.path.join(pdf_dirname, str(fname)) #print filename pdffile = CreatePDF(filename) userdata = [] contractdata = [] try: conplandates = DBS_ContractData.query(JistContractPlanningDates). \ filter(JistContractPlanningDates.jcno==jno_id).one() except: conplandates = None wip = DBS_ContractData.query(JistContracts).join(JistContractStatus). \ filter(JistContracts.completed=='False'). \ filter(JistContractStatus.pointperson==point). \ all() wip1 = [] for w in wip: statusall = DBS_ContractData.query(JistContractStatus).filter( JistContractStatus.jno == w.jno).one() try: conplandates = DBS_ContractData.query(JistContractPlanningDates). \ filter(JistContractPlanningDates.jcno==w.jno).one() #print type(conplandates) #print conplandates.planstartdate #planstart = str(conplandates.planstartdate).split(' ')[0] #planend = str(conplandates.planenddate).split(' ')[0], planstart = datetime.date(conplandates.planstartdate) planend = datetime.date(conplandates.planenddate) except: planstart = '' planend = '' statcode = DBS_ContractData.query(JistContractStatusCodes).filter( JistContractStatusCodes.id == statusall.statuscode).one() wip1.append({ 'jno': w.jno, 'client': w.client, 'site': w.site, 'description': w.description, 'planstart': planstart, 'planend': planend, 'status': statcode.status, 'pointperson': statusall.pointperson }) count = len(wip1) pointperson_name = User.by_user_id(point).user_name userdata.append([ datetime.date(datetime.now()), "Point Contracts For %s" % pointperson_name, "" ]) headers = [ "JCNo", "Client", "Site", "Description", "Plan Start", "Plan End", "Status" ] headerwidths = [40, 120, 200, 200, 60, 60, 80] pdffile.CreatePDFPointContracts(userdata, wip1, headers, headerwidths) response.headers["Content-Type"] = 'application/pdf' response.headers[ "Content-Disposition"] = 'attachment; filename="' + fname + '"' filecontent = file(filename, "r") return filecontent
def stats_fetch(self, cmp_id, page, rows, sidx, sord, **kw): # User must be admin or queue supervisor sv = ['admin'] for q in Globals.asterisk.queues: sv.append('SV ' + q) if not in_any_group(*sv): tmpl_context.grid = None flash(u'Accès interdit !', 'error') return '' members, total = stats_compute(cmp_id) rows = [] # Create a row for each member for k,v in members.iteritems(): rows.append({ 'id' : k, 'cell': [ k, u'%d (%s)' % (v['r0'], percent(v['r0'], total['r0'])), # RDV u'%d (%s)' % ( v['r1'] + v['r2'] + v['r3'], percent(v['r1'] + v['r2'] + v['r3'], total['r1']+total['r2']+total['r3'])), # A rappeler u'%d (%s)' % (v['r4'], percent(v['r4'], total['r4'])), # Contact direct CC u'%d (%s)' % (v['r5'], percent(v['r5'], total['r5'])), # Pas intéressé u'%d (%s)' % (v['answ'], percent(v['answ'], total['answ'])), # Total appels aboutis u'%d (%s)' % (v['r6'], percent(v['r6'], total['r6'])), # Absent u'%d (%s)' % (v['r7'], percent(v['r7'], total['r7'])), # Décédé u'%d (%s)' % (v['r8'], percent(v['r8'], total['r8'])), # Faux numéro / Aucun numéro u'%d (%s)' % (v['r9'], percent(v['r9'], total['r9'])), # Injoignable u'%d (%s)' % (v['no_answ'], percent(v['no_answ'], total['no_answ'])), # Total appels non aboutis u'%d (%s)' % (v['r10'], percent(v['r10'], total['r10'])), # Hors cible u'%d (%s)' % (v['r11'], percent(v['r11'], total['r11'])), # Réclamation u'%d (%s)' % (v['tot'], percent(v['tot'], total['tot'])), # Total Fiches clients traitées ]}) # Add global rows.append({ 'id' : 'total', 'cell': [ Markup(u'<em>Total</em>'), Markup(u'<em>%d</em>' % total['r0']), # RDV Markup(u'<em>%d</em>' % ( total['r1'] + total['r2'] + total['r3'])), # A rappeler Markup(u'<em>%d</em>' % total['r4']), # Contact direct CC Markup(u'<em>%d</em>' % total['r5']), # Pas intéressé Markup(u'<em>%d</em>' % total['answ']), # Total appels aboutis Markup(u'<em>%d</em>' % total['r6']), # Absent Markup(u'<em>%d</em>' % total['r7']), # Décédé Markup(u'<em>%d</em>' % total['r8']), # Faux numéro / Aucun numéro Markup(u'<em>%d</em>' % total['r9']), # Injoignable Markup(u'<em>%d</em>' % total['no_answ']), # Total appels non aboutis Markup(u'<em>%d</em>' % total['r10']), # Hors cible Markup(u'<em>%d</em>' % total['r11']), # Réclamation Markup(u'<em>%d</em>' % total['tot']), # Total Fiches clients traitées ]}) return dict(page=page, total=1, rows=rows)
def test_user_doesnt_belong_to_groups(self): environ = make_environ('gustavo', ['users', 'admins']) p = predicates.in_any_group('developers', 'designers') self.eval_unmet_predicate( p, environ, 'The member must belong to at least one of the ' 'following groups: developers, designers')
def fetch(self, page, rows, sidx, sord='desc', _search='false', searchOper=None, searchField=None, searchString=None, **kw): ''' Function called on AJAX request made by FlexGrid Fetch data from DB, return the list of rows + total + current page ''' if not in_any_group('admin','STATS'): flash(u'Accès interdit !', 'error') redirect('/') try: page = int(page) rows = int(rows) offset = (page-1) * rows except: page = 1 rows = 12 offset = 0 log.info('fetch : page=%d, rows=%d, offset=%d' % (page, rows, offset)) if self.stats_type: # Daily stats d = datetime.datetime.strptime(self.stats_type, '%m/%d/%Y') if db_engine=='oracle': req = func.trunc(CDR.calldate, 'J') else: # PostgreSql req = func.date_trunc('day', CDR.calldate) cdrs = DBSession.query(req, func.count(req), func.sum(CDR.billsec)) if db_engine=='oracle': cdrs = cdrs.filter(func.trunc(CDR.calldate, 'month') == \ func.trunc(d, 'month')) else: # PostgreSql cdrs = cdrs.filter(func.date_trunc('month', CDR.calldate) == \ func.date_trunc('month', d)) cdrs = cdrs.group_by(req) else: # Monthly stats if db_engine=='oracle': req = func.trunc(CDR.calldate, 'month') else: # PostgreSql req = func.date_trunc('month', CDR.calldate) cdrs = DBSession.query(req, func.count(req), func.sum(CDR.billsec)) cdrs = cdrs.group_by(req) self.stats_req = cdrs if sidx=='calls': cdrs = cdrs.order_by(getattr(func.count(req),sord)()) elif sidx=='billsec': cdrs = cdrs.order_by(getattr(func.sum(CDR.billsec),sord)()) else: cdrs = cdrs.order_by(getattr(req,sord)()) cdrs = cdrs.offset(offset).limit(rows) total = cdrs.count()/rows + 1 data = [{ 'id' : i, 'cell': cell(self.stats_type, i, c) } for i, c in enumerate(cdrs.all()) ] return dict(page=page, total=total, rows=data)
class AccountController(TGController): allow_only = in_any_group( 'voter', 'managers', msg=l_('Only for people with the "manage" permission')) def __init__(self, models, session, config_type=None, translations=None): self.utility = Utility() self.model = models # self.registerService = RegisterService(); dh = LogDBHandler(config=config, request=request) log.addHandler(dh) def _before(self, *args, **kw): tmpl_context.project_name = "managepoll" @expose('managepoll.templates.account.index') def index(self, **kw): user = request.identity['user'] print user.user_id userService = self.model.UserService() if request.identity: user = request.identity['user'] userService = self.model.UserService.getById(user.user_id) if userService is None: userService = self.model.UserService() listConutry = [] self.country = self.model.FixCountry.getAll("1") for lang in self.country: listConutry.append(lang.to_json()) listGender = self.model.Gender.getAll(1) listLanguage = [] self.language = self.model.FixLanguage.getAll("1") for lang in self.language: listLanguage.append(lang.to_json()) return dict(page='index', userService=userService, listConutry=listConutry, listGender=listGender, listLanguage=listLanguage, idproject=None) @expose('managepoll.templates.account.changepassword') def changepass(self, *args, **kw): """Handle the front-page.""" return dict(page='changepassword') # @expose('managepoll.templates.account.socialmedia') # def socialmedia(self, *args, **kw): # user = request.identity['user']; # self.userSocialNetwork = self.model.UserSocialNetwork.getSocialByUserId(user.user_id) # return dict(page='socialmedia',userSocialNetwork=self.userSocialNetwork, socialType = self.serviceType) @expose('managepoll.templates.account.socialmedia') def socialmedia(self, *args, **kw): user = request.identity['user'] print user.user_id self.userSocialNetwork = self.model.UserSocialNetwork.getSocialByUserId( user.user_id) self.serviceType = self.serviceType = self.model.SocialType.getAll(1) return dict(page='socialmedia', userSocialNetwork=self.userSocialNetwork, serviceType=self.serviceType) @expose('managepoll.templates.account.cancellation') def cancellation(self, *args, **kw): """Handle the front-page.""" return dict(page='cancellation') @expose() def rechangepass(self, *args, **kw): self.success = False self.message = '' if request.identity: self.current_password = kw.get('password') self.new_password = kw.get('newpassword') self.re_new_password = kw.get('rnewpassword') user = request.identity['user'] if (user.validate_password(self.current_password)): if (str(self.new_password) == str(self.re_new_password)): user._set_password(self.new_password) self.success = True self.message = LanguageObject.getdata( "msg_password_changed") else: self.message = LanguageObject.getdata( "msg_password_not_match") else: log.warning("user %s password not match : %s", user.user_name, self.current_password) self.message = LanguageObject.getdata("msg_password_not_match") else: self.message = LanguageObject.getdata("msg_not_login") log.warning("user cannot login, redirect to login") flash(_(self.message), 'warning') redirect('/managepoll/account/changepass')
def can_be_viewed(self): return predicates.in_any_group(self.view).check_authorization(request.environ)
class UserRestController(TIMRestController): """CRUD Controller allowing to manage Users.""" allow_only = predicates.in_any_group( Group.TIM_MANAGER_GROUPNAME, Group.TIM_ADMIN_GROUPNAME, ) password = UserPasswordAdminRestController() profile = UserProfileAdminRestController() workspaces = UserWorkspaceRestController() PASSWORD_LENGTH = 12 PASSWORD_CHARACTERS = '0123456789' \ 'abcdefghijklmonpqrstuvwxyz' \ 'ABCDEFGHIJKLMONPQRSTUVWXYZ' @classmethod def current_item_id_key_in_context(cls): return 'user_id' @tg.require(predicates.in_group(Group.TIM_MANAGER_GROUPNAME)) @tg.expose('tracim.templates.admin.user_getall') def get_all(self, *args, **kw): current_user = tmpl_context.current_user api = UserApi(current_user) users = api.get_all() current_user_content = Context(CTX.CURRENT_USER).toDict(current_user) fake_api = Context(CTX.USERS).toDict({'current_user': current_user_content}) dictified_users = Context(CTX.USERS).toDict(users, 'users', 'user_nb') return DictLikeClass(result=dictified_users, fake_api=fake_api) @tg.require(predicates.in_group(Group.TIM_MANAGER_GROUPNAME)) @tg.expose() def post( self, name: str, email: str, password: str, is_tracim_manager: str='off', is_tracim_admin: str='off', send_email: str='off', ): is_tracim_manager = h.on_off_to_boolean(is_tracim_manager) is_tracim_admin = h.on_off_to_boolean(is_tracim_admin) send_email = h.on_off_to_boolean(send_email) current_user = tmpl_context.current_user if current_user.profile.id < Group.TIM_ADMIN: # A manager can't give large rights is_tracim_manager = False is_tracim_admin = False api = UserApi(current_user) if api.user_with_email_exists(email): tg.flash(_('A user with email address "{}" already exists.').format(email), CST.STATUS_ERROR) tg.redirect(self.url()) user = api.create_user() user.email = email user.display_name = name if password: user.password = password elif send_email: # Setup a random password to send email at user password = self.generate_password() user.password = password api.save(user) # Now add the user to related groups group_api = GroupApi(current_user) user.groups.append(group_api.get_one(Group.TIM_USER)) if is_tracim_manager: user.groups.append(group_api.get_one(Group.TIM_MANAGER)) if is_tracim_admin: user.groups.append(group_api.get_one(Group.TIM_ADMIN)) api.save(user) email_sent = True if send_email: email_manager = get_email_manager() try: email_manager.notify_created_account(user, password=password) except Exception: email_sent = False api.execute_created_user_actions(user) if not email_sent: tg.flash(_('User {0} created but email was not sent to {1}').format(user.get_display_name(), user.email), CST.STATUS_WARNING) else: tg.flash(_('User {} created.').format(user.get_display_name()), CST.STATUS_OK) tg.redirect(self.url()) @classmethod def generate_password( cls, password_length=PASSWORD_LENGTH, password_chars=PASSWORD_CHARACTERS, ): # character list that will be contained into the password char_list = [] for _unused in range(password_length): # This puts a random char from the list above inside # the list of chars and then merges them into a String char_list.append(random.choice(password_chars)) password = ''.join(char_list) return password @tg.expose('tracim.templates.admin.user_getone') def get_one(self, user_id): current_user = tmpl_context.current_user api = UserApi(current_user) # role_api = RoleApi(tg.tmpl_context.current_user) # user_api = UserApi(tg.tmpl_context.current_user) user = api.get_one(user_id) # FIXME role_api = RoleApi(tg.tmpl_context.current_user) role_list = role_api.get_roles_for_select_field() dictified_user = Context(CTX.ADMIN_USER).toDict(user, 'user') current_user_content = Context(CTX.CURRENT_USER).toDict(tmpl_context.current_user) fake_api_content = DictLikeClass(current_user=current_user_content, role_types=role_list) fake_api = Context(CTX.ADMIN_USER).toDict(fake_api_content) return DictLikeClass(result=dictified_user, fake_api=fake_api) @tg.expose('tracim.templates.admin.user_edit') def edit(self, id): current_user = tmpl_context.current_user api = UserApi(current_user) user = api.get_one(id) dictified_user = Context(CTX.USER).toDict(user, 'user') return DictLikeClass( result=dictified_user, timezones=pytz.all_timezones, ) @tg.require(predicates.in_group(Group.TIM_MANAGER_GROUPNAME)) @tg.expose() def put(self, user_id, name, email, timezone: str='', next_url=''): api = UserApi(tmpl_context.current_user) user = api.get_one(int(user_id)) api.update(user, name, email, True, timezone=timezone) tg.flash(_('User {} updated.').format(user.get_display_name()), CST.STATUS_OK) if next_url: tg.redirect(next_url) tg.redirect(self.url()) @tg.require(predicates.in_group(Group.TIM_ADMIN_GROUPNAME)) @tg.expose() def enable(self, id, next_url=None): current_user = tmpl_context.current_user api = UserApi(current_user) user = api.get_one(id) user.is_active = True api.save(user) tg.flash(_('User {} enabled.').format(user.get_display_name()), CST.STATUS_OK) if next_url == 'user': tg.redirect(self.url(id=user.user_id)) tg.redirect(self.url()) @tg.require(predicates.in_group(Group.TIM_ADMIN_GROUPNAME)) @tg.expose() def disable(self, id, next_url=None): id = int(id) current_user = tmpl_context.current_user api = UserApi(current_user) if current_user.user_id == id: tg.flash(_('You can\'t de-activate your own account'), CST.STATUS_ERROR) else: user = api.get_one(id) user.is_active = False api.save(user) tg.flash(_('User {} disabled').format(user.get_display_name()), CST.STATUS_OK) if next_url == 'user': tg.redirect(self.url(id=user.user_id)) tg.redirect(self.url())
def can_be_written(self): return predicates.in_any_group(self.write).check_authorization(request.environ)
def test_user_doesnt_belong_to_groups(self): environ = make_environ('gustavo', ['users', 'admins']) p = predicates.in_any_group('developers', 'designers') self.eval_unmet_predicate(p, environ, 'The member must belong to at least one of the ' 'following groups: developers, designers')
def can_be_moderated(self): return predicates.in_any_group(self.moderate).check_authorization(request.environ)