Пример #1
0
def informe_mes_empleado():
    empleados = db(db.empleado.is_active is True).select(db.empleado.ALL)
    fempl = ([" "] +
             [f"{p.user_code} {p.nombre} {p.apellido}" for p in empleados])
    form = FORM(
        CENTER(
            H4('Marcadas del personal'),
            TABLE(
                TR(
                    TAG('<label class "control-label">Persona</label>'),
                    SELECT(fempl,
                           _name='fempleado',
                           _type='text',
                           _id="persona",
                           _class="form-control string")),
                TR(
                    TAG('<label class "control-label">Periodo desde</label>'),
                    INPUT(_name='fdesde',
                          _type='date',
                          _id="mesanio",
                          _class="form-control string",
                          requires=IS_NOT_EMPTY())),
                TR(
                    TAG('<label class "control-label">Periodo hasta</label>'),
                    INPUT(
                        _name='fhasta',
                        _type='date',
                        _id="mesanio",
                        _class="form-control string",
                    ))), BR(),
            INPUT(_type="submit",
                  _class="btn btn-primary btn-medium",
                  _value='Continuar')))
    if form.accepts(request, session):
        session.empleado = request.vars['fempleado']
        session.user_code = request.vars['fempleado'].split()[0]
        session.fdesde = request.vars['fdesde']
        session.fhasta = request.vars['fhasta']
        log(f"seleccionado {session.empleado}")
        log(f"desde: {session.fdesde} hasta {session.fhasta}")
        # selector = (db.empleado.user_code == user_code)
        # usuario = db(selector).select().first().as_dict()
        session.tdesde = datetime.datetime.strptime(session.fdesde, '%Y-%m-%d')
        session.thasta = datetime.datetime.strptime(session.fhasta, '%Y-%m-%d')
        lista = aplico_politica(session.user_code, session.fdesde,
                                session.fhasta)
        nombre_archivo = f'''{session.empleado}
        -{session.fdesde}-{session.fhasta}'''
        session.table = list_dict_to_table_sortable(lista, nombre_archivo)
        redirect(URL('informe'))
    else:
        log(f'acceso {request.function}')
    return dict(form=form)
Пример #2
0
    def layout(item):
        """ Language menu layout

            options for each entry:
                - lang_code: the language code
                - lang_name: the language name
            option for the menu
                - current_language: code of the current language
        """

        if item.enabled:
            if item.components:
                # The language menu itself
                current_language = current.T.accepted_language
                items = item.render_components()
                select = SELECT(
                    items,
                    value=current_language,
                    _name="_language",
                    # @ToDo T:
                    _title="Language Selection",
                    _onchange=
                    "S3.reloadWithQueryStringVars({'_language':$(this).val()});"
                )
                form = FORM(select,
                            _class="language-selector",
                            _name="_language",
                            _action="",
                            _method="get")
                return form
            else:
                # A language entry
                return OPTION(item.opts.lang_name, _value=item.opts.lang_code)
        else:
            return None
Пример #3
0
 def confirm(text='OK', btntype="btn-default", buttons=None, hidden=None):
     if not buttons:
         buttons = {}
     if not hidden:
         hidden = {}
     inputs = [INPUT(_type='button',
                     _value=name,
                     _class='btn btn-default',
                     _onclick=FORM.REDIRECT_JS % link)
               for name, link in buttons.iteritems()]
     inputs += [INPUT(_type='hidden',
                      _name=name,
                      _value=value)
                for name, value in hidden.iteritems()]
     form = FORM(INPUT(_type='submit', _value=text, _class='btn {0}'.format(btntype)), *inputs,
                 formstyle='bootstrap3_stacked')
     form.process()
     return form
Пример #4
0
def car_model_form():
    """
    Creates a form using web2py helpers.

    This is the most manual method of creating a form. It allows
    the specification of every aspect of the resulting html
    elements.

    Some notes:
        Validators must be specified during the INPUT fields creation.
        form.accepts() must be called to process the form.
        Database insertion must be handled manually.
    """

    # Must repeat the field validators declared in the db.py
    car_model_input=INPUT(_name='car_model', requires=IS_NOT_EMPTY())
    base_price_input=INPUT(_name='base_price', requires=IS_NOT_EMPTY())

    # Manual creation of the html table
    table_rows = []
    table_rows.append(TR('Car Model:', car_model_input))
    table_rows.append(TR('Base Price:', base_price_input))
    # Fields starting with _ are passed to the html as attribute elements
    table_rows.append(TR(TD(INPUT(_type='submit'), _colspan='2', _align='center')))
    table = TABLE(table_rows)

    form = FORM(table)

    # Processing the form submition
    if form.accepts(request,session):
        # Retriving the form fields
        form_car_model = form.vars.car_model
        form_base_price = form.vars.base_price
        # Inserting in the database
        db.car_model.insert(car_model=form_car_model, car_base_price=form_base_price)
        # Tell the user about the insertion
        response.flash = 'New car: ' + form_car_model
    elif form.errors:
        response.flash = 'Form has errors'
    else:
        response.flash = 'Please fill the form'

    return dict(car_model_form=form)
Пример #5
0
 def search(self):
     q = self.request.vars.q or None
     self.context.form = FORM(INPUT(_type="text",
                                    _name="q",
                                    _id="q",
                                    _value=q or ''),
                              _method="GET")
     if q:
         query = (self.db.Article.search_index.like("%" + q + "%")) | (
             self.db.Article.tags.contains(q))
         self.context.results = self.db(query).select()
     else:
         self.context.results = []
Пример #6
0
    def get_form(self):
        """
        """
        db = current.db
        form = FORM(INPUT(_type='file', _name='data'), INPUT(_type='submit'))
        output = None
        if form.process().accepted:
            csvfile = db.parse_csv(form.vars.data.file)

            # for every table
            #for table in db.tables:
                ## for every uuid, delete all but the latest
                #items = db(db[table]).select(db[table].id,
                        #db[table].uuid,
                        #orderby=db[table].modified_on,
                        #groupby=db[table].uuid)
                #for item in items:
                    #db((db[table].uuid==item.uuid)&
                       #(db[table].id!=item.id)).delete()
            pprint(csvfile)
            output = pprint(csvfile)

        return {'form': form, 'output': output}
Пример #7
0
def index():
    log('acceso')
    # menu favoritos
    form = CENTER(
        FORM(DIV(I(' Personal',
                   _class='fa fa-ticket fa-2x',
                   _id='tit_minigrid'),
                 DIV(grand_button('empleados',
                                  'admin_tabla',
                                  'fa-cart-plus',
                                  vars={'tabla': 'empleado'}),
                     grand_button('ver marcadas', 'admin_tabla',
                                  'fa-th-large'),
                     grand_button('informe mes empleado',
                                  'informe_mes_empleado', 'fa-truck'),
                     _id='mini_grid'),
                 _id='indexdiv'),
             _id='panel_grid'))
    return dict(form=form)
Пример #8
0
    def get_html(self):
        card_content = DIV(FORM(
            INPUT(_type="text",
                  _name="q",
                  _placeholder="Type some tag...",
                  _autocomplete="off"),
            INPUT(_type="submit", _value="Search", _class="btn btn-default"),
            _action=URL("problems", "search"),
            _method="GET",
            _class="col offset-s1 s10 search-by-tag-card-submit"),
                           _class="row")

        card_html = BaseCard.get_html(
            self,
            **dict(card_title=self.card_title,
                   card_content=card_content,
                   cta_links=self.get_cta_html(),
                   card_color_class="white",
                   card_text_color_class="black-text"))
        return card_html
Пример #9
0
def getEditgameBtn(game, user):
    """
	Gets a dictionary of buttons that do stuff for the edit game page.

	Keyword Arguments:
	game -- row representing the current game
	user -- row representing the current user

	Return Values:
	btn -- dictionary of web2py forms
	        -- 'back'   Back To Game
	        -- 'delete' Delete Game
	"""

    from gluon import URL, INPUT, FORM, A, redirect

    btn = {'back': 'back', 'delete': 'delete'}

    link = A('Back to Game',
             _class='btn btn-large btn-inverse btn-block',
             _href=URL('default', 'game', args=game.id))
    btn['back'] = link

    button = INPUT(
        _type='submit',
        _value='(Host) Delete Game',
        _class='btn btn-small btn-block abtn-small',
        _onclick=
        'return confirm(\'Are you sure you want to delete this game?\');')
    formDelete = FORM(button)
    btn['delete'] = formDelete

    if btn['delete'].process().accepted:
        deleteGame(game.id, user)
        redirect(URL('default', 'current'))

    return btn
Пример #10
0
    def merge(self, r, **attr):
        """
            Merge form for two records

            @param r: the S3Request
            @param **attr: the controller attributes for the request

            @note: this method can always only be POSTed, and requires
                   both "selected" and "mode" in post_vars, as well as
                   the duplicate bookmarks list in session.s3
        """

        T = current.T
        session = current.session
        response = current.response

        output = dict()
        tablename = self.tablename

        # Get the duplicate bookmarks
        s3 = session.s3
        DEDUPLICATE = self.DEDUPLICATE
        if DEDUPLICATE in s3:
            bookmarks = s3[DEDUPLICATE]
            if tablename in bookmarks:
                record_ids = bookmarks[tablename]

        # Process the post variables
        post_vars = r.post_vars
        mode = post_vars.get("mode")
        selected = post_vars.get("selected", "")
        selected = selected.split(",")
        if mode == "Inclusive":
            ids = selected
        elif mode == "Exclusive":
            ids = [i for i in record_ids if i not in selected]
        else:
            # Error
            ids = []
        if len(ids) != 2:
            r.error(501, T("Please select exactly two records"),
                    next = r.url(id=0, vars={}))

        # Get the selected records
        table = self.table
        query = (table._id == ids[0]) | (table._id == ids[1])
        orderby = table.created_on if "created_on" in table else None
        rows = current.db(query).select(orderby=orderby,
                                        limitby=(0, 2))
        if len(rows) != 2:
            r.error(404, current.ERROR.BAD_RECORD, next = r.url(id=0, vars={}))
        original = rows[0]
        duplicate = rows[1]

        # Prepare form construction
        formfields = [f for f in table if f.readable or f.writable]

        ORIGINAL, DUPLICATE, KEEP = self.ORIGINAL, self.DUPLICATE, self.KEEP
        keep_o = KEEP.o in post_vars and post_vars[KEEP.o]
        keep_d = KEEP.d in post_vars and post_vars[KEEP.d]

        trs = []
        init_requires = self.init_requires
        index = 1
        num_fields = len(formfields)

        for f in formfields:

            # Render the widgets
            oid = "%s_%s" % (ORIGINAL, f.name)
            did = "%s_%s" % (DUPLICATE, f.name)
            sid = "swap_%s" % f.name
            init_requires(f, original[f], duplicate[f])
            if keep_o or not any((keep_o, keep_d)):
                owidget = self.widget(f, original[f], _name=oid, _id=oid, _tabindex=index)
            else:
                try:
                    owidget = s3_represent_value(f, value=original[f])
                except:
                    owidget = s3_str(original[f])
            if keep_d or not any((keep_o, keep_d)):
                dwidget = self.widget(f, duplicate[f], _name=did, _id=did)
            else:
                try:
                    dwidget = s3_represent_value(f, value=duplicate[f])
                except:
                    dwidget = s3_str(duplicate[f])

            # Swap button
            if not any((keep_o, keep_d)):
                swap = INPUT(_value="<-->",
                             _class="swap-button",
                             _id=sid,
                             _type="button",
                             _tabindex = index+num_fields)
            else:
                swap = DIV(_class="swap-button")

            if owidget is None or dwidget is None:
                continue

            # Render label row
            label = f.label
            trs.append(TR(TD(label, _class="w2p_fl"),
                          TD(),
                          TD(label, _class="w2p_fl")))

            # Append widget row
            trs.append(TR(TD(owidget, _class="mwidget"),
                          TD(swap),
                          TD(dwidget, _class="mwidget")))

            index = index + 1
        # Show created_on/created_by for each record
        if "created_on" in table:
            original_date = original.created_on
            duplicate_date = duplicate.created_on
            if "created_by" in table:
                represent = table.created_by.represent
                original_author = represent(original.created_by)
                duplicate_author = represent(duplicate.created_by)
                created = T("Created on %s by %s")
                original_created = created % (original_date, original_author)
                duplicate_created = created % (duplicate_date, duplicate_author)
            else:
                created = T("Created on %s")
                original_created = created % original_date
                duplicate_created = created % duplicate_date
        else:
            original_created = ""
            duplicate_created = ""

        # Page title and subtitle
        output["title"] = T("Merge records")
        #output["subtitle"] = self.crud_string(tablename, "title_list")

        # Submit buttons
        if keep_o or not any((keep_o, keep_d)):
            submit_original = INPUT(_value=T("Keep Original"),
                                    _type="submit", _name=KEEP.o, _id=KEEP.o)
        else:
            submit_original = ""

        if keep_d or not any((keep_o, keep_d)):
            submit_duplicate = INPUT(_value=T("Keep Duplicate"),
                                     _type="submit", _name=KEEP.d, _id=KEEP.d)
        else:
            submit_duplicate = ""

        # Build the form
        form = FORM(TABLE(
                        THEAD(
                            TR(TH(H3(T("Original"))),
                               TH(),
                               TH(H3(T("Duplicate"))),
                            ),
                            TR(TD(original_created),
                               TD(),
                               TD(duplicate_created),
                               _class="authorinfo",
                            ),
                        ),
                        TBODY(trs),
                        TFOOT(
                            TR(TD(submit_original),
                               TD(),
                               TD(submit_duplicate),
                            ),
                        ),
                    ),
                    # Append mode and selected - required to get back here!
                    hidden = {
                        "mode": "Inclusive",
                        "selected": ",".join(ids),
                    }
                )

        output["form"] = form

        # Add RESET and CANCEL options
        output["reset"] = FORM(INPUT(_value=T("Reset"),
                                     _type="submit",
                                     _name="reset", _id="form-reset"),
                               A(T("Cancel"), _href=r.url(id=0, vars={}), _class="action-lnk"),
                               hidden = {"mode": mode,
                                         "selected": ",".join(ids),
                                         },
                               )

        # Process the merge form
        formname = "merge_%s_%s_%s" % (tablename,
                                       original[table._id],
                                       duplicate[table._id])
        if form.accepts(post_vars, session,
                        formname=formname,
                        onvalidation=lambda form: self.onvalidation(tablename, form),
                        keepvalues=False,
                        hideerror=False):

            s3db = current.s3db

            if form.vars[KEEP.d]:
                prefix = "%s_" % DUPLICATE
                original, duplicate = duplicate, original
            else:
                prefix = "%s_" % ORIGINAL

            data = Storage()
            for key in form.vars:
                if key.startswith(prefix):
                    fname = key.split("_", 1)[1]
                    data[fname] = form.vars[key]

            search = False
            resource = s3db.resource(tablename)
            try:
                resource.merge(original[table._id],
                               duplicate[table._id],
                               update=data)
            except current.auth.permission.error:
                r.unauthorized()
            except KeyError:
                r.error(404, current.ERROR.BAD_RECORD)
            except Exception:
                import sys
                r.error(424,
                        T("Could not merge records. (Internal Error: %s)") %
                            sys.exc_info()[1],
                        next=r.url())
            else:
                # Cleanup bookmark list
                if mode == "Inclusive":
                    bookmarks[tablename] = [i for i in record_ids if i not in ids]
                    if not bookmarks[tablename]:
                        del bookmarks[tablename]
                        search = True
                elif mode == "Exclusive":
                    bookmarks[tablename].extend(ids)
                    if not selected:
                        search = True
                # Confirmation message
                # @todo: Having the link to the merged record in the confirmation
                # message would be nice, but it's currently not clickable there :/
                #result = A(T("Open the merged record"),
                        #_href=r.url(method="read",
                                    #id=original[table._id],
                                    #vars={}))
                response.confirmation = T("Records merged successfully.")

            # Go back to bookmark list
            if search:
                self.next = r.url(method="", id=0, vars={})
            else:
                self.next = r.url(id=0, vars={})

        # View
        response.view = self._view(r, "merge.html")

        return output
Пример #11
0
    def widget(
        cls,
        r,
        record_ids=None,
        _class="action-lnk",
    ):
        """
            Render an action item (link or button) to anonymize the
            provided records

            @param r: the S3Request
            @param record_ids: The list of record_ids to act on
            @param _class: HTML class for the action item

            @returns: the action item (a HTML helper instance), or an empty
                      string if no anonymize-rules are configured for the
                      target table, no target record was specified or the
                      user is not permitted to anonymize it
        """

        T = current.T

        default = ""

        # Determine target table
        if r.component:
            resource = r.component
            if resource.link and not r.actuate_link():
                resource = resource.link
        else:
            resource = r.resource
        table = resource.table

        # Determine target record
        if not record_ids:
            return default

        # Check if target is configured for anonymize
        rules = resource.get_config("anonymize")
        if not rules:
            return default
        if not isinstance(rules, (tuple, list)):
            # Single rule
            rules["name"] = "default"
            rules = [rules]

        # Determine widget ID
        widget_id = "%s-anonymize" % table

        # Dialog and Form
        INFO = T(
            "The following information will be deleted from all the selected records"
        )
        CONFIRM = T("Are you sure you want to delete the selected details?")
        #SUCCESS = T("Action successful - please wait...")

        form = FORM(
            P("%s:" % INFO),
            cls.selector(rules),
            P(CONFIRM),
            DIV(
                INPUT(
                    value="anonymize_confirm",
                    _name="anonymize_confirm",
                    _type="checkbox",
                ),
                LABEL(T("Yes, delete the selected details")),
                _class="anonymize-confirm",
            ),
            DIV(
                INPUT(
                    _class="small alert button anonymize-submit",
                    _disabled="disabled",
                    _type="submit",
                    _value=T("Anonymize"),
                ),
                _class="anonymize-buttons",
            ),
            _class="anonymize-form",
            # Store action key in form
            hidden={"action-key": cls.action_key(widget_id)},
        )

        script = '''var submitButton=$('.anonymize-submit');
$('input[name="anonymize_confirm"]').off('.anonymize').on('click.anonymize',function(){if ($(this).prop('checked')){submitButton.prop('disabled',false);}else{submitButton.prop('disabled',true);}});'''
        current.response.s3.jquery_ready.append(script)

        return form
Пример #12
0
    def widget(
        cls,
        r,
        label="Anonymize",
        ajaxURL=None,
        _class="action-lnk",
    ):
        """
            Render an action item (link or button) to anonymize the
            target record of an S3Request, which can be embedded in
            the record view

            @param r: the S3Request
            @param label: The label for the action item
            @param ajaxURL: The URL for the AJAX request
            @param _class: HTML class for the action item

            @returns: the action item (a HTML helper instance), or an empty
                      string if no anonymize-rules are configured for the
                      target table, no target record was specified or the
                      user is not permitted to anonymize it
        """

        T = current.T

        default = ""

        # Determine target table
        if r.component:
            resource = r.component
            if resource.link and not r.actuate_link():
                resource = resource.link
        else:
            resource = r.resource
        table = resource.table

        # Determine target record
        record_id = S3Anonymize._record_id(r)
        if not record_id:
            return default

        # Check if target is configured for anonymize
        rules = resource.get_config("anonymize")
        if not rules:
            return default
        if not isinstance(rules, (tuple, list)):
            # Single rule
            rules["name"] = "default"
            rules = [rules]

        # Check permissions to anonymize
        if not S3Anonymize.permitted(table, record_id):
            return default

        # Determine widget ID
        widget_id = "%s-%s-anonymize" % (table, record_id)

        # Inject script
        if ajaxURL is None:
            ajaxURL = r.url(
                method="anonymize",
                representation="json",
            )
        script_options = {
            "ajaxURL": ajaxURL,
        }
        next_url = resource.get_config("anonymize_next")
        if next_url:
            script_options["nextURL"] = next_url
        cls.inject_script(widget_id, script_options)

        # Action button
        translated_label = T(label)
        action_button = A(translated_label, _class="anonymize-btn")
        if _class:
            action_button.add_class(_class)

        # Dialog and Form
        INFO = T("The following information will be deleted from the record")
        CONFIRM = T("Are you sure you want to delete the selected details?")
        SUCCESS = T("Action successful - please wait...")

        form = FORM(
            P("%s:" % INFO),
            cls.selector(rules),
            P(CONFIRM),
            DIV(
                INPUT(
                    value="anonymize_confirm",
                    _name="anonymize_confirm",
                    _type="checkbox",
                ),
                LABEL(T("Yes, delete the selected details")),
                _class="anonymize-confirm",
            ),
            cls.buttons(),
            _class="anonymize-form",
            # Store action key in form
            hidden={"action-key": cls.action_key(widget_id)},
        )

        dialog = DIV(
            form,
            DIV(
                P(SUCCESS),
                _class="hide anonymize-success",
            ),
            _class="anonymize-dialog hide",
            _title=translated_label,
        )

        # Assemble widget
        widget = DIV(
            action_button,
            dialog,
            _class="s3-anonymize",
            _id=widget_id,
        )

        return widget
Пример #13
0
Файл: cwa.py Проект: sahana/eden
    def formatted(self, retry=False):
        """
            Formatted version of this report

            @param retry: add retry-action for sending to CWA

            @returns: a FORM containing
                      - the QR-code
                      - human-readable report details
                      - actions to download PDF, or retry sending to CWA
        """

        T = current.T
        table = current.s3db.disease_case_diagnostics

        # Personal Details
        data_repr = TABLE()
        data = self.data
        if not any(k in data for k in ("fn", "ln", "dob")):
            data_repr.append(
                TR(
                    TD(T("Person Tested")),
                    TD(T("anonymous"), _class="cwa-data"),
                ))
        else:
            labels = {
                "fn": T("First Name"),
                "ln": T("Last Name"),
                "dob": T("Date of Birth"),
            }
            for k in ("ln", "fn", "dob"):
                value = data[k]
                if k == "dob":
                    value = self.to_local_dtfmt(value)
                data_repr.append(
                    TR(
                        TD(labels.get(k)),
                        TD(value, _class="cwa-data"),
                    ))

        # Test Station, date and result
        field = table.site_id
        if field.represent:
            data_repr.append(
                TR(
                    TD(field.label),
                    TD(
                        field.represent(self.site_id),
                        _class="cwa-data",
                    ),
                ))
        field = table.probe_date
        if field.represent:
            data_repr.append(
                TR(
                    TD(field.label),
                    TD(
                        field.represent(self.probe_date),
                        _class="cwa-data",
                    ),
                ))
        field = table.result
        if field.represent:
            data_repr.append(
                TR(
                    TD(field.label),
                    TD(
                        field.represent(self.result),
                        _class="cwa-data",
                    ),
                ))

        # Details
        details = DIV(
            H5(T("Details")),
            data_repr,
            _class="cwa-details",
        )

        # QR Code
        title = T("Code for %(app)s") % CWA
        qrcode = DIV(
            s3_qrcode_represent(self.get_link(), show_value=False),
            DIV(title, _class="cwa-qrcode-title"),
            _class="cwa-qrcode",
        )
        if retry:
            qrcode.add_class("hide")

        # Form buttons
        buttons = [
            BUTTON(
                T("Download PDF"),
                _class="tiny primary button cwa-pdf",
                _type="button",
            ),
        ]
        if retry:
            buttons[0].add_class("hide")
            buttons.append(
                BUTTON(
                    T("Retry sending to %(app)s") % CWA,
                    _class="tiny alert button cwa-retry",
                    _type="button",
                ))

        # Generate form key
        formurl = URL(
            c="disease",
            f="case_diagnostics",
            args=[self.result_id],
        )
        formkey = uuid.uuid4().hex

        # Store form key in session
        session = current.session
        keyname = "_formkey[testresult/%s]" % self.result_id
        session[keyname] = session.get(keyname, [])[-9:] + [formkey]

        form = FORM(
            DIV(
                DIV(
                    details,
                    qrcode,
                    _class="small-12 columns",
                ),
                _class="row form-row",
            ),
            DIV(
                DIV(
                    buttons,
                    _class="small-12 columns",
                ),
                _class="row form-row",
            ),
            hidden={
                "formurl": formurl,
                "cwadata": json.dumps(self.data),
                "_formkey": formkey,
            },
        )

        return form
Пример #14
0
    def apply_method(r, **attr):
        """
            Apply method.

            @param r: the S3Request
            @param attr: controller options for this request
        """

        if r.representation == "html":

            T = current.T
            s3db = current.s3db
            response = current.response
            table = r.table
            tracker = S3Trackable(table, record_id=r.id)

            title = T("Check-In")

            get_vars = r.get_vars

            # Are we being passed a location_id?
            location_id = get_vars.get("location_id", None)
            if not location_id:
                # Are we being passed a lat and lon?
                lat = get_vars.get("lat", None)
                if lat is not None:
                    lon = get_vars.get("lon", None)
                    if lon is not None:
                        form_vars = Storage(
                            lat=float(lat),
                            lon=float(lon),
                        )
                        form = Storage(vars=form_vars)
                        s3db.gis_location_onvalidation(form)
                        location_id = s3db.gis_location.insert(**form_vars)

            form = None
            if not location_id:
                # Give the user a form to check-in

                # Test the formstyle
                formstyle = current.deployment_settings.get_ui_formstyle()
                row = formstyle("test", "test", "test", "test")
                if isinstance(row, tuple):
                    # Formstyle with separate row for label (e.g. default Eden formstyle)
                    tuple_rows = True
                else:
                    # Formstyle with just a single row (e.g. Bootstrap, Foundation or DRRPP)
                    tuple_rows = False

                form_rows = []
                comment = ""

                _id = "location_id"
                label = LABEL("%s:" % T("Location"))

                from .s3widgets import S3LocationSelector
                field = table.location_id
                #value = tracker.get_location(_fields=["id"],
                #                             as_rows=True).first().id
                value = None  # We always want to create a new Location, not update the existing one
                widget = S3LocationSelector(show_latlon=True)(field, value)

                row = formstyle("%s__row" % _id, label, widget, comment)
                if tuple_rows:
                    form_rows.append(row[0])
                    form_rows.append(row[1])
                else:
                    form_rows.append(row)

                _id = "submit"
                label = ""
                widget = INPUT(_type="submit", _value=T("Check-In"))
                row = formstyle("%s__row" % _id, label, widget, comment)
                if tuple_rows:
                    form_rows.append(row[0])
                    form_rows.append(row[1])
                else:
                    form_rows.append(row)

                if tuple_rows:
                    # Assume TRs
                    form = FORM(TABLE(*form_rows))
                else:
                    form = FORM(*form_rows)

                if form.accepts(current.request.vars, current.session):
                    location_id = form.vars.get("location_id", None)

            if location_id:
                # We're not Checking-in in S3Track terms (that's about interlocking with another object)
                #tracker.check_in()
                #timestmp = form.vars.get("timestmp", None)
                #if timestmp:
                #    # @ToDo: Convert from string
                #    pass
                #tracker.set_location(location_id, timestmp=timestmp)
                tracker.set_location(location_id)
                response.confirmation = T("Checked-In successfully!")

            response.view = "check-in.html"
            output = dict(
                form=form,
                title=title,
            )
            return output

        # @ToDo: JSON representation for check-in from mobile devices
        else:
            raise HTTP(415, current.ERROR.BAD_FORMAT)
Пример #15
0
def carro():

    title = "Cadastro de Carros"

    if not session.flashed:
        response.flash = T('Bem vindo a loja de carros!')

    #lista todos os carros na tela
    car_grid = SQLFORM.smartgrid(db2.carro)

    #CRUD
    #aqui ele formata tudo sozinho e ainda envia para o banco sozinho também
    #mostra a mensagem de falha sozinho
    carro_crud = crud.create(db2.carro)

    #######################################################
    #aqui ele formata tudo sozinho e ainda envia para o banco sozinho também
    #mas não mostra a mensagem de falha ou aceitação sozinho
    carro_sqlform = SQLFORM(db2.carro)

    if carro_sqlform.accepts(request,session):
        response.flash = 'Form accepted'
    elif carro_sqlform.errors:
        response.flash = 'Form has errors'
    else:
        response.flash = 'Please fill the form'

    excluir_carro(1)

    alterar_carro(2)

    #######################################################
     # Must repeat the field validators declared in the db.py
    marca_input=INPUT(_name='marca_input', requires=IS_IN_DB(db2, 'marca.id','marca.nome',error_message=e_m['not_in_db']))
    modelo_input=INPUT(_name='modelo_input')
    y1 = request.now.year-20
    y2 = request.now.year+2
    ano_input=INPUT(_name='ano_input', requires=IS_INT_IN_RANGE(y1,y2,error_message=e_m['not_in_range']))
    cor_input=INPUT(_name='cor_input', requires=IS_IN_SET(cores))
    valor_input=INPUT(_name='valor_input')
    itens_input=INPUT(_name='itens_input',requires=IS_IN_SET(('Alarme','Trava','Som', 'Ar'),multiple=True,error_message=e_m['not_in_set']))
    estado_input=INPUT(_name='estado_input',requires=IS_IN_SET(estados,error_message=e_m['not_in_set']))
    desc_input=INPUT(_name='desc_input')
    foto_input=INPUT(_name='foto_input',requires=IS_IMAGE(IS_IMAGE(extensions=('jpeg', 'png', '.gif'),error_message=e_m['image'])))

    #neste ponto define a posição dos dados dentro de uma tabela
    # Manual creation of the html table
    table_rows = []
    table_rows.append(TR('Marca:', marca_input))
    table_rows.append(TR('Modelo:', modelo_input))
    table_rows.append(TR('Ano:', ano_input))
    table_rows.append(TR('Cor:', cor_input))
    table_rows.append(TR('Valor:', valor_input))
    table_rows.append(TR('Itens:', itens_input))
    table_rows.append(TR('Estado:', estado_input))
    table_rows.append(TR('Descrição:', desc_input))
    table_rows.append(TR('Foto:', foto_input))
    # Fields starting with _ are passed to the html as attribute elements
    table_rows.append(TR(TD(INPUT(_type='submit'), _colspan='2', _align='center')))
    table = TABLE(table_rows)

    form = FORM(table)

    #momento em que realmente o dado é colocado dentro do banco de dados
    # Processing the form submition
    if form.accepts(request,session):
        # Retriving the form fields
        form_marca_input = form.vars.marca
        form_modelo_input = form.vars.modelo
        form_ano_input = form.vars.ano
        form_cor_input = form.vars.cor
        form_valor_input = form.vars.valor
        form_itens_input = form.vars.itens
        form_estado_input = form.vars.estado
        form_desc_input = form.vars.desc
        form_foto_input = form.vars.foto
        # Inserting in the database
        db.car_model.insert(marca=form_marca_input, modelo = form_modelo_input,ano = form_ano_input, cor = form_cor_input, valor = form_valor_input, itens = form_itens_input, estado = form_estado_input, desc = form_desc_input, foto = form_foto_input)
        # Tell the user about the insertion
        response.flash = 'New car: ' + form_modelo_input
    elif form.errors:
        response.flash = 'Form has errors'
    else:
        response.flash = 'Please fill the form'

    #######################################################
    form_carro = detalhes_geral(db2.carro,2)

    (form_crud,table_crud) = pesquisa_geral(db2.carro)

    return locals()
Пример #16
0
def getGameFormBtn(game, user, gameStats):
    """
	Gets a dictionary of form buttons that do stuff for the game page.

	Keyword Arguments:
	game    -- row representing the current game
	user    -- row representing the current user

	Return Values:
	formBtn -- dictionary of web2py forms
	        -- 'start'  Start Game button
	        -- 'join'   Join Game button
	        -- 'leave'  Leave Game button
	        -- 'target' Target Eliminated button
	        -- 'dead'   I have been eliminated button
	"""

    from gluon import current, INPUT, FORM, redirect, URL, BUTTON
    db = current.db

    formBtn = {
        'start': 'start',
        'join': 'join',
        'leave': 'leave',
        'target': 'target',
        'dead': 'dead'
    }

    if gameStats['players'] > 1:
        formBtn['start'] = FORM(
            INPUT(
                _type='submit',
                _value='(Host) Start Game',
                _class='btn btn-large btn-block btn-inverse abtn-large',
                _onclick=
                'return confirm(\'Are you sure you want to start this game?\');'
            ))
    else:
        formBtn['start'] = BUTTON(
            '(Host) Start Game',
            _class='btn btn-large btn-block btn-inverse abtn-large',
            _onclick='alert(\'You need at least 2 players to start a game?\');'
        )

    formBtn['join'] = FORM(
        INPUT(_type='submit',
              _value='Join Game',
              _class='btn btn-large btn-block btn-inverse abtn-large'))
    formBtn['leave'] = FORM(
        INPUT(
            _type='submit',
            _value='Leave Game',
            _class='btn btn-block abtn-small',
            _onclick=
            'return confirm(\'Are you sure you want to leave this game?\');'))
    formBtn['target'] = FORM(
        INPUT(_type='submit',
              _value='Target Eliminated',
              _class='btn btn-large btn-block btn-inverse abtn-large'))
    formBtn['dead'] = FORM(
        INPUT(
            _type='submit',
            _value='I am dead.',
            _class='btn btn-block abtn-small',
            _onclick=
            'return confirm(\'Are you sure you want to eliminate yourself?\');'
        ))

    if gameStats['players'] > 1 and formBtn['start'].process(
            formname='formBtnStart').accepted:
        startGameAssassins(game.id, user)
        redirect(URL('default', 'game', args=game.id))

    if formBtn['join'].process(formname='formBtnJoin').accepted:
        joinGame(game.id, user)
        redirect(URL('default', 'game', args=game.id))

    if formBtn['leave'].process(formname='formBtnLeave').accepted:
        leaveGame(game.id, user)
        redirect(URL('default', 'game', args=game.id))

    if formBtn['target'].process(formname='formBtnTarget').accepted:
        killCompletedAssassins(game.id, user.id)
        redirect(URL('default', 'game', args=game.id))

    if formBtn['dead'].process(formname='formBtnDead').accepted:
        query = db((db.player.game_id == game.id)
                   & (db.player.player_id == user.id)).select(db.player.id)[0]
        killPlayer(game.id, user.id)
        #wasKilledAssassins()
        redirect(URL('default', 'game', args=game.id))

    return formBtn
Пример #17
0
    def merge(self, r, **attr):
        """
            Merge form for two records

            @param r: the S3Request
            @param **attr: the controller attributes for the request

            @note: this method can always only be POSTed, and requires
                   both "selected" and "mode" in post_vars, as well as
                   the duplicate bookmarks list in session.s3
        """

        T = current.T
        session = current.session
        response = current.response

        output = {}
        tablename = self.tablename

        # Get the duplicate bookmarks
        s3 = session.s3
        DEDUPLICATE = self.DEDUPLICATE
        if DEDUPLICATE in s3:
            bookmarks = s3[DEDUPLICATE]
            if tablename in bookmarks:
                record_ids = bookmarks[tablename]

        # Process the post variables
        post_vars = r.post_vars
        mode = post_vars.get("mode")
        selected = post_vars.get("selected", "")
        selected = selected.split(",")
        if mode == "Inclusive":
            ids = selected
        elif mode == "Exclusive":
            ids = [i for i in record_ids if i not in selected]
        else:
            # Error
            ids = []
        if len(ids) != 2:
            r.error(501,
                    T("Please select exactly two records"),
                    next=r.url(id=0, vars={}))

        # Get the selected records
        table = self.table
        query = (table._id == ids[0]) | (table._id == ids[1])
        orderby = table.created_on if "created_on" in table else None
        rows = current.db(query).select(orderby=orderby, limitby=(0, 2))
        if len(rows) != 2:
            r.error(404, current.ERROR.BAD_RECORD, next=r.url(id=0, vars={}))
        original = rows[0]
        duplicate = rows[1]

        # Prepare form construction
        formfields = [f for f in table if f.readable or f.writable]

        ORIGINAL, DUPLICATE, KEEP = self.ORIGINAL, self.DUPLICATE, self.KEEP
        keep_o = KEEP.o in post_vars and post_vars[KEEP.o]
        keep_d = KEEP.d in post_vars and post_vars[KEEP.d]

        trs = []
        init_requires = self.init_requires
        index = 1
        num_fields = len(formfields)

        for f in formfields:

            # Render the widgets
            oid = "%s_%s" % (ORIGINAL, f.name)
            did = "%s_%s" % (DUPLICATE, f.name)
            sid = "swap_%s" % f.name
            init_requires(f, original[f], duplicate[f])
            if keep_o or not any((keep_o, keep_d)):
                owidget = self.widget(f,
                                      original[f],
                                      _name=oid,
                                      _id=oid,
                                      _tabindex=index)
            else:
                try:
                    owidget = s3_represent_value(f, value=original[f])
                except:
                    owidget = s3_str(original[f])
            if keep_d or not any((keep_o, keep_d)):
                dwidget = self.widget(f, duplicate[f], _name=did, _id=did)
            else:
                try:
                    dwidget = s3_represent_value(f, value=duplicate[f])
                except:
                    dwidget = s3_str(duplicate[f])

            # Swap button
            if not any((keep_o, keep_d)):
                swap = INPUT(
                    _value="<-->",
                    _class="swap-button",
                    _id=sid,
                    _type="button",
                    _tabindex=index + num_fields,
                )
            else:
                swap = DIV(_class="swap-button")

            if owidget is None or dwidget is None:
                continue

            # Render label row
            label = f.label
            trs.append(
                TR(TD(label, _class="w2p_fl"), TD(), TD(label,
                                                        _class="w2p_fl")))

            # Append widget row
            trs.append(
                TR(TD(owidget, _class="mwidget"), TD(swap),
                   TD(dwidget, _class="mwidget")))

            index = index + 1
        # Show created_on/created_by for each record
        if "created_on" in table:
            original_date = original.created_on
            duplicate_date = duplicate.created_on
            if "created_by" in table:
                represent = table.created_by.represent
                original_author = represent(original.created_by)
                duplicate_author = represent(duplicate.created_by)
                created = T("Created on %s by %s")
                original_created = created % (original_date, original_author)
                duplicate_created = created % (duplicate_date,
                                               duplicate_author)
            else:
                created = T("Created on %s")
                original_created = created % original_date
                duplicate_created = created % duplicate_date
        else:
            original_created = ""
            duplicate_created = ""

        # Page title and subtitle
        output["title"] = T("Merge records")
        #output["subtitle"] = self.crud_string(tablename, "title_list")

        # Submit buttons
        if keep_o or not any((keep_o, keep_d)):
            submit_original = INPUT(
                _value=T("Keep Original"),
                _type="submit",
                _name=KEEP.o,
                _id=KEEP.o,
            )
        else:
            submit_original = ""

        if keep_d or not any((keep_o, keep_d)):
            submit_duplicate = INPUT(
                _value=T("Keep Duplicate"),
                _type="submit",
                _name=KEEP.d,
                _id=KEEP.d,
            )
        else:
            submit_duplicate = ""

        # Build the form
        form = FORM(
            TABLE(
                THEAD(
                    TR(
                        TH(H3(T("Original"))),
                        TH(),
                        TH(H3(T("Duplicate"))),
                    ),
                    TR(
                        TD(original_created),
                        TD(),
                        TD(duplicate_created),
                        _class="authorinfo",
                    ),
                ),
                TBODY(trs),
                TFOOT(TR(
                    TD(submit_original),
                    TD(),
                    TD(submit_duplicate),
                ), ),
            ),
            # Append mode and selected - required to get back here!
            hidden={
                "mode": "Inclusive",
                "selected": ",".join(ids),
            })

        output["form"] = form

        # Add RESET and CANCEL options
        output["reset"] = FORM(
            INPUT(
                _value=T("Reset"),
                _type="submit",
                _name="reset",
                _id="form-reset",
            ),
            A(T("Cancel"), _href=r.url(id=0, vars={}), _class="action-lnk"),
            hidden={
                "mode": mode,
                "selected": ",".join(ids),
            },
        )

        # Process the merge form
        formname = "merge_%s_%s_%s" % (tablename, original[table._id],
                                       duplicate[table._id])
        if form.accepts(
                post_vars,
                session,
                formname=formname,
                onvalidation=lambda form: self.onvalidation(tablename, form),
                keepvalues=False,
                hideerror=False):

            s3db = current.s3db

            if form.vars[KEEP.d]:
                prefix = "%s_" % DUPLICATE
                original, duplicate = duplicate, original
            else:
                prefix = "%s_" % ORIGINAL

            data = Storage()
            for key in form.vars:
                if key.startswith(prefix):
                    fname = key.split("_", 1)[1]
                    data[fname] = form.vars[key]

            search = False
            resource = s3db.resource(tablename)
            try:
                resource.merge(original[table._id],
                               duplicate[table._id],
                               update=data)
            except current.auth.permission.error:
                r.unauthorised()
            except KeyError:
                r.error(404, current.ERROR.BAD_RECORD)
            except Exception:
                import sys
                r.error(424,
                        T("Could not merge records. (Internal Error: %s)") %
                        sys.exc_info()[1],
                        next=r.url())
            else:
                # Cleanup bookmark list
                if mode == "Inclusive":
                    bookmarks[tablename] = [
                        i for i in record_ids if i not in ids
                    ]
                    if not bookmarks[tablename]:
                        del bookmarks[tablename]
                        search = True
                elif mode == "Exclusive":
                    bookmarks[tablename].extend(ids)
                    if not selected:
                        search = True
                # Confirmation message
                # @todo: Having the link to the merged record in the confirmation
                # message would be nice, but it's currently not clickable there :/
                #result = A(T("Open the merged record"),
                #_href=r.url(method="read",
                #id=original[table._id],
                #vars={}))
                response.confirmation = T("Records merged successfully.")

            # Go back to bookmark list
            if search:
                self.next = r.url(method="", id=0, vars={})
            else:
                self.next = r.url(id=0, vars={})

        # View
        response.view = self._view(r, "merge.html")

        return output
Пример #18
0
def get_task_num_form():
    form = FORM('Show:',
                INPUT(_name = 'task_num', _class='task_num', requires = IS_INT_IN_RANGE(1,101)),
                A(SPAN(_class='icon-refresh'), _onclick = 'tab_refresh();$(this).closest(\'form\').submit()', _href='#'))
    return form
Пример #19
0
    def apply_method(r, **attr):
        """
            Apply method.

            @param r: the S3Request
            @param attr: controller options for this request
        """

        if r.representation == "html":

            T = current.T

            response = current.response
            tracker = S3Trackable(r.table, record_id=r.id)

            title = T("Check-Out")

            # Give the user a form to check-out

            # Test the formstyle
            formstyle = current.deployment_settings.get_ui_formstyle()
            row = formstyle("test", "test", "test", "test")
            if isinstance(row, tuple):
                # Formstyle with separate row for label (e.g. default Eden formstyle)
                tuple_rows = True
            else:
                # Formstyle with just a single row (e.g. Bootstrap, Foundation or DRRPP)
                tuple_rows = False

            form_rows = []
            comment = ""

            _id = "submit"
            label = ""
            widget = INPUT(_type="submit", _value=T("Check-Out"))
            row = formstyle("%s__row" % _id, label, widget, comment)
            if tuple_rows:
                form_rows.append(row[0])
                form_rows.append(row[1])
            else:
                form_rows.append(row)

            if tuple_rows:
                # Assume TRs
                form = FORM(TABLE(*form_rows))
            else:
                form = FORM(*form_rows)

            if form.accepts(current.request.vars, current.session):
                # Check-Out
                # We're not Checking-out in S3Track terms (that's about removing an interlock with another object)
                # What we're doing is saying that we're now back at our base location
                #tracker.check_out()
                #timestmp = form_vars.get("timestmp", None)
                #if timestmp:
                #    # @ToDo: Convert from string
                #    pass
                #tracker.set_location(r.record.location_id, timestmp=timestmp)
                tracker.set_location(r.record.location_id)
                response.confirmation = T("Checked-Out successfully!")

            response.view = "check-in.html"
            output = dict(form = form,
                          title = title,
                          )
            return output

        # @ToDo: JSON representation for check-out from mobile devices
        else:
            raise HTTP(415, current.ERROR.BAD_FORMAT)
Пример #20
0
def BD_Apostila():

    #############seleciona os registros com informações
    print 'lendo antes de inserir'
    registros = db(db.minhatabela.meucampo!=None).select()
    for registro in registros:
        print registro.meucampo

    ############seleciona os registros com a palavra teste, porém só mostra no terminal
    minhaquery = (db.minhatabela.meucampo == 'pepino')
    # definir o conjunto de registros ' SELECT * FROM minhatabela where meucampo = 'Teste'
    conjunto = db(minhaquery)
    # executar o select acima e popula o objeto registros
    registros = conjunto.select()
    # alterar os registros 'UPDATE minhatabela set meucampo = 'Teste2' where meucampo = 'Teste'
    conjunto.update(meucampo='arroz')
    ##########################################################################
    print 'lendo depois de trocar'
    registros = db(db.minhatabela.meucampo!=None).select()
    for registro in registros:
        print registro.meucampo
    ############seleciona os registros com a palavra arroz, porém só mostra no terminal
    minhaquery2 = (db.minhatabela.meucampo == 'verde')
    # definir o conjunto de registros ' SELECT * FROM minhatabela where meucampo = 'Teste'
    conjunto2 = db(minhaquery2)
    # executar o select acima e popula o objeto registros
    registros2 = conjunto2.select()
    # deletar os registros 'DELETE FROM minhatabela where meucampo = 'Teste'
    conjunto2.delete()
    ##########################################################################
    print 'lendo depois de deletar'
    registros = db(db.minhatabela.meucampo!=None).select()
    for registro in registros:
        print registro.meucampo
    ##########################################################################

    ##################
    print 'lendo na minhaordem'
    minhaordem = db.minhatabela.meucampo.upper() | db.minhatabela.id
    registro = db().select(db.minhatabela.ALL, orderby=minhaordem)
    for registro in registros:
        print registro.meucampo
    ###########Adicionando um elemento no form/db############################
    meucampo_input=INPUT(_name='meucampo', requires=IS_NOT_EMPTY(error_message='você deve informar algo'))
    table_rows = []
    table_rows.append(TR('Meu campo:',meucampo_input))
    table_rows.append(TR(TD(INPUT(_type='submit'),colspan='2',align='center')))
    table=TABLE(table_rows)

    form_db = FORM(table)

    if form_db.accepts(request,session):
        form_meucampo = form_db.vars.meucampo
        db.minhatabela.insert(meucampo=form_meucampo)
        response.flash = 'tabela:'+ form_meucampo
    elif form_db.errors:
        response.flash = 'form errors'
    else:
        response.flash = 'please fill the form'

    ##########################adicionando um elemento SQLFORM/db
    form99=SQLFORM(db.minhatabela)
    ##########################################################################

    print 'lendo depois de inserir'
    registros = db(db.minhatabela.meucampo!=None).select()
    for registro in registros:
        print registro.meucampo
    ##########################################################################

    print 'Inserindo mais dados'
    db.minhatabela.insert(meucampo = 'verde')
    print 'lendo depois de inserir'
    registros = db(db.minhatabela.meucampo!=None).select()
    for registro in registros:
        print registro.meucampo

    print 'Inserindo muitos dados'
    maisdados = [{'meucampo':'azul'},
                 {'meucampo':'amarelo'},
                 {'meucampo':'pepino'}
                ]

    #############falta o código

    query = db.minhatabela.meucampo != 'verde'

    conjunto = db(query)
    registros = conjunto.select()

    print 'lendo query'

    for registro in registros:
        print registro.meucampo

    meuregistro = db.minhatabela(10)
    print meuregistro

    meuregistro = db.minhatabela(db.minhatabela.id == 10 )
    print meuregistro

    meuregistro = db.minhatabela(10,meucampo='laranja')
    print meuregistro

    print 'Orderby'
    for registro in db().select(db.minhatabela.ALL, orderby=db.minhatabela.meucampo):
        print registro.meucampo

    print 'query multipla'
    for registro in db((db.minhatabela.meucampo=='laranja')|(db.minhatabela.meucampo=='verde')).select():
        print registro.meucampo

    print db(db.minhatabela.id>0).count()

    print 'alterar campo'
    teste = db.minhatabela(10)
    print teste.meucampo
    teste.meucampo = 'rosa'
    print teste.meucampo

    print 'alterando todos'
    teste = db().select(db.minhatabela.ALL)
    for test in teste:
        test.update(meucampo='estragou')

    for registro in teste:
        print registro.meucampo

    return dict(form_db_table=form_db, registros=registros, form99=form99)
Пример #21
0
    def apply_method(r, **attr):
        """
            Apply method.

            @param r: the S3Request
            @param attr: controller options for this request
        """

        if r.representation == "html":

            T = current.T

            response = current.response
            tracker = S3Trackable(r.table, record_id=r.id)

            title = T("Check-Out")

            # Give the user a form to check-out

            # Test the formstyle
            formstyle = current.deployment_settings.get_ui_formstyle()
            row = formstyle("test", "test", "test", "test")
            if isinstance(row, tuple):
                # Formstyle with separate row for label (e.g. default Eden formstyle)
                tuple_rows = True
            else:
                # Formstyle with just a single row (e.g. Bootstrap, Foundation or DRRPP)
                tuple_rows = False

            form_rows = []
            comment = ""

            _id = "submit"
            label = ""
            widget = INPUT(_type="submit", _value=T("Check-Out"))
            row = formstyle("%s__row" % _id, label, widget, comment)
            if tuple_rows:
                form_rows.append(row[0])
                form_rows.append(row[1])
            else:
                form_rows.append(row)

            if tuple_rows:
                # Assume TRs
                form = FORM(TABLE(*form_rows))
            else:
                form = FORM(*form_rows)

            if form.accepts(current.request.vars, current.session):
                # Check-Out
                # We're not Checking-out in S3Track terms (that's about removing an interlock with another object)
                # What we're doing is saying that we're now back at our base location
                #tracker.check_out()
                #timestmp = form_vars.get("timestmp", None)
                #if timestmp:
                #    # @ToDo: Convert from string
                #    pass
                #tracker.set_location(r.record.location_id, timestmp=timestmp)
                tracker.set_location(r.record.location_id)
                response.confirmation = T("Checked-Out successfully!")

            response.view = "check-in.html"
            output = dict(
                form=form,
                title=title,
            )
            return output

        # @ToDo: JSON representation for check-out from mobile devices
        else:
            raise HTTP(415, current.ERROR.BAD_FORMAT)
Пример #22
0
def getEditgamePlayers(game, user):
    """
	Gets a list of players and buttons for the edit game page.

	Keyword Arguments:
	game    -- row representing the current game
	user    -- row representing the current user

	Return Values:
	out -- list containing dictionaries for each player
	    -- 'name'   string of the full name of the player
	    -- 'status' string of the status of the player
	    -- 'kill'   '' or a button to kill the player
	    -- 'kick'   '' or a button to kick the player
	"""

    from gluon import current, INPUT, FORM, redirect, URL
    db = current.db

    #Rows for the current player's list
    players = db((db.player.player_id == db.auth_user.id)
                 & (db.player.game_id == game.id)).select(
                     db.player.status, db.player.id, db.player.player_id,
                     db.auth_user.first_name, db.auth_user.last_name)

    out = []
    for player in players:
        row = {'name': 'name', 'status': 'status', 'kill': '', 'kick': ''}

        action1 = 'Kill'
        action2 = 'Kick'
        if game.rules == 'Assassins':
            action1 = 'Eliminate'
        elif game.rules == 'Humans v. Zombies':
            action1 = 'Zombify'

        row['name'] = player.auth_user.first_name + ' ' + player.auth_user.last_name
        if game.host_id == player.player.player_id:
            row['name'] = row['name'] + ' (Host)'

        if game.game_status == "STARTED":
            row['status'] = player.player.status

        if row['status'] != 'DEAD' and game.game_status == 'STARTED':
            action = 'action'

            id = INPUT(_name='id',
                       _type='text',
                       _value=player.player.player_id,
                       _class='hidden')
            kill = INPUT(
                _type='submit',
                _value=action1,
                _class='btn btn-mini',
                _onclick='return confirm(\'Are you sure you want to ' +
                action1.lower() + ' this player?\');')
            row['kill'] = FORM(id, kill)

            if row['kill'].process(formname='formBtnKill').accepted:
                player
                killPlayer(game.id, row['kill'].vars.id, user)
                redirect(URL('kiwi', 'editgame', args=game.id))

        if player.player.player_id != user.id:
            id = INPUT(_name='id',
                       _type='text',
                       _value=player.player.id,
                       _class='hidden')
            kick = INPUT(
                _type='submit',
                _value=action2,
                _class='btn btn-mini btn-danger',
                _onclick='return confirm(\'Are you sure you want to ' +
                action2.lower() + ' this player?\');')
            row['kick'] = FORM(id, kick)

            if row['kick'].process(formname='formBtnKick').accepted:
                kickPlayer(row['kick'].vars.id, user)
                redirect(URL('kiwi', 'editgame', args=game.id))

        out.append(row)
    #End for player in players:

    #Sort players by status, then by name
    out.sort(key=lambda n: (n['status'], n['name']))

    return out