def table_template(table): from gluon.html import TR, TD, TABLE, TAG def FONT(*args, **kwargs): return TAG.font(*args, **kwargs) def types(field): f_type = field.type if not isinstance(f_type, str): return ' ' elif f_type == 'string': return field.length elif f_type == 'id': return B('pk') elif f_type.startswith('reference') or \ f_type.startswith('list:reference'): return B('fk') else: return ' ' # This is horribe HTML but the only one graphiz understands rows = [] cellpadding = 4 color = "#000000" bgcolor = "#FFFFFF" face = "Helvetica" face_bold = "Helvetica Bold" border = 0 rows.append(TR(TD(FONT(table, _face=face_bold, _color=bgcolor), _colspan=3, _cellpadding=cellpadding, _align="center", _bgcolor=color))) for row in db[table]: rows.append(TR(TD(FONT(row.name, _color=color, _face=face_bold), _align="left", _cellpadding=cellpadding, _border=border), TD(FONT(row.type, _color=color, _face=face), _align="left", _cellpadding=cellpadding, _border=border), TD(FONT(types(row), _color=color, _face=face), _align="center", _cellpadding=cellpadding, _border=border))) return "< %s >" % TABLE(*rows, **dict(_bgcolor=bgcolor, _border=1, _cellborder=0, _cellspacing=0) ).xml()
def test_THEAD(self): self.assertEqual( THEAD('<>', _a='1', _b='2').xml(), b'<thead a="1" b="2"><tr><th><></th></tr></thead>') # self.assertEqual(THEAD(TRHEAD('<>'), _a='1', _b='2').xml(), # '<thead a="1" b="2"><tr><th><></th></tr></thead>') self.assertEqual( THEAD(TR('<>'), _a='1', _b='2').xml(), b'<thead a="1" b="2"><tr><td><></td></tr></thead>')
def toolbar(self): from html import DIV, SCRIPT, BEAUTIFY, TAG, URL, A BUTTON = TAG.button admin = URL("admin", "default", "design", extension='html', args=current.request.application) from gluon.dal import DAL dbstats = [] dbtables = {} infos = DAL.get_instances() for k,v in infos.iteritems(): dbstats.append(TABLE(*[TR(PRE(row[0]),'%.2fms' % (row[1]*1000)) for row in v['dbstats']])) dbtables[k] = dict(defined=v['dbtables']['defined'] or '[no defined tables]', lazy=v['dbtables']['lazy'] or '[no lazy tables]') u = web2py_uuid() backtotop = A('Back to top', _href="#totop-%s" % u) # Convert lazy request.vars from property to Storage so they # will be displayed in the toolbar. request = copy.copy(current.request) request.update(vars=current.request.vars, get_vars=current.request.get_vars, post_vars=current.request.post_vars) return DIV( BUTTON('design', _onclick="document.location='%s'" % admin), BUTTON('request', _onclick="jQuery('#request-%s').slideToggle()" % u), BUTTON('response', _onclick="jQuery('#response-%s').slideToggle()" % u), BUTTON('session', _onclick="jQuery('#session-%s').slideToggle()" % u), BUTTON('db tables', _onclick="jQuery('#db-tables-%s').slideToggle()" % u), BUTTON('db stats', _onclick="jQuery('#db-stats-%s').slideToggle()" % u), DIV(BEAUTIFY(request), backtotop, _class="hidden", _id="request-%s" % u), DIV(BEAUTIFY(current.session), backtotop, _class="hidden", _id="session-%s" % u), DIV(BEAUTIFY(current.response), backtotop, _class="hidden", _id="response-%s" % u), DIV(BEAUTIFY(dbtables), backtotop, _class="hidden", _id="db-tables-%s" % u), DIV(BEAUTIFY( dbstats), backtotop, _class="hidden", _id="db-stats-%s" % u), SCRIPT("jQuery('.hidden').hide()"), _id="totop-%s" % u )
def show_disabled(self, title): return HTML( HEAD( TITLE(title), LINK(_rel="shortcut icon", _href=URL('static', 'favicon.ico'), _type="image/x-icon")), BODY( DIV(CENTER( TABLE(TR( TD(IMG(_src=URL('static', 'images/dataprotection_min.jpg'), _style="border: solid;border-color: #FFFFFF;"), _style= "text-align: center;vertical-align: middle;font-weight: bold;font-family: Arial, Helvetica, sans-serif;font-size: 20px;" )), _style= "background-color:#FFFFFF;color:#444444;margin-top:30px;" )), _style="width:100%;height:100%;")), _style="background-color:#879FB7;")
def rowstyle(self, form, fields, *args, **kwargs): """ Formstyle for subform edit-rows, using a vertical formstyle because multiple fields combined with location-selector are too complex for horizontal layout. """ # Use standard foundation formstyle from s3theme import formstyle_foundation as formstyle if args: col_id = form label = fields widget, comment = args hidden = kwargs.get("hidden", False) return formstyle(col_id, label, widget, comment, hidden) else: parent = TD(_colspan=len(fields)) for col_id, label, widget, comment in fields: parent.append(formstyle(col_id, label, widget, comment)) return TR(parent)
def select(): import re db = get_database(request) dbname = request.args[0] regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)') if len(request.args) > 1 and hasattr(db[request.args[1]], '_primarykey'): regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)') if request.vars.query: match = regex.match(request.vars.query) if match: request.vars.query = '%s.%s.%s==%s' % ( request.args[0], match.group('table'), match.group('field'), match.group('value')) else: request.vars.query = session.last_query query = get_query(request) if request.vars.start: start = int(request.vars.start) else: start = 0 nrows = 0 stop = start + 100 table = None rows = [] orderby = request.vars.orderby if orderby: orderby = dbname + '.' + orderby if orderby == session.last_orderby: if orderby[0] == '~': orderby = orderby[1:] else: orderby = '~' + orderby session.last_orderby = orderby session.last_query = request.vars.query form = FORM(TABLE( TR( T('Query:'), '', INPUT(_style='width:400px', _name='query', _value=request.vars.query or '', requires=IS_NOT_EMPTY(error_message=T("Cannot be empty")))), TR( T('Update:'), INPUT(_name='update_check', _type='checkbox', value=False), INPUT(_style='width:400px', _name='update_fields', _value=request.vars.update_fields or '')), TR( T('Delete:'), INPUT(_name='delete_check', _class='delete', _type='checkbox', value=False), ''), TR('', '', INPUT(_type='submit', _value=T('submit')))), _action=URL(r=request, args=request.args)) tb = None if form.accepts(request.vars, formname=None): regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+') match = regex.match(form.vars.query.strip()) if match: table = match.group('table') try: nrows = db(query).count() if form.vars.update_check and form.vars.update_fields: db(query).update(**eval_in_global_env('dict(%s)' % form.vars.update_fields)) response.flash = T('%s %%{row} updated', nrows) elif form.vars.delete_check: db(query).delete() response.flash = T('%s %%{row} deleted', nrows) nrows = db(query).count() if orderby: rows = db(query, ignore_common_filters=True).select( limitby=(start, stop), orderby=eval_in_global_env(orderby)) else: rows = db(query, ignore_common_filters=True).select(limitby=(start, stop)) except Exception as e: import traceback tb = traceback.format_exc() (rows, nrows) = ([], 0) response.flash = DIV(T('Invalid Query'), PRE(str(e))) # begin handle upload csv csv_table = table or request.vars.table if csv_table: formcsv = FORM( str(T('or import from csv file')) + " ", INPUT(_type='file', _name='csvfile'), INPUT(_type='hidden', _value=csv_table, _name='table'), INPUT(_type='submit', _value=T('import'))) else: formcsv = None if formcsv and formcsv.process().accepted: try: import_csv(db[request.vars.table], request.vars.csvfile.file) response.flash = T('data uploaded') except Exception as e: response.flash = DIV(T('unable to parse csv file'), PRE(str(e))) # end handle upload csv return dict( form=form, table=table, start=start, stop=stop, nrows=nrows, rows=rows, query=request.vars.query, formcsv=formcsv, tb=tb, )
def select(): import re db = get_database(request) dbname = request.args[0] try: is_imap = db._uri.startswith("imap://") except (KeyError, AttributeError, TypeError): is_imap = False regex = re.compile(r"(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)") if len(request.args) > 1 and hasattr(db[request.args[1]], "_primarykey"): regex = re.compile(r"(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)") if request.vars.query: match = regex.match(request.vars.query) if match: request.vars.query = "%s.%s.%s==%s" % ( request.args[0], match.group("table"), match.group("field"), match.group("value"), ) else: request.vars.query = session.last_query query = get_query(request) if request.vars.start: start = int(request.vars.start) else: start = 0 nrows = 0 step = 100 fields = [] if is_imap: step = 3 stop = start + step table = None rows = [] orderby = request.vars.orderby if orderby: orderby = dbname + "." + orderby if orderby == session.last_orderby: if orderby[0] == "~": orderby = orderby[1:] else: orderby = "~" + orderby session.last_orderby = orderby session.last_query = request.vars.query form = FORM( TABLE( TR( T("Query:"), "", INPUT( _style="width:400px", _name="query", _value=request.vars.query or "", _class="form-control", requires=IS_NOT_EMPTY(error_message=T("Cannot be empty")), ), ), TR( T("Update:"), INPUT(_name="update_check", _type="checkbox", value=False), INPUT( _style="width:400px", _name="update_fields", _value=request.vars.update_fields or "", _class="form-control", ), ), TR( T("Delete:"), INPUT(_name="delete_check", _class="delete", _type="checkbox", value=False), "", ), TR( "", "", INPUT(_type="submit", _value=T("submit"), _class="btn btn-primary"), ), ), _action=URL(r=request, args=request.args), ) tb = None if form.accepts(request.vars, formname=None): regex = re.compile(request.args[0] + r"\.(?P<table>\w+)\..+") match = regex.match(form.vars.query.strip()) if match: table = match.group("table") try: nrows = db(query, ignore_common_filters=True).count() if form.vars.update_check and form.vars.update_fields: db(query, ignore_common_filters=True).update( **eval_in_global_env("dict(%s)" % form.vars.update_fields)) response.flash = T("%s %%{row} updated", nrows) elif form.vars.delete_check: db(query, ignore_common_filters=True).delete() response.flash = T("%s %%{row} deleted", nrows) nrows = db(query, ignore_common_filters=True).count() if is_imap: fields = [ db[table][name] for name in ("id", "uid", "created", "to", "sender", "subject") ] if orderby: rows = db(query, ignore_common_filters=True).select( *fields, limitby=(start, stop), orderby=eval_in_global_env(orderby)) else: rows = db(query, ignore_common_filters=True).select(*fields, limitby=(start, stop)) except Exception as e: import traceback tb = traceback.format_exc() (rows, nrows) = ([], 0) response.flash = DIV(T("Invalid Query"), PRE(str(e))) # begin handle upload csv csv_table = table or request.vars.table if csv_table: formcsv = FORM( str(T("or import from csv file")) + " ", INPUT(_type="file", _name="csvfile"), INPUT(_type="hidden", _value=csv_table, _name="table"), INPUT(_type="submit", _value=T("import"), _class="btn btn-primary"), ) else: formcsv = None if formcsv and formcsv.process().accepted: try: import_csv(db[request.vars.table], request.vars.csvfile.file) response.flash = T("data uploaded") except Exception as e: response.flash = DIV(T("unable to parse csv file"), PRE(str(e))) # end handle upload csv return dict( form=form, table=table, start=start, stop=stop, step=step, nrows=nrows, rows=rows, query=request.vars.query, formcsv=formcsv, tb=tb, )
f_type.startswith('list:reference'): return B('fk') else: return ' ' # This is horribe HTML but the only one graphiz understands rows = [] cellpadding = 4 color = "#000000" bgcolor = "#FFFFFF" face = "Helvetica" face_bold = "Helvetica Bold" border = 0 rows.append(TR(TD(FONT(table, _face=face_bold, _color=bgcolor), _colspan=3, _cellpadding=cellpadding, _align="center", _bgcolor=color))) for row in db[table]: rows.append(TR(TD(FONT(row.name, _color=color, _face=face_bold), _align="left", _cellpadding=cellpadding, _border=border), TD(FONT(row.type, _color=color, _face=face), _align="left", _cellpadding=cellpadding, _border=border), TD(FONT(types(row), _color=color, _face=face), _align="center", _cellpadding=cellpadding, _border=border))) return "< %s >" % TABLE(*rows, **dict(_bgcolor=bgcolor, _border=1, _cellborder=0, _cellspacing=0) ).xml()
def report_template(): response.subtitle = T("Edit report template") response.view = 'nas/template.html' #response.cmd_menu = None response.cmd_labels = ui.control.get_mobil_button( label=T("Labels"), href="#", cformat=None, style="text-align: left;", icon="edit", ajax="true", theme="d", onclick="document.getElementById('edit_label').style.display = 'block';" + "document.getElementById('edit_label_update').style.display = 'block';" + "document.getElementById('edit_template_update').style.display = 'none';" + "document.getElementById('view_template').style.display = 'none';" + "document.getElementById('edit_template').style.display = 'none';return true;" ) response.cmd_view = ui.control.get_mobil_button( label=T("View XML"), href="#", cformat=None, style="text-align: left;", icon="page", ajax="true", theme="d", onclick="document.getElementById('edit_label').style.display = 'none';" + "document.getElementById('edit_label_update').style.display = 'none';" + "document.getElementById('edit_template_update').style.display = 'none';" + "document.getElementById('view_template').style.display = 'block';" + "document.getElementById('edit_template').style.display = 'none';return true;" ) response.cmd_edit = ui.control.get_mobil_button( label=T("Edit XML"), href="#", cformat=None, style="text-align: left;", icon="edit", ajax="true", theme="d", onclick="document.getElementById('edit_label').style.display = 'none';" + "document.getElementById('edit_label_update').style.display = 'none';" + "document.getElementById('edit_template_update').style.display = 'block';" + "document.getElementById('view_template').style.display = 'none';" + "document.getElementById('edit_template').style.display = 'block';return true;" ) response.cmd_labels_update = ui.control.get_mobil_button( label=T("Save"), href="#", cformat=None, style="text-align: left;", icon="check", ajax="false", theme="a", onclick="document.forms['frm_labels'].submit();") response.frm_report_update = ui.control.get_mobil_button( label=T("Save"), href="#", cformat=None, style="text-align: left;", icon="check", ajax="false", theme="a", onclick="document.forms['frm_report'].submit();") labels, tmp_view, tmp_edit = "", "", "" response.report_name = "" if ns.local.setEngine( database=db.databases(id=request.vars["database"]).alias, check_ndi=False, created=False, createdb=False): if request.post_vars.has_key("update_labels"): for label_id in request.post_vars.keys(): if label_id not in ("update_labels"): row_id = ns.connect.updateData( "ui_message", values={ "id": label_id, "msg": request.post_vars[label_id] }, validate=False, insert_row=False) if not row_id: response.flash = str(ns.error_message) ns.db.commit() if request.post_vars.has_key("report_template"): row_id = ns.connect.updateData( "ui_report", values={ "id": ns.db.ui_report(reportkey=request.vars["reportkey"])["id"], "report": request.post_vars["report_template"] }, validate=False, insert_row=False) if not row_id: response.flash = str(ns.error_message) ns.db.commit() report = ns.db.ui_report(reportkey=request.vars["reportkey"]) if report: response.report_name = report["repname"] tmp_view = CODE(report["report"]) tmp_edit = TEXTAREA( _name="report_template", value=report["report"], _style="height: auto!important;overflow-y: scroll;", _rows=20) response.update_labels = INPUT(_name="update_labels", _type="hidden", _value="yes") ui_message = ns.db( (ns.db.ui_message.secname.like(report["reportkey"] + "%") )).select(orderby=ns.db.ui_message.secname | ns.db.ui_message.fieldname) labels = TABLE(_style="width: 100%;", _cellpadding="0px;", _cellspacing="0px;") ridlen = len(str(report["reportkey"]).split("_")) for message in ui_message: labels.append( TR( TD(DIV(str(message["secname"]).split("_")[ridlen], _class="label"), _style="padding-right:10px;"), TD(DIV(message["fieldname"], _class="label"), _style="padding-right:10px;"), TD(INPUT(_name=message["id"], _type="text", _value=message["msg"], _style="width: 100%;"), _style="width: 100%;"))) else: response.flash = str(ns.error_message) return dict(labels=labels, tmp_view=tmp_view, tmp_edit=tmp_edit)
def select(): import re db = get_database(request) dbname = request.args[0] try: is_imap = db._uri.startswith("imap://") except (KeyError, AttributeError, TypeError): is_imap = False regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)') if len(request.args) > 1 and hasattr(db[request.args[1]], '_primarykey'): regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)') if request.vars.query: match = regex.match(request.vars.query) if match: request.vars.query = '%s.%s.%s==%s' % (request.args[0], match.group('table'), match.group('field'), match.group('value')) else: request.vars.query = session.last_query query = get_query(request) if request.vars.start: start = int(request.vars.start) else: start = 0 nrows = 0 step = 100 fields = [] if is_imap: step = 3 stop = start + step table = None rows = [] orderby = request.vars.orderby if orderby: orderby = dbname + '.' + orderby if orderby == session.last_orderby: if orderby[0] == '~': orderby = orderby[1:] else: orderby = '~' + orderby session.last_orderby = orderby session.last_query = request.vars.query form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px', _name='query', _value=request.vars.query or '', requires=IS_NOT_EMPTY( error_message=T("Cannot be empty")))), TR(T('Update:'), INPUT(_name='update_check', _type='checkbox', value=False), INPUT(_style='width:400px', _name='update_fields', _value=request.vars.update_fields or '')), TR(T('Delete:'), INPUT(_name='delete_check', _class='delete', _type='checkbox', value=False), ''), TR('', '', INPUT(_type='submit', _value=T('submit')))), _action=URL(r=request, args=request.args)) tb = None if form.accepts(request.vars, formname=None): regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+') match = regex.match(form.vars.query.strip()) if match: table = match.group('table') try: nrows = db(query, ignore_common_filters=True).count() if form.vars.update_check and form.vars.update_fields: db(query, ignore_common_filters=True).update( **eval_in_global_env('dict(%s)' % form.vars.update_fields)) response.flash = T('%s %%{row} updated', nrows) elif form.vars.delete_check: db(query, ignore_common_filters=True).delete() response.flash = T('%s %%{row} deleted', nrows) nrows = db(query, ignore_common_filters=True).count() if is_imap: fields = [db[table][name] for name in ("id", "uid", "created", "to", "sender", "subject")] if orderby: rows = db(query, ignore_common_filters=True).select( *fields, limitby=(start, stop), orderby=eval_in_global_env(orderby)) else: rows = db(query, ignore_common_filters=True).select( *fields, limitby=(start, stop)) except Exception, e: import traceback tb = traceback.format_exc() (rows, nrows) = ([], 0) response.flash = DIV(T('Invalid Query'), PRE(str(e)))
def user(): table = TABLE(TR(TD("Back to home: ",A(SPAN("HOME"), _href=URL("index"), _title=T("HOME")))), TR(TD(auth()))) return table
def secret_page(): table = TABLE(TR(TD("Back to home: ",A(SPAN("HOME"), _href=URL("index"), _title=T("HOME")))), TR(TD("Change password: "******"Change password"), _href=URL("user/change_password"), _title=T("Change password...")))), TR(TD("Logout: ",A(SPAN("Exit"), _href=URL("user/logout"), _title=T("Logout..."))))) return table
def select(): import re db = get_database(request) dbname = request.args[0] regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)') if len(request.args) > 1 and hasattr(db[request.args[1]], '_primarykey'): regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)') if request.vars.query: match = regex.match(request.vars.query) if match: request.vars.query = '%s.%s.%s==%s' % ( request.args[0], match.group('table'), match.group('field'), match.group('value')) else: request.vars.query = session.last_query query = get_query(request) if request.vars.start: start = int(request.vars.start) else: start = 0 nrows = 0 stop = start + 100 table = None rows = [] orderby = request.vars.orderby if orderby: orderby = dbname + '.' + orderby if orderby == session.last_orderby: if orderby[0] == '~': orderby = orderby[1:] else: orderby = '~' + orderby session.last_orderby = orderby session.last_query = request.vars.query form = FORM(TABLE( TR( T('Query:'), '', INPUT(_style='width:400px', _name='query', _value=request.vars.query or '', requires=IS_NOT_EMPTY(error_message=T("Cannot be empty")))), TR( T('Update:'), INPUT(_name='update_check', _type='checkbox', value=False), INPUT(_style='width:400px', _name='update_fields', _value=request.vars.update_fields or '')), TR( T('Delete:'), INPUT(_name='delete_check', _class='delete', _type='checkbox', value=False), ''), TR('', '', INPUT(_type='submit', _value='submit'))), _action=URL(r=request, args=request.args)) if request.vars.csvfile != None: try: import_csv(db[request.vars.table], request.vars.csvfile.file) response.flash = T('data uploaded') except Exception, e: response.flash = DIV(T('unable to parse csv file'), PRE(str(e)))
def resumen(self, prestamo_id): #### Resumen de cuotas por prestamo. """ El método presenta un resumen detallado de las cuotas que pertenecen a ciertos prestamos/créditos de un cliente. Forma de presentación: |Nº Cuota| Importe| Fecha Límite| Estado| Fecha de Pago| Btn Abonar NOTA: Btn Abonar llama una acción para poder registar el pago de una cuota """ sepadador = HR(_class='bs-docs-separator') # INPUT que contendrá el IDCuota que será enviado a través de ajax. input_ = INPUT(_type='hidden', _id='IDCuota', _name='idcuota') cuotas = self.search('prestamo_id', 'equal', prestamo_id, orderby=self.container.db[self.name_table].id) fields = self.getFields('fecha_limite', 'estado', 'fecha_pago') tr_head = TR(TH('Nº Couta'), TH('Importe')) [tr_head.append(TH(f.label)) for f in fields] table = TABLE(THEAD(tr_head), _class='table table-striped table-condensed') tbody = TBODY() debe = list() pago = list() for cuota in cuotas: tbody.append(TR( TD(cuota.nro), TD("$%.2f" % cuota.valor_cuota), TD(cuota.fecha_limite, _title=cuota.fecha_limite.strftime('%A %Y/%m/%d')), TD(self.get_estado(cuota)), TD(cuota.fecha_pago or '-'), TD(CENTER(SPAN(I(_class='icon-download-alt'), ' Abonar', _onclick='func_abonar(%s)' % cuota.id, _class='btn btn-mini')) ) if cuota.estado[0] != '2' else '', _id='tr_cuota_%s' % cuota.id ) ) # Analizamos que cuotas pagó y cuales adeuda. if cuota.estado[0] != '2': debe.append(cuota.valor_cuota) else: pago.append(cuota.valor_cuota) tbody.append(TR(TH('Total Pagó'), TH('Total Debe'))) tbody.append(TR( TD('+ $', SPAN("%.2f" % sum(pago), _id='ttpago'), INPUT(_name='pago', _type='hidden', _id='input_pago'), _style='color:green'), TD("- $", SPAN("%.2f" % sum(debe), _id='ttdebe'), INPUT(_name='debe', _type='hidden', _id='input_debe'), _style='color:red') ) ) table.append(tbody) url = URL('cuotas', 'abonar_cuota', user_signature=True) javascript = """ function func_abonar(cuotaid){ jQuery('#IDCuota').val(cuotaid); jQuery('#input_pago').val(jQuery('#ttpago').html()); jQuery('#input_debe').val(jQuery('#ttdebe').html()); if(confirm('Desea aceptar el pago?')){ ajax("%s", ['idcuota', 'pago', 'debe'], ':eval'); } else { alert('Canceló el pago!') } } """ % url return TAG[''](sepadador, input_, table, SCRIPT(javascript))
def grid(query, fields=None, field_id=None, left=None, join=None, #! orderby=None, groupby=None, groupfields=None, #! having=None, #! headers={}, searchable=False, #True, sortable=True, paginate=20, pagename="page", #! deletable=False, #! True, editable=True, details=False, #! True, selectable=None, create=False, #!True, csv=False, #!True, links=None, links_in_grid=True, upload = '<default>', args=[], user_signature = False, #!True, maxtextlengths={}, maxtextlength=20, onvalidation=None, oncreate=None, onupdate=None, ondelete=None, sorter_icons=(XML('↑'),XML('↓')), ui = 'web2py', showbuttontext=True, _class="web2py_grid", formname='web2py_grid', search_widget='default', ignore_rw = False, formstyle = 'table3cols', exportclasses = None, formargs={}, createargs={}, editargs={}, viewargs={}, ): # jQuery UI ThemeRoller classes (empty if ui is disabled) if ui == 'jquery-ui': ui = dict(widget='ui-widget', header='ui-widget-header', content='ui-widget-content', default='ui-state-default', cornerall='ui-corner-all', cornertop='ui-corner-top', cornerbottom='ui-corner-bottom', button='ui-button-text-icon-primary', buttontext='ui-button-text', buttonadd='ui-icon ui-icon-plusthick', buttonback='ui-icon ui-icon-arrowreturnthick-1-w', buttonexport='ui-icon ui-icon-transferthick-e-w', buttondelete='ui-icon ui-icon-trash', buttonedit='ui-icon ui-icon-pencil', buttontable='ui-icon ui-icon-triangle-1-e', buttonview='ui-icon ui-icon-zoomin', ) elif ui == 'web2py': ui = dict(widget='', header='', content='', default='', cornerall='', cornertop='', cornerbottom='', button='button btn', buttontext='buttontext button', buttonadd='icon plus icon-plus', buttonback='icon leftarrow icon-arrow-left', buttonexport='icon downarrow icon-download', buttondelete='icon trash icon-trash', buttonedit='icon pen icon-pencil', buttontable='icon rightarrow icon-arrow-right', buttonview='icon magnifier icon-zoom-in', ) elif not isinstance(ui,dict): raise RuntimeError,'SQLFORM.grid ui argument must be a dictionary' db = query._db T = current.T request = current.request session = current.session response = current.response wenabled = (not user_signature or (session.auth and session.auth.user)) create = wenabled and create editable = wenabled and editable deletable = wenabled and deletable def url(**b): b['args'] = args+b.get('args',[]) b['hash_vars']=False b['user_signature'] = user_signature return URL(**b) def url2(**b): b['args'] = request.args+b.get('args',[]) b['hash_vars']=False b['user_signature'] = user_signature return URL(**b) referrer = session.get('_web2py_grid_referrer_'+formname, url()) # if not user_signature every action is accessible # else forbid access unless # - url is based url # - url has valid signature (vars are not signed, only path_info) # = url does not contain 'create','delete','edit' (readonly) if user_signature: if not( '/'.join(str(a) for a in args) == '/'.join(request.args) # or # URL.verify(request,user_signature=user_signature, # hash_vars=False) or not ( 'create' in request.args or 'delete' in request.args or 'edit' in request.args)): session.flash = T('not authorized') redirect(referrer) def gridbutton(buttonclass='buttonadd', buttontext='Add', buttonurl=url(args=[]), callback=None, delete=None, trap=True): if showbuttontext: if callback: return A(SPAN(_class=ui.get(buttonclass)), SPAN(T(buttontext),_title=buttontext, _class=ui.get('buttontext')), callback=callback,delete=delete, _class=trap_class(ui.get('button'),trap)) else: return A(SPAN(_class=ui.get(buttonclass)), SPAN(T(buttontext),_title=buttontext, _class=ui.get('buttontext')), _href=buttonurl, _class=trap_class(ui.get('button'),trap)) else: if callback: return A(SPAN(_class=ui.get(buttonclass)), callback=callback,delete=delete, _title=buttontext, _class=trap_class(ui.get('buttontext'),trap)) else: return A(SPAN(_class=ui.get(buttonclass)), _href=buttonurl,_title=buttontext, _class=trap_class(ui.get('buttontext'),trap)) dbset = db(query) tablenames = db._adapter.tables(dbset.query) #if left!=None: tablenames+=db._adapter.tables(left) if left!=None: if isinstance(left,list): for _left in left: tablenames=tablenames+db._adapter.tables(_left) else: tablenames=tablenames+db._adapter.tables(left) if join!=None: if isinstance(join,list): for _join in join: tablenames=tablenames+db._adapter.tables(_join) else: tablenames=tablenames+db._adapter.tables(join) tables = [db[tablename] for tablename in tablenames] if not fields: fields = reduce(lambda a,b:a+b, [[field for field in table] for table in tables]) if not field_id: field_id = tables[0]._id columns = [str(field) for field in fields \ if field._tablename in tablenames] if not str(field_id) in [str(f) for f in fields]: fields.append(field_id) table = field_id.table tablename = table._tablename if upload=='<default>': upload = lambda filename: url(args=['download',filename]) if len(request.args)>1 and request.args[-2]=='download': stream = response.download(request,db) raise HTTP(200,stream,**response.headers) def buttons(edit=False,view=False,record=None): buttons = DIV(gridbutton('buttonback', 'Back', referrer), _class='form_header row_buttons %(header)s %(cornertop)s' % ui) if edit and (not callable(edit) or edit(record)): args = ['edit',table._tablename,request.args[-1]] buttons.append(gridbutton('buttonedit', 'Edit', url(args=args))) if view: args = ['view',table._tablename,request.args[-1]] buttons.append(gridbutton('buttonview', 'View', url(args=args))) if record and links: for link in links: if isinstance(link,dict): buttons.append(link['body'](record)) elif link(record): buttons.append(link(record)) return buttons formfooter = DIV( _class='form_footer row_buttons %(header)s %(cornerbottom)s' % ui) create_form = update_form = view_form = search_form = None sqlformargs = dict(formargs) if create and len(request.args)>1 and request.args[-2] == 'new': table = db[request.args[-1]] sqlformargs.update(createargs) create_form = SQLFORM( table, ignore_rw=ignore_rw, formstyle=formstyle, _class='web2py_form', **sqlformargs) create_form.process(formname=formname, next=referrer, onvalidation=onvalidation, onsuccess=oncreate) res = DIV(buttons(), create_form, formfooter, _class=_class) res.create_form = create_form res.update_form = update_form res.view_form = view_form res.search_form = search_form return res elif details and len(request.args)>2 and request.args[-3]=='view': table = db[request.args[-2]] record = table(request.args[-1]) or redirect(URL('error')) sqlformargs.update(viewargs) view_form = SQLFORM(table, record, upload=upload, ignore_rw=ignore_rw, formstyle=formstyle, readonly=True, _class='web2py_form', **sqlformargs) res = DIV(buttons(edit=editable, record=record), view_form, formfooter, _class=_class) res.create_form = create_form res.update_form = update_form res.view_form = view_form res.search_form = search_form return res # elif editable and len(request.args)>2 and request.args[-3]=='edit': # table = db[request.args[-2]] # record = table(request.args[-1]) or redirect(URL('error')) # sqlformargs.update(editargs) # update_form = SQLFORM(table, record, upload=upload, ignore_rw=ignore_rw, # formstyle=formstyle, deletable=deletable, # _class='web2py_form', # submit_button=T('Submit'), # delete_label=T('Check to delete'), # **sqlformargs) # update_form.process(formname=formname, # onvalidation=onvalidation, # onsuccess=onupdate, # next=referrer) # res = DIV(buttons(view=details, record=record), # update_form, formfooter, _class=_class) # res.create_form = create_form # res.update_form = update_form # res.view_form = view_form # res.search_form = search_form # return res elif deletable and len(request.args)>2 and request.args[-3]=='delete': table = db[request.args[-2]] if ondelete: ondelete(table,request.args[-1]) ret = db(table[table._id.name]==request.args[-1]).delete() return ret exportManager = dict( csv_with_hidden_cols=(ExporterCSV,'CSV (hidden cols)'), csv=(ExporterCSV,'CSV'), xml=(ExporterXML, 'XML'), html=(ExporterHTML, 'HTML'), tsv_with_hidden_cols=\ (ExporterTSV,'TSV (Excel compatible, hidden cols)'), tsv=(ExporterTSV, 'TSV (Excel compatible)')) if not exportclasses is None: exportManager.update(exportclasses) export_type = request.vars._export_type if export_type: order = request.vars.order or '' if sortable: if order and not order=='None': if order[:1]=='~': sign, rorder = '~', order[1:] else: sign, rorder = '', order tablename,fieldname = rorder.split('.',1) orderby=db[tablename][fieldname] if sign=='~': orderby=~orderby table_fields = [f for f in fields if f._tablename in tablenames] if export_type in ('csv_with_hidden_cols','tsv_with_hidden_cols'): if request.vars.keywords: try: dbset = dbset(SQLFORM.build_query( fields,request.vars.get('keywords',''))) rows = dbset.select(cacheable=True) except Exception: response.flash = T('Internal Error') rows = [] else: rows = dbset.select(cacheable=True) else: rows = dbset.select(left=left,orderby=orderby, cacheable=True*columns) if export_type in exportManager: value = exportManager[export_type] clazz = value[0] if hasattr(value, '__getitem__') else value oExp = clazz(rows) filename = '.'.join(('rows', oExp.file_ext)) response.headers['Content-Type'] = oExp.content_type response.headers['Content-Disposition'] = \ 'attachment;filename='+filename+';' raise HTTP(200, oExp.export(),**response.headers) elif request.vars.records and not isinstance( request.vars.records,list): request.vars.records=[request.vars.records] elif not request.vars.records: request.vars.records=[] session['_web2py_grid_referrer_'+formname] = url2(vars=request.vars) console = DIV(_class='web2py_console %(header)s %(cornertop)s' % ui) error = None search_actions = DIV(_class='web2py_search_actions') if create: search_actions.append(gridbutton(buttonclass='buttonadd', buttontext=T('Add'), buttonurl=url(args=['new',tablename]))) console.append(search_actions) # if create: # add = gridbutton( # buttonclass='buttonadd', # buttontext='Add', # buttonurl=url(args=['new',tablename])) # if not searchable: # console.append(add) else: add = '' if searchable: sfields = reduce(lambda a,b:a+b, [[f for f in t if f.readable] for t in tables]) if isinstance(search_widget,dict): search_widget = search_widget[tablename] if search_widget=='default': search_menu = SQLFORM.search_menu(sfields) search_widget = lambda sfield, url: CAT(add,FORM( INPUT(_name='keywords',_value=request.vars.keywords, _id='web2py_keywords',_onfocus="jQuery('#w2p_query_fields').change();jQuery('#w2p_query_panel').slideDown();"), INPUT(_type='submit',_value=T('Search'),_class="btn"), INPUT(_type='submit',_value=T('Clear'),_class="btn", _onclick="jQuery('#web2py_keywords').val('');"), _method="GET",_action=url),search_menu) form = search_widget and search_widget(sfields,url()) or '' console.append(form) keywords = request.vars.get('keywords','') try: if callable(searchable): subquery = searchable(sfields, keywords) else: subquery = SQLFORM.build_query(sfields, keywords) except RuntimeError: subquery = None error = T('Invalid query') else: subquery = None if subquery: dbset = dbset(subquery) try: if groupby: nrows = len(dbset.select(*groupfields, join=join, left=left, groupby=groupby, having=having, cacheable=True)) elif left or join: nrows = dbset.select('count(*)',join=join,left=left, cacheable=True).first()['count(*)'] # if left or groupby: # c = 'count(*)' # nrows = dbset.select(c,left=left,cacheable=True, # groupby=groupby).first()[c] else: nrows = dbset.count() except: nrows = 0 error = T('Unsupported query') order = request.vars.order or '' if sortable: if order and not order=='None': if groupby: if str(groupby[0]).find(order)>-1: tablename,fieldname = order.split('~')[-1].split('.',1) sort_field = db[tablename][fieldname] exception = sort_field.type in ('date','datetime','time') if exception: orderby = (order[:1]=='~' and sort_field) or ~sort_field else: orderby = (order[:1]=='~' and ~sort_field) or sort_field else: tablename,fieldname = order.split('~')[-1].split('.',1) gfields = str(groupfields[0]).split(",") for gfield in gfields: if len(gfield.split(" AS "))>1: if gfield.split(" AS ")[1]==fieldname: if str(gfield.split(" AS ")[0]).find("SUM")>-1: sort_field = db[tablename][fieldname].sum() elif str(gfield.split(" AS ")[0]).find("COUNT")>-1: sort_field = db[tablename][fieldname].count() elif str(gfield.split(" AS ")[0]).find("MIN")>-1: sort_field = db[tablename][fieldname].min() elif str(gfield.split(" AS ")[0]).find("MAX")>-1: sort_field = db[tablename][fieldname].max() elif str(gfield.split(" AS ")[0]).find("LENGTH")>-1: sort_field = db[tablename][fieldname].len() else: break orderby = (order[:1]=='~' and ~sort_field) or sort_field break else: tablename,fieldname = order.split('~')[-1].split('.',1) sort_field = db[tablename][fieldname] exception = sort_field.type in ('date','datetime','time') if exception: orderby = (order[:1]=='~' and sort_field) or ~sort_field else: orderby = (order[:1]=='~' and ~sort_field) or sort_field head = TR(_class=ui.get('header')) if selectable: head.append(TH(_class=ui.get('default'))) for field in fields: if columns and not str(field) in columns: continue if not field.readable: continue key = str(field) header = headers.get(str(field), hasattr(field,'label') and field.label or key) if sortable: if key == order: key, marker = '~'+order, sorter_icons[0] elif key == order[1:]: marker = sorter_icons[1] else: marker = '' header = A(header,marker,_href=url(vars=dict( keywords=request.vars.keywords or '', order=key)),_class=trap_class()) head.append(TH(header, _class=ui.get('default'))) if links and links_in_grid: for link in links: if isinstance(link,dict): head.append(TH(link['header'], _class=ui.get('default'))) # Include extra column for buttons if needed. include_buttons_column = (details or editable or deletable or (links and links_in_grid and not all([isinstance(link, dict) for link in links]))) if include_buttons_column: head.insert(0,TH(_class=ui.get('default',''))) # head.append(TH(_class=ui.get('default'))) paginator = UL() if paginate and paginate<nrows: npages,reminder = divmod(nrows,paginate) if reminder: npages+=1 try: page = int(request.vars.page or 1)-1 except ValueError: page = 0 limitby = (paginate*page,paginate*(page+1)) def self_link(name,p): d = dict(page=p+1) if order: d['order']=order if request.vars.keywords: d['keywords']=request.vars.keywords return A(name,_href=url(vars=d),_class=trap_class()) NPAGES = 5 # window is 2*NPAGES if page>NPAGES+1: paginator.append(LI(self_link('<<',0))) if page>NPAGES: paginator.append(LI(self_link('<',page-1))) pages = range(max(0,page-NPAGES),min(page+NPAGES,npages)) for p in pages: if p == page: paginator.append(LI(A(p+1,_onclick='return false'), _class=trap_class('current'))) else: paginator.append(LI(self_link(p+1,p))) if page<npages-NPAGES: paginator.append(LI(self_link('>',page+1))) if page<npages-NPAGES-1: paginator.append(LI(self_link('>>',npages-1))) else: limitby = None try: table_fields = [f for f in fields if f._tablename in tablenames] if groupby: rows = dbset.select(*groupfields,join=join,left=left,groupby=groupby,having=having,orderby=orderby,limitby=limitby,cacheable=True) else: rows = dbset.select(join=join,left=left,orderby=orderby,limitby=limitby,cacheable=True,*table_fields) # rows = dbset.select(left=left,orderby=orderby, # groupby=groupby,limitby=limitby, # cacheable=True,*table_fields) except SyntaxError: rows = None error = T("Query Not Supported") if nrows: message = error or T('%(nrows)s records found') % dict(nrows=nrows) console.append(DIV(message,_class='web2py_counter')) if rows: htmltable = TABLE(THEAD(head)) tbody = TBODY() numrec=0 for row in rows: if numrec % 2 == 0: classtr = 'even' else: classtr = 'odd' numrec+=1 id = row[field_id] #@ReservedAssignment if id: rid = id if callable(rid): ### can this ever be callable? rid = rid(row) tr = TR(_id=rid, _class='%s %s' % (classtr, 'with_id')) else: tr = TR(_class=classtr) if selectable: tr.append(INPUT(_type="checkbox",_name="records",_value=id, value=request.vars.records)) for field in fields: if not str(field) in columns: continue if not field.readable: continue if field.type=='blob': continue value = row[field] maxlength = maxtextlengths.get(str(field),maxtextlength) if field.represent: try: value=field.represent(value,row) except Exception: try: value=field.represent(value,row[field._tablename]) except Exception: pass elif field.type=='boolean': value = INPUT(_type="checkbox",_checked = value, _disabled=True) elif field.type=='upload': if value: if callable(upload): value = A(current.T('file'), _href=upload(value)) elif upload: value = A(current.T('file'), _href='%s/%s' % (upload, value)) else: value = '' if isinstance(value,str): value = truncate_string(value,maxlength) elif not isinstance(value,DIV): value = field.formatter(value) if not include_buttons_column: tr.append(TD(value,_style="padding:10px;")) else: tr.append(TD(value)) row_buttons = TD(_class='row_buttons') if links and links_in_grid: for link in links: if isinstance(link, dict): tr.append(TD(link['body'](row))) else: if link(row): row_buttons.append(link(row)) if include_buttons_column: if details and (not callable(details) or details(row)): row_buttons.append(gridbutton( 'buttonview', 'View', url(args=['view',tablename,id]))) if editable and (not callable(editable) or editable(row)): row_buttons.append(gridbutton( 'buttonedit', 'Edit', url(args=['edit',tablename,id]))) if deletable and (not callable(deletable) or deletable(row)): row_buttons.append(gridbutton( 'buttondelete', 'Delete', callback=url(args=['delete',tablename,id]), delete='tr')) #tr.append(row_buttons) tr.insert(0,row_buttons) tbody.append(tr) htmltable.append(tbody) htmltable = DIV(htmltable,_style='width:100%;overflow-x:auto') if selectable: htmltable = FORM(htmltable,INPUT(_type="submit")) if htmltable.process(formname=formname).accepted:# htmltable.vars.records = htmltable.vars.records or [] htmltable.vars.records = htmltable.vars.records if type(htmltable.vars.records) == list else [htmltable.vars.records] records = [int(r) for r in htmltable.vars.records] selectable(records) redirect(referrer) else: htmltable = DIV(current.T('No records found')) if csv and nrows: export_links =[] for k,v in sorted(exportManager.items()): label = v[1] if hasattr(v, "__getitem__") else k link = url2(vars=dict( order=request.vars.order or '', _export_type=k, keywords=request.vars.keywords or '')) export_links.append(A(T(label),_href=link)) export_menu = \ DIV(T('Export:'),_class="w2p_export_menu",*export_links) else: export_menu = None res = DIV(console,DIV(htmltable,_class="web2py_table"), _class='%s %s' % (_class, ui.get('widget'))) if paginator.components: res.append( DIV(paginator, _class="web2py_paginator %(header)s %(cornerbottom)s"%ui)) if export_menu: res.append(export_menu) res.create_form = create_form res.update_form = update_form res.view_form = view_form res.search_form = search_form return res
def test_TR(self): self.assertEqual( TR('<>', _a='1', _b='2').xml(), b'<tr a="1" b="2"><td><></td></tr>')
def widget(cls, field, value, disable=False, auth_user_permissions=None, **attributes): mylogger.debug(message='auth_user_permissions:%s' % auth_user_permissions) mylogger.debug(message='value:%s' % value) _widget = super(PermissionWidget, cls).widget(field, value, cols=5, **attributes) _hidden_fields = [] for e in _widget.elements('input'): _value = e.attributes[ '_value'] if '_value' in e.attributes else None _name = e.attributes['_name'] checked = e.attributes[ '_checked'] == 'checked' if '_checked' in e.attributes else False mylogger.debug(message='_value:%s' % _value) mylogger.debug(message='_name:%s' % _name) # tip to "disable" input with None value if _value is None: e.attributes['_name'] = '%s-renamed-to-disable' % _name # disabling checkboxes for default permissions if (_value and _value in current.settings['disabled_permissions'].keys() ) or disable: mylogger.debug(message='NM') e.update(_disabled='disabled') e.update(_class='NM') # checking checkboxes for default permissions set to True # adding an hidden field to pass the value in the form if not disable and current.settings['disabled_permissions'][ _value]: e.update(_checked='checked') _hidden_fields.append( INPUT(_type='hidden', _value=_value, _name=_name)) # hidding checkboxes for permissions not owned by the authenticated user # to avoid action elif (auth_user_permissions is not None) and (_value not in auth_user_permissions): mylogger.debug(message='blocked') e.update(_style='display: none;') if checked: e.update(_class='blocked') try: e.__delitem__('_checked') except KeyError: pass # disabling the hidden if the permission was not set # we could also remove the input if not checked: e.update(_disabled='disabled') _v_header1 = [ cc.get_string("PRODUCT_CARD"), cc.get_string("PRODUCT_CARD_RESTRICTED"), cc.get_string("STORAGE_CARD"), cc.get_string("STORAGE_ARCHIVE"), cc.get_string("STORE_LOCATION"), cc.get_string("ENTITY"), cc.get_string("USER"), cc.get_string("COC"), cc.get_string("SUPPLIER"), cc.get_string("MESSAGE"), cc.get_string("COMMAND") ] _v_header2 = ['', '', '*', '*', '*', '*', '*', '', '', '**', ''] _i = 0 for e in _widget.elements('tr')[:11]: e.insert(0, _v_header1[_i]) _i = _i + 1 _i = 0 for e in _widget.elements('tr')[:11]: e.insert(6, _v_header2[_i]) _i = _i + 1 _h_legend = TR( TR(TD('S: %s' % cc.get_string("PERMISSION_SELECT"), _colspan="7")), TR(TD('R: %s' % cc.get_string("PERMISSION_READ"), _colspan="7")), TR(TD('U: %s' % cc.get_string("PERMISSION_UPDATE"), _colspan="7")), TR(TD('C: %s' % cc.get_string("PERMISSION_CREATE"), _colspan="7")), TR(TD('D: %s' % cc.get_string("PERMISSION_DELETE"), _colspan="7")), TR( TD('*: %s' % cc.get_string("PERMISSION_IN_HIS_ENTITY"), _colspan="7")), TR( TD('**: %s' % cc.get_string("PERMISSION_HIS_MESSAGE"), _colspan="7"))) _h_header = TR(TH(''), TH('S'), TH('R'), TH('U'), TH('C'), TH('D'), TH('')) _widget.element('table').insert(0, _h_header) _widget.element('table').insert(0, _h_legend) _widget.components.extend(_hidden_fields) return _widget
def grid( query, fields=None, field_id=None, left=None, join=None, #! orderby=None, groupby=None, groupfields=None, #! having=None, #! headers={}, searchable=False, #True, sortable=True, paginate=20, pagename="page", #! deletable=False, #! True, editable=True, details=False, #! True, selectable=None, create=False, #!True, csv=False, #!True, links=None, links_in_grid=True, upload='<default>', args=[], user_signature=False, #!True, maxtextlengths={}, maxtextlength=20, onvalidation=None, oncreate=None, onupdate=None, ondelete=None, sorter_icons=(XML('↑'), XML('↓')), ui='web2py', showbuttontext=True, _class="web2py_grid", formname='web2py_grid', search_widget='default', ignore_rw=False, formstyle='table3cols', exportclasses=None, formargs={}, createargs={}, editargs={}, viewargs={}, ): # jQuery UI ThemeRoller classes (empty if ui is disabled) if ui == 'jquery-ui': ui = dict( widget='ui-widget', header='ui-widget-header', content='ui-widget-content', default='ui-state-default', cornerall='ui-corner-all', cornertop='ui-corner-top', cornerbottom='ui-corner-bottom', button='ui-button-text-icon-primary', buttontext='ui-button-text', buttonadd='ui-icon ui-icon-plusthick', buttonback='ui-icon ui-icon-arrowreturnthick-1-w', buttonexport='ui-icon ui-icon-transferthick-e-w', buttondelete='ui-icon ui-icon-trash', buttonedit='ui-icon ui-icon-pencil', buttontable='ui-icon ui-icon-triangle-1-e', buttonview='ui-icon ui-icon-zoomin', ) elif ui == 'web2py': ui = dict( widget='', header='', content='', default='', cornerall='', cornertop='', cornerbottom='', button='button btn', buttontext='buttontext button', buttonadd='icon plus icon-plus', buttonback='icon leftarrow icon-arrow-left', buttonexport='icon downarrow icon-download', buttondelete='icon trash icon-trash', buttonedit='icon pen icon-pencil', buttontable='icon rightarrow icon-arrow-right', buttonview='icon magnifier icon-zoom-in', ) elif not isinstance(ui, dict): raise RuntimeError, 'SQLFORM.grid ui argument must be a dictionary' db = query._db T = current.T request = current.request session = current.session response = current.response wenabled = (not user_signature or (session.auth and session.auth.user)) create = wenabled and create editable = wenabled and editable deletable = wenabled and deletable def url(**b): b['args'] = args + b.get('args', []) b['hash_vars'] = False b['user_signature'] = user_signature return URL(**b) def url2(**b): b['args'] = request.args + b.get('args', []) b['hash_vars'] = False b['user_signature'] = user_signature return URL(**b) referrer = session.get('_web2py_grid_referrer_' + formname, url()) # if not user_signature every action is accessible # else forbid access unless # - url is based url # - url has valid signature (vars are not signed, only path_info) # = url does not contain 'create','delete','edit' (readonly) if user_signature: if not ('/'.join(str(a) for a in args) == '/'.join(request.args) # or # URL.verify(request,user_signature=user_signature, # hash_vars=False) or not ('create' in request.args or 'delete' in request.args or 'edit' in request.args)): session.flash = T('not authorized') redirect(referrer) def gridbutton(buttonclass='buttonadd', buttontext='Add', buttonurl=url(args=[]), callback=None, delete=None, trap=True): if showbuttontext: if callback: return A(SPAN(_class=ui.get(buttonclass)), SPAN(T(buttontext), _title=buttontext, _class=ui.get('buttontext')), callback=callback, delete=delete, _class=trap_class(ui.get('button'), trap)) else: return A(SPAN(_class=ui.get(buttonclass)), SPAN(T(buttontext), _title=buttontext, _class=ui.get('buttontext')), _href=buttonurl, _class=trap_class(ui.get('button'), trap)) else: if callback: return A(SPAN(_class=ui.get(buttonclass)), callback=callback, delete=delete, _title=buttontext, _class=trap_class(ui.get('buttontext'), trap)) else: return A(SPAN(_class=ui.get(buttonclass)), _href=buttonurl, _title=buttontext, _class=trap_class(ui.get('buttontext'), trap)) dbset = db(query) tablenames = db._adapter.tables(dbset.query) #if left!=None: tablenames+=db._adapter.tables(left) if left != None: if isinstance(left, list): for _left in left: tablenames = tablenames + db._adapter.tables(_left) else: tablenames = tablenames + db._adapter.tables(left) if join != None: if isinstance(join, list): for _join in join: tablenames = tablenames + db._adapter.tables(_join) else: tablenames = tablenames + db._adapter.tables(join) tables = [db[tablename] for tablename in tablenames] if not fields: fields = reduce(lambda a, b: a + b, [[field for field in table] for table in tables]) if not field_id: field_id = tables[0]._id columns = [str(field) for field in fields \ if field._tablename in tablenames] if not str(field_id) in [str(f) for f in fields]: fields.append(field_id) table = field_id.table tablename = table._tablename if upload == '<default>': upload = lambda filename: url(args=['download', filename]) if len(request.args) > 1 and request.args[-2] == 'download': stream = response.download(request, db) raise HTTP(200, stream, **response.headers) def buttons(edit=False, view=False, record=None): buttons = DIV( gridbutton('buttonback', 'Back', referrer), _class='form_header row_buttons %(header)s %(cornertop)s' % ui) if edit and (not callable(edit) or edit(record)): args = ['edit', table._tablename, request.args[-1]] buttons.append(gridbutton('buttonedit', 'Edit', url(args=args))) if view: args = ['view', table._tablename, request.args[-1]] buttons.append(gridbutton('buttonview', 'View', url(args=args))) if record and links: for link in links: if isinstance(link, dict): buttons.append(link['body'](record)) elif link(record): buttons.append(link(record)) return buttons formfooter = DIV( _class='form_footer row_buttons %(header)s %(cornerbottom)s' % ui) create_form = update_form = view_form = search_form = None sqlformargs = dict(formargs) if create and len(request.args) > 1 and request.args[-2] == 'new': table = db[request.args[-1]] sqlformargs.update(createargs) create_form = SQLFORM(table, ignore_rw=ignore_rw, formstyle=formstyle, _class='web2py_form', **sqlformargs) create_form.process(formname=formname, next=referrer, onvalidation=onvalidation, onsuccess=oncreate) res = DIV(buttons(), create_form, formfooter, _class=_class) res.create_form = create_form res.update_form = update_form res.view_form = view_form res.search_form = search_form return res elif details and len(request.args) > 2 and request.args[-3] == 'view': table = db[request.args[-2]] record = table(request.args[-1]) or redirect(URL('error')) sqlformargs.update(viewargs) view_form = SQLFORM(table, record, upload=upload, ignore_rw=ignore_rw, formstyle=formstyle, readonly=True, _class='web2py_form', **sqlformargs) res = DIV(buttons(edit=editable, record=record), view_form, formfooter, _class=_class) res.create_form = create_form res.update_form = update_form res.view_form = view_form res.search_form = search_form return res # elif editable and len(request.args)>2 and request.args[-3]=='edit': # table = db[request.args[-2]] # record = table(request.args[-1]) or redirect(URL('error')) # sqlformargs.update(editargs) # update_form = SQLFORM(table, record, upload=upload, ignore_rw=ignore_rw, # formstyle=formstyle, deletable=deletable, # _class='web2py_form', # submit_button=T('Submit'), # delete_label=T('Check to delete'), # **sqlformargs) # update_form.process(formname=formname, # onvalidation=onvalidation, # onsuccess=onupdate, # next=referrer) # res = DIV(buttons(view=details, record=record), # update_form, formfooter, _class=_class) # res.create_form = create_form # res.update_form = update_form # res.view_form = view_form # res.search_form = search_form # return res elif deletable and len( request.args) > 2 and request.args[-3] == 'delete': table = db[request.args[-2]] if ondelete: ondelete(table, request.args[-1]) ret = db(table[table._id.name] == request.args[-1]).delete() return ret exportManager = dict( csv_with_hidden_cols=(ExporterCSV,'CSV (hidden cols)'), csv=(ExporterCSV,'CSV'), xml=(ExporterXML, 'XML'), html=(ExporterHTML, 'HTML'), tsv_with_hidden_cols=\ (ExporterTSV,'TSV (Excel compatible, hidden cols)'), tsv=(ExporterTSV, 'TSV (Excel compatible)')) if not exportclasses is None: exportManager.update(exportclasses) export_type = request.vars._export_type if export_type: order = request.vars.order or '' if sortable: if order and not order == 'None': if order[:1] == '~': sign, rorder = '~', order[1:] else: sign, rorder = '', order tablename, fieldname = rorder.split('.', 1) orderby = db[tablename][fieldname] if sign == '~': orderby = ~orderby table_fields = [f for f in fields if f._tablename in tablenames] if export_type in ('csv_with_hidden_cols', 'tsv_with_hidden_cols'): if request.vars.keywords: try: dbset = dbset( SQLFORM.build_query( fields, request.vars.get('keywords', ''))) rows = dbset.select(cacheable=True) except Exception: response.flash = T('Internal Error') rows = [] else: rows = dbset.select(cacheable=True) else: rows = dbset.select(left=left, orderby=orderby, cacheable=True * columns) if export_type in exportManager: value = exportManager[export_type] clazz = value[0] if hasattr(value, '__getitem__') else value oExp = clazz(rows) filename = '.'.join(('rows', oExp.file_ext)) response.headers['Content-Type'] = oExp.content_type response.headers['Content-Disposition'] = \ 'attachment;filename='+filename+';' raise HTTP(200, oExp.export(), **response.headers) elif request.vars.records and not isinstance(request.vars.records, list): request.vars.records = [request.vars.records] elif not request.vars.records: request.vars.records = [] session['_web2py_grid_referrer_' + formname] = url2(vars=request.vars) console = DIV(_class='web2py_console %(header)s %(cornertop)s' % ui) error = None search_actions = DIV(_class='web2py_search_actions') if create: search_actions.append( gridbutton(buttonclass='buttonadd', buttontext=T('Add'), buttonurl=url(args=['new', tablename]))) console.append(search_actions) # if create: # add = gridbutton( # buttonclass='buttonadd', # buttontext='Add', # buttonurl=url(args=['new',tablename])) # if not searchable: # console.append(add) else: add = '' if searchable: sfields = reduce(lambda a, b: a + b, [[f for f in t if f.readable] for t in tables]) if isinstance(search_widget, dict): search_widget = search_widget[tablename] if search_widget == 'default': search_menu = SQLFORM.search_menu(sfields) search_widget = lambda sfield, url: CAT( add, FORM(INPUT( _name='keywords', _value=request.vars.keywords, _id='web2py_keywords', _onfocus= "jQuery('#w2p_query_fields').change();jQuery('#w2p_query_panel').slideDown();" ), INPUT( _type='submit', _value=T('Search'), _class="btn"), INPUT(_type='submit', _value=T('Clear'), _class="btn", _onclick="jQuery('#web2py_keywords').val('');"), _method="GET", _action=url), search_menu) form = search_widget and search_widget(sfields, url()) or '' console.append(form) keywords = request.vars.get('keywords', '') try: if callable(searchable): subquery = searchable(sfields, keywords) else: subquery = SQLFORM.build_query(sfields, keywords) except RuntimeError: subquery = None error = T('Invalid query') else: subquery = None if subquery: dbset = dbset(subquery) try: if groupby: nrows = len( dbset.select(*groupfields, join=join, left=left, groupby=groupby, having=having, cacheable=True)) elif left or join: nrows = dbset.select('count(*)', join=join, left=left, cacheable=True).first()['count(*)'] # if left or groupby: # c = 'count(*)' # nrows = dbset.select(c,left=left,cacheable=True, # groupby=groupby).first()[c] else: nrows = dbset.count() except: nrows = 0 error = T('Unsupported query') order = request.vars.order or '' if sortable: if order and not order == 'None': if groupby: if str(groupby[0]).find(order) > -1: tablename, fieldname = order.split('~')[-1].split( '.', 1) sort_field = db[tablename][fieldname] exception = sort_field.type in ('date', 'datetime', 'time') if exception: orderby = (order[:1] == '~' and sort_field) or ~sort_field else: orderby = (order[:1] == '~' and ~sort_field) or sort_field else: tablename, fieldname = order.split('~')[-1].split( '.', 1) gfields = str(groupfields[0]).split(",") for gfield in gfields: if len(gfield.split(" AS ")) > 1: if gfield.split(" AS ")[1] == fieldname: if str(gfield.split(" AS ")[0]).find( "SUM") > -1: sort_field = db[tablename][ fieldname].sum() elif str(gfield.split(" AS ")[0]).find( "COUNT") > -1: sort_field = db[tablename][ fieldname].count() elif str(gfield.split(" AS ")[0]).find( "MIN") > -1: sort_field = db[tablename][ fieldname].min() elif str(gfield.split(" AS ")[0]).find( "MAX") > -1: sort_field = db[tablename][ fieldname].max() elif str(gfield.split(" AS ")[0]).find( "LENGTH") > -1: sort_field = db[tablename][ fieldname].len() else: break orderby = (order[:1] == '~' and ~sort_field) or sort_field break else: tablename, fieldname = order.split('~')[-1].split('.', 1) sort_field = db[tablename][fieldname] exception = sort_field.type in ('date', 'datetime', 'time') if exception: orderby = (order[:1] == '~' and sort_field) or ~sort_field else: orderby = (order[:1] == '~' and ~sort_field) or sort_field head = TR(_class=ui.get('header')) if selectable: head.append(TH(_class=ui.get('default'))) for field in fields: if columns and not str(field) in columns: continue if not field.readable: continue key = str(field) header = headers.get( str(field), hasattr(field, 'label') and field.label or key) if sortable: if key == order: key, marker = '~' + order, sorter_icons[0] elif key == order[1:]: marker = sorter_icons[1] else: marker = '' header = A( header, marker, _href=url(vars=dict(keywords=request.vars.keywords or '', order=key)), _class=trap_class()) head.append(TH(header, _class=ui.get('default'))) if links and links_in_grid: for link in links: if isinstance(link, dict): head.append(TH(link['header'], _class=ui.get('default'))) # Include extra column for buttons if needed. include_buttons_column = ( details or editable or deletable or (links and links_in_grid and not all([isinstance(link, dict) for link in links]))) if include_buttons_column: head.insert(0, TH(_class=ui.get('default', ''))) # head.append(TH(_class=ui.get('default'))) paginator = UL() if paginate and paginate < nrows: npages, reminder = divmod(nrows, paginate) if reminder: npages += 1 try: page = int(request.vars.page or 1) - 1 except ValueError: page = 0 limitby = (paginate * page, paginate * (page + 1)) def self_link(name, p): d = dict(page=p + 1) if order: d['order'] = order if request.vars.keywords: d['keywords'] = request.vars.keywords return A(name, _href=url(vars=d), _class=trap_class()) NPAGES = 5 # window is 2*NPAGES if page > NPAGES + 1: paginator.append(LI(self_link('<<', 0))) if page > NPAGES: paginator.append(LI(self_link('<', page - 1))) pages = range(max(0, page - NPAGES), min(page + NPAGES, npages)) for p in pages: if p == page: paginator.append( LI(A(p + 1, _onclick='return false'), _class=trap_class('current'))) else: paginator.append(LI(self_link(p + 1, p))) if page < npages - NPAGES: paginator.append(LI(self_link('>', page + 1))) if page < npages - NPAGES - 1: paginator.append(LI(self_link('>>', npages - 1))) else: limitby = None try: table_fields = [f for f in fields if f._tablename in tablenames] if groupby: rows = dbset.select(*groupfields, join=join, left=left, groupby=groupby, having=having, orderby=orderby, limitby=limitby, cacheable=True) else: rows = dbset.select(join=join, left=left, orderby=orderby, limitby=limitby, cacheable=True, *table_fields) # rows = dbset.select(left=left,orderby=orderby, # groupby=groupby,limitby=limitby, # cacheable=True,*table_fields) except SyntaxError: rows = None error = T("Query Not Supported") if nrows: message = error or T('%(nrows)s records found') % dict(nrows=nrows) console.append(DIV(message, _class='web2py_counter')) if rows: htmltable = TABLE(THEAD(head)) tbody = TBODY() numrec = 0 for row in rows: if numrec % 2 == 0: classtr = 'even' else: classtr = 'odd' numrec += 1 id = row[field_id] #@ReservedAssignment if id: rid = id if callable(rid): ### can this ever be callable? rid = rid(row) tr = TR(_id=rid, _class='%s %s' % (classtr, 'with_id')) else: tr = TR(_class=classtr) if selectable: tr.append( INPUT(_type="checkbox", _name="records", _value=id, value=request.vars.records)) for field in fields: if not str(field) in columns: continue if not field.readable: continue if field.type == 'blob': continue value = row[field] maxlength = maxtextlengths.get(str(field), maxtextlength) if field.represent: try: value = field.represent(value, row) except Exception: try: value = field.represent( value, row[field._tablename]) except Exception: pass elif field.type == 'boolean': value = INPUT(_type="checkbox", _checked=value, _disabled=True) elif field.type == 'upload': if value: if callable(upload): value = A(current.T('file'), _href=upload(value)) elif upload: value = A(current.T('file'), _href='%s/%s' % (upload, value)) else: value = '' if isinstance(value, str): value = truncate_string(value, maxlength) elif not isinstance(value, DIV): value = field.formatter(value) if not include_buttons_column: tr.append(TD(value, _style="padding:10px;")) else: tr.append(TD(value)) row_buttons = TD(_class='row_buttons') if links and links_in_grid: for link in links: if isinstance(link, dict): tr.append(TD(link['body'](row))) else: if link(row): row_buttons.append(link(row)) if include_buttons_column: if details and (not callable(details) or details(row)): row_buttons.append( gridbutton('buttonview', 'View', url(args=['view', tablename, id]))) if editable and (not callable(editable) or editable(row)): row_buttons.append( gridbutton('buttonedit', 'Edit', url(args=['edit', tablename, id]))) if deletable and (not callable(deletable) or deletable(row)): row_buttons.append( gridbutton( 'buttondelete', 'Delete', callback=url(args=['delete', tablename, id]), delete='tr')) #tr.append(row_buttons) tr.insert(0, row_buttons) tbody.append(tr) htmltable.append(tbody) htmltable = DIV(htmltable, _style='width:100%;overflow-x:auto') if selectable: htmltable = FORM(htmltable, INPUT(_type="submit")) if htmltable.process(formname=formname).accepted: # htmltable.vars.records = htmltable.vars.records or [] htmltable.vars.records = htmltable.vars.records if type( htmltable.vars.records) == list else [ htmltable.vars.records ] records = [int(r) for r in htmltable.vars.records] selectable(records) redirect(referrer) else: htmltable = DIV(current.T('No records found')) if csv and nrows: export_links = [] for k, v in sorted(exportManager.items()): label = v[1] if hasattr(v, "__getitem__") else k link = url2(vars=dict(order=request.vars.order or '', _export_type=k, keywords=request.vars.keywords or '')) export_links.append(A(T(label), _href=link)) export_menu = \ DIV(T('Export:'),_class="w2p_export_menu",*export_links) else: export_menu = None res = DIV(console, DIV(htmltable, _class="web2py_table"), _class='%s %s' % (_class, ui.get('widget'))) if paginator.components: res.append( DIV(paginator, _class="web2py_paginator %(header)s %(cornerbottom)s" % ui)) if export_menu: res.append(export_menu) res.create_form = create_form res.update_form = update_form res.view_form = view_form res.search_form = search_form return res
def exportToReport(): if request.vars.database and request.vars.username: if request.vars.code in ("base64", "base64all"): if request.vars.password: password = base64.b64decode(request.vars.password) else: password = None validator = getLogin(base64.b64decode(request.vars.database), base64.b64decode(request.vars.username), password) else: if request.vars.password: password = request.vars.password else: password = None validator = getLogin(request.vars.database, request.vars.username, password) if validator["valid"] == False: return validator["message"] else: return T('Missing login parameter(s)!') params = {} filters = {} if request.vars.reportcode: if request.vars.code in ("base64", "base64all"): params["reportcode"] = base64.b64decode(request.vars.reportcode) else: params["reportcode"] = request.vars.reportcode elif request.vars.report_id: if request.vars.code in ("base64", "base64all"): params["report_id"] = base64.b64decode(request.vars.report_id) else: params["report_id"] = request.vars.report_id else: return T('Missing reportcode or report_id parameter!') if request.vars.filters: if request.vars.code in ("base64", "base64all"): filters = getParamList(base64.b64decode(request.vars.filters))[0] else: filters = getParamList(request.vars.filters)[0] else: return T('Missing filters parameter!') if request.vars.output: if request.vars.code in ("base64", "base64all"): params["output"] = base64.b64decode(request.vars.output) else: params["output"] = request.vars.output else: params["output"] = "html" if request.vars.orientation: if request.vars.code in ("base64", "base64all"): params["orientation"] = base64.b64decode(request.vars.orientation) else: params["orientation"] = request.vars.orientation else: params["orientation"] = "P" if request.vars.size: if request.vars.code in ("base64", "base64all"): params["size"] = base64.b64decode(request.vars.size) else: params["size"] = request.vars.size else: params["size"] = "A4" if params["output"] == "printer": if not request.vars.printername: return T('Missing printername parameter!') printer_prop = dbout.check_printer(request.vars.printername) if printer_prop["state"] == False: return printer_prop["error_message"] params["output"] = "pdf" if request.vars.copies: try: copies = int(request.vars.copies) except: copies = 1 else: copies = 1 else: printer_prop = None report_tmp = dbout.getReport(params, filters) if type(report_tmp).__name__ == "str": if report_tmp == "NODATA": return HTML( HEAD( TITLE("Nervatura Report"), LINK(_rel="shortcut icon", _href=URL('static', 'favicon.ico'), _type="image/x-icon")), BODY( DIV(CENTER( TABLE(TR( TD(IMG( _src=URL('static', 'images/nodata.png'), _style="border: solid;border-color: #FFFFFF;"), _style= "text-align: center;vertical-align: middle;font-weight: bold;font-family: sans-serif;font-size: 20px;" )), _style= "background-color:#FFFFFF;color:#444444;margin-top:200px;" )), _style="width:100%;height:100%")), _style="background-color:#000000;") else: return report_tmp if printer_prop: print_item = dbout.printReport(printer_prop, report_tmp["template"], "Nervatura Report", copies, params["orientation"], params["size"]) if print_item["state"] == False: return print_item["error_message"] return "OK" elif report_tmp["filetype"] == "ntr": if params["output"] == "xml": response.headers['Content-Type'] = 'text/xml' elif params["output"] == "pdf": response.headers['Content-Type'] = 'application/pdf' if request.vars.code == "base64all": return base64.b64encode(report_tmp["template"]) else: return report_tmp["template"] elif report_tmp["filetype"] == "xls": response.headers['Content-Type'] = "application/vnd.ms-excel" response.headers[ 'Content-Disposition'] = 'attachment;filename="NervaturaReport.xls"' if request.vars.code == "base64all": return base64.b64encode(report_tmp["template"]) else: return report_tmp["template"] elif report_tmp["filetype"] == "html": response.view = "default/report.html" response.title = report_tmp["data"]["title"] response.subtitle = "" import StringIO report_tmp["template"] = response.render( StringIO.StringIO(report_tmp["template"]), report_tmp["data"]) return dict(template=XML(report_tmp["template"])) else: if request.vars.code == "base64all": return base64.b64encode(report_tmp["template"]) else: return report_tmp["template"]
def key_table(keys): return TABLE( TR(TD(B(T('Key'))), TD(B(T('Time in Cache (h:m:s)')))), *[TR(TD(k[0]), TD('%02d:%02d:%02d' % k[1])) for k in keys], **dict(_class='cache-keys', _style="border-collapse: separate; border-spacing: .5em;"))
groups_id = ns.valid.get_groups_id('nervatype', frm_filter.vars.label) if groups_id: query = query & ((ns.db.ui_report.nervatype == groups_id)) else: query = query & ( (ns.db.ui_report.transtype == ns.valid.get_groups_id( 'transtype', frm_filter.vars.label))) reportkey_rows = ns.db(query).select( ns.db.ui_report.reportkey, orderby=ns.db.ui_report.repname) [dbs_reports.append(row.reportkey) for row in reportkey_rows] else: response.flash = str(ns.error_message) htmltable = TABLE( THEAD(TR(TH(), TH(), TH(), TH(T("Name") + "/" + T("Description"))))) tbody = TBODY() numrec = 0 for row in nas_reports["reports"]: cmd_edit = INPUT(_value=T("Edit template"), _disabled="", _type="button") def filter_row(): if frm_filter.vars.repname and frm_filter.vars.repname != "": if str(row["repname"].lower()).find( frm_filter.vars.repname.lower()) == -1 and str( row["description"].lower()).find( frm_filter.vars.repname.lower()) == -1: return False if frm_filter.vars.label and frm_filter.vars.label != "":