Esempio n. 1
0
    def render_form_select(self, data):
        """Use to automatically render a select widget.

        Pass in a dictionary with keys:

        name: name of the select widget
        choices: list of 2-tuples (value, text)
        selected: value of selected choice (if any)
        editmode: False if element should be disabled

        """

        #print 'start', data
        name = data['name']
        #print 'rendering select ', name, data
        _id = name
        choices = data['choices']
        selected = data.get('selected', '')
        editmode = data.get('editmode', True)

        if not choices:
            return 'No choices available.'

        import types
        if type(choices[0]) in types.StringTypes:
            options = self.form_options(choices, selected)
        else:
            options = self.form_options2(choices, selected)

        if editmode:
            select = T.select(name=name, _id=_id)[options]
        else:
            select = T.select(name=name, _id=_id, disabled="disabled")[options]

        return select
    def render_genericCommand(self, ctx: WovenContext, data):
        startTime = tags.input(id='startTime', type='text', class_='IDateTime', placeholder='Start Time')
        endTime = tags.input(id='hours', type='number', step='0.5', placeholder='Hours')

        se = ISolomonEmployee(self.employee)
        s = tags.select(id="sub", style='display:none')[self.getSubs(se)]

        w = tags.select(id='wloc', style='display:none')[self.getWLocs(se)]
        typ = tags.select(id='type')[
            tags.option(value='Vacation')['Vacation'],
            tags.option(value='Illness')['Sick Leave'],
            #tags.option(value='Personal')['Personal']
        ]
        submit = tags.input(type='button', value='Schedule Time Off')[tags.Tag('athena:handler')(event='onclick', handler='scheduleTimeOff')]
        return self.preprocess([startTime, endTime, s, w, typ, submit])
Esempio n. 3
0
 def render_genericCommand(self, ctx: WovenContext, data):
     ret = [
         tags.select(id='subAccount', style='display:block')[
             [self.getSubs(),
              tags.Tag('athena:handler')(handler='selectSubAccount', event='onchange')]
         ],
         tags.select(id='workLocation', style='display:block')[
             [self.getLocs(),
              tags.Tag('athena:handler')(handler='selectWorkLocation', event='onchange')]
         ],
         tags.br(),
         tags.input(id='password', type='password', placeholder='password'),
         tags.input(id='clockInOut', type='button', value='ClockInOut')[tags.Tag('athena:handler')(event='onclick', handler='clockInOut')]
     ]
     return self.preprocess(ret)
Esempio n. 4
0
    def _renderTag(self, ctx, key, value, converter, disabled):
        def renderOptions(ctx, data):
            if self.noneOption is not None:
                yield T.option(
                    value=iformal.IKey(self.noneOption).key())[iformal.ILabel(
                        self.noneOption).label()]
            if data is None:
                return
            for item in data:
                optValue = iformal.IKey(item).key()
                optLabel = iformal.ILabel(item).label()
                optValue = converter.fromType(optValue)
                option = T.option(value=optValue)[optLabel]

                if value and optValue in value:
                    option = option(selected='selected')

                yield option

        tag = T.select(name=key,
                       id=render_cssid(key),
                       data=self.options,
                       multiple="multiple")[renderOptions]

        if disabled:
            tag(class_='disabled', disabled='disabled')
        return tag
    def render_genericCommand(self, ctx: WovenContext, data):

        employees = []
        self.l1 = l1 = List(employees, ["Employee ID", "Name"])
        self.l2 = l2 = List([], ["Entry Type", "Work Location", "Sub Account", "Start Time", "End Time", "Shift Duration", "Daily Total", "Approved", "Denied"])
        self.ltl = ltl = ListToListSelector(l1, l2)
        ltl.mappingReturnsNewElements = True
        ltl.prepare(self)
        ltl.visible = True
        ltl.closeable = False
        ltl.getMappingFor = self.getMappingFor
        ltl.setMappingFor = self.setMappingFor
        l2.setSelectable(False)

        startTime = tags.input(id='startTime', placeholder='Start Time')#[tags.Tag('athena:handler')(event='onchange', handler='timeWindowChanged')]
        endTime = tags.input(id='endTime', placeholder='End Time')
        addTime = [
            tags.input(id='addTime', type='button', value='Add Time Entry')[
                tags.Tag('athena:handler')(event='onclick', handler='addTime')],
            tags.select(id='newTimeType')[
                [tags.option(id=et.getTypeName())[et.getTypeName()] for et in self.entryTypes]
                ]
            ]
        if not IAdministrator(self.employee, None):
            addTime = ''

        self.preprocess([startTime, endTime, addTime])
        return [startTime, endTime, tags.br(), addTime, ltl]
Esempio n. 6
0
    def _renderTag(self, ctx, tparser, tvalue, namer, readonly):
        tag = T.invisible()
        if len(self.parsers) > 1:
            tp = T.select(name=namer('tparser'),
                          id=render_cssid(namer('tparser')))
            if readonly:
                tp(class_='disabled', disabled='disabled')

            for k, v in self.parsers:
                if k == tparser:
                    tp[T.option(selected='selected', value=k)[v]]
                else:
                    tp[T.option(value=k)[v]]
        else:
            tp = T.input(type='hidden',
                         name=namer('tparser'),
                         id=render_cssid(namer('tparser')),
                         value=self.parsers[0][0])
        ta = T.textarea(name=namer('tvalue'),
                        id=render_cssid(namer('tvalue')),
                        cols=self.cols,
                        rows=self.rows)[tvalue or '']
        if readonly:
            ta(class_='readonly', readonly='readonly')
        tag[tp, T.br, ta]
        return tag
Esempio n. 7
0
	def _renderTag(self, ctx, key, value, converter, disabled):
		if not isinstance(value, (list, tuple)):
			value = [value]

		# unfortunately, I need to copy all that code from formal to let 
		# me keep multiple selections
		def renderOptions(ctx, data):
			if self.noneOption is not None:
				noneVal = iformal.IKey(self.noneOption).key()
				option = T.option(value=noneVal)[
					iformal.ILabel(self.noneOption).label()]
				if value is None or value==noneVal:
					option = option(selected='selected')
				yield option
			if data is None:
				return
			for item in data:
				optValue = iformal.IKey(item).key()
				optLabel = iformal.ILabel(item).label()
				optValue = converter.fromType(optValue)
				option = T.option(value=optValue)[optLabel]
				if optValue in value:
					option = option(selected='selected')
				yield option

		tag = T.select(name=key, id=render_cssid(key), data=self.options)[
			renderOptions]
		if disabled:
			tag(class_='disabled', disabled='disabled')
		return T.span(style="white-space:nowrap")[
			tag(size=str(self.size), multiple="multiple"),
			" ",
			T.span(class_="fieldlegend")[
				"No selection matches all, multiple values legal."]]
Esempio n. 8
0
    def _renderTag(self, ctx, key, value, readonly):
        html = []
        tag = T.textarea(name=key,
                         id=render_cssid(key),
                         cols=self.cols,
                         rows=self.rows)[value or '']
        if readonly:
            tag(class_='readonly', readonly='readonly')
        html.append(tag)
        if self.values is None:
            return html

        def renderOptions(ctx, options):
            for value, label in options:
                yield T.option(value=value)[label]

        selecttrigger = T.select(name='%s__selecttrigger' % key,
                                 data=self.values)[renderOptions]

        form = iformal.IForm(ctx)
        js = T.xml(
            "var x = document.getElementById('%(form)s');x.%(key)s.value += x.%(key)s__selecttrigger.options[x.%(key)s__selecttrigger.options.selectedIndex].value + "\\n";"
            % {
                'key': key,
                'form': form.name
            })
        aonclick = T.a(onclick=js)['add']
        html.append(T.div(class_="add")[selecttrigger, aonclick])
        return html
Esempio n. 9
0
    def _renderTag(self, ctx, tparser, tvalue, namer, readonly):
        tag=T.invisible()
        if len(self.parsers) > 1:
            tp = T.select(name=namer('tparser'),id=render_cssid(namer('tparser')))
            if readonly:
                tp(class_='disabled', disabled='disabled')        
            
            for k,v in self.parsers:
                if k == tparser:
                    tp[T.option(selected='selected',value=k)[ v ]]
                else:
                    tp[T.option(value=k)[ v ]]
        else:
            tp = T.input(type='hidden',name=namer('tparser'),id=render_cssid(namer('tparser')),value=self.parsers[0][0])
        tag[tp]     
               
        if self.itemTypes is not None:
            tag[ T.input(type='hidden',class_="itemTypes",name=namer('itemTypes'),id=render_cssid(namer('itemTypes')),value=encodeTypes(self.itemTypes)) ]
        if self.itemTemplates is not None:
            tag[ T.input(type='hidden',class_="itemTemplates",name=namer('itemTemplates'),id=render_cssid(namer('itemTemplates')),value=','.join(self.itemTemplates)) ]

        ta=T.textarea(name=namer('tvalue'), id=render_cssid(namer('tvalue')), cols=self.cols, rows=self.rows)[tvalue or '']
        if readonly:
            ta(class_='readonly', readonly='readonly')
        tag[ [T.br,ta ]]
        return tag
Esempio n. 10
0
File: widget.py Progetto: bne/squeal
    def _renderTag(self, ctx, year, month, day, namer, readonly):
        years = [(v,v) for v in xrange(self.yearFrom,self.yearTo)]
        months = self.months
        days = self.days

        options = []
        if self.noneOption is not None:
            options.append( T.option(value=self.noneOption[0])[self.noneOption[1]] )
        for value in years:
            if str(value[0]) == str(year):
                options.append( T.option(value=value[0],selected='selected')[value[1]] )
            else:
                options.append( T.option(value=value[0])[value[1]] )
        yearTag = T.select(name=namer('year'))[ options ]
        
        options = []
        if self.noneOption is not None:
            options.append( T.option(value=self.noneOption[0])[self.noneOption[1]] )
        for value in months:
            if str(value[0]) == str(month):
                options.append( T.option(value=value[0],selected='selected')[value[1]] )
            else:
                options.append( T.option(value=value[0])[value[1]] )
        monthTag = T.select(name=namer('month'))[ options ]
        
        options = []
        if self.noneOption is not None:
            options.append( T.option(value=self.noneOption[0])[self.noneOption[1]] )
        for value in days:
            if str(value[0]) == str(day):
                options.append( T.option(value=value[0],selected='selected')[value[1]] )
            else:
                options.append( T.option(value=value[0])[value[1]] )
        dayTag = T.select(name=namer('day'))[ options ]
        
        if readonly:
            tags = (yearTag, monthTag, dayTag)
            for tag in tags:
                tag(class_='readonly', readonly='readonly')

        if self.dayFirst:
            return dayTag, ' / ', monthTag, ' / ', yearTag, ' ', _('(day/month/year)')
        else:
            return monthTag, ' / ', dayTag, ' / ', yearTag, ' ', _('(month/day/year)')
Esempio n. 11
0
    def _renderTag(self, ctx, year, month, day, namer, readonly):
        years = [(v,v) for v in xrange(self.yearFrom,self.yearTo)]
        months = self.months
        days = self.days

        options = []
        if self.noneOption is not None:
            options.append( T.option(value=self.noneOption[0])[self.noneOption[1]] )
        for value in years:
            if str(value[0]) == str(year):
                options.append( T.option(value=value[0],selected='selected')[value[1]] )
            else:
                options.append( T.option(value=value[0])[value[1]] )
        yearTag = T.select(name=namer('year'))[ options ]
        
        options = []
        if self.noneOption is not None:
            options.append( T.option(value=self.noneOption[0])[self.noneOption[1]] )
        for value in months:
            if str(value[0]) == str(month):
                options.append( T.option(value=value[0],selected='selected')[value[1]] )
            else:
                options.append( T.option(value=value[0])[value[1]] )
        monthTag = T.select(name=namer('month'))[ options ]
        
        options = []
        if self.noneOption is not None:
            options.append( T.option(value=self.noneOption[0])[self.noneOption[1]] )
        for value in days:
            if str(value[0]) == str(day):
                options.append( T.option(value=value[0],selected='selected')[value[1]] )
            else:
                options.append( T.option(value=value[0])[value[1]] )
        dayTag = T.select(name=namer('day'))[ options ]
        
        if readonly:
            tags = (yearTag, monthTag, dayTag)
            for tag in tags:
                tag(class_='readonly', readonly='readonly')

        if self.dayFirst:
            return dayTag, ' / ', monthTag, ' / ', yearTag, ' ', _('(day/month/year)')
        else:
            return monthTag, ' / ', dayTag, ' / ', yearTag, ' ', _('(month/day/year)')
Esempio n. 12
0
    def render_selectProfile(self, ctx, data):
        # Renderer for the form (because formal rendering sucks piles)
        profiles = []
        for il in os.listdir('/usr/local/tcs/tums/profiles/'):
            if il[-3:] == '.py':
                name = il[:-3].replace('_', ' ').capitalize()
                profiles.append((il, name))

        return ctx.tag[tags.select(
            id="selectProfile-profile",
            name="profile")[[tags.option(value=k)[v] for k, v in profiles]]]
Esempio n. 13
0
 def getWidgetDocument(self):
     # XXX No support for rendering these yet!
     f = liveform.LiveForm(self.submit,
                           [liveform.Parameter('argument', None, unicode)])
     f.docFactory = loaders.stan(
         tags.form(render=tags.directive('liveElement'))
         [tags.select(
             name="argument")[tags.option(value="apples")["apples"],
                              tags.option(value="oranges")["oranges"]],
          tags.input(type='submit', render=tags.directive('submitbutton'))])
     f.setFragmentParent(self)
     return f
Esempio n. 14
0
 def getWidgetDocument(self):
     # XXX No support for rendering these yet!
     f = liveform.LiveForm(
         self.submit,
         [liveform.Parameter('argument', None, unicode)])
     f.docFactory = loaders.stan(tags.form(render=tags.directive('liveElement'))[
         tags.select(name="argument")[
             tags.option(value="apples")["apples"],
             tags.option(value="oranges")["oranges"]],
         tags.input(type='submit', render=tags.directive('submitbutton'))])
     f.setFragmentParent(self)
     return f
Esempio n. 15
0
    def render_genericCommand(self, ctx: WovenContext, data):
        se = ISolomonEmployee(self._employee)
        s = tags.select(id="sub")[self.getSubs(se)]

        w = tags.select(id='wloc')[self.getWLocs(se)]


        sub = tags.input(type='button', value='Clock In')[
            tags.Tag('athena:handler')(event='onclick', handler='doClockIn')
        ]

        out = tags.input(type='button', value='Clock Out', id='clockout')[
            tags.Tag('athena:handler')(event='onclick', handler='doClockOut')
        ]
        d = tags.div(id='clockin')[s, w, sub]

        if self._employee.timeEntry:
            d(style='display:none')
        else:
            out(style='display:none')

        return self.preprocess([d, out])
Esempio n. 16
0
 def get_and_set(name, options, default=None, astype=int):
     current_value = getarg(name, astype)
     i_select = T.select(name=name)
     for (count, description) in options:
         count = astype(count)
         if ((current_value is not None and count == current_value) or
             (current_value is None and count == default)):
             o = T.option(value=str(count), selected="true")[description]
         else:
             o = T.option(value=str(count))[description]
         i_select = i_select[o]
     if current_value is None:
         current_value = default
     return current_value, i_select
Esempio n. 17
0
 def get_and_set(name, options, default=None, astype=int):
     current_value = getarg(name, astype)
     i_select = T.select(name=name)
     for (count, description) in options:
         count = astype(count)
         if ((current_value is not None and count == current_value) or
             (current_value is None and count == default)):
             o = T.option(value=str(count), selected="true")[description]
         else:
             o = T.option(value=str(count))[description]
         i_select = i_select[o]
     if current_value is None:
         current_value = default
     return current_value, i_select
Esempio n. 18
0
File: widget.py Progetto: bne/squeal
 def _renderTag(self, ctx, key, values, converter, disabled):
     def renderOptions(ctx, options):
         # loops through checkbox options and renders
         for item in options:
             optValue = converter.fromType(iformal.IKey(item).key())
             optLabel = iformal.ILabel(item).label()
             option = T.option(value=optValue)[optLabel]
             if optValue in values:
                 option = option(selected='selected')
             yield option
     tag=T.select(name=key, id=render_cssid(key), data=self.options, multiple='multiple', size=self.size)[renderOptions]
     if disabled:
         tag(class_='disabled', disabled='disabled')
     return tag
Esempio n. 19
0
 def render_manifest_form(self, ctx, data):
     ophandle = base32.b2a(os.urandom(16))
     manifest = T.form(
         action=".", method="post",
         enctype="multipart/form-data")[T.fieldset[
             T.input(type="hidden", name="t", value="start-manifest"),
             T.legend(class_="freeform-form-label"
                      )["Run a manifest operation (EXPENSIVE)"],
             T.div["Output Format: ",
                   T.select(name="output")[
                       T.option(value="html", selected="true")["HTML"],
                       T.option(value="text")["text"],
                       T.option(value="json")["JSON"], ], ],
             T.input(type="hidden", name="ophandle", value=ophandle),
             T.input(type="submit", value="Manifest"), ]]
     return ctx.tag[manifest]
Esempio n. 20
0
 def render_manifest_form(self, ctx, data):
     ophandle = base32.b2a(os.urandom(16))
     manifest = T.form(action=".", method="post",
                         enctype="multipart/form-data")[
         T.fieldset[
         T.input(type="hidden", name="t", value="start-manifest"),
         T.legend(class_="freeform-form-label")["Run a manifest operation (EXPENSIVE)"],
         T.div["Output Format: ",
               T.select(name="output")
               [ T.option(value="html", selected="true")["HTML"],
                 T.option(value="text")["text"],
                 T.option(value="json")["JSON"],
                 ],
               ],
         T.input(type="hidden", name="ophandle", value=ophandle),
         T.input(type="submit", value="Manifest"),
         ]]
     return ctx.tag[manifest]
Esempio n. 21
0
 def _renderTag(self, ctx, tparser, tvalue, namer, readonly):
     tag=T.invisible()
     if len(self.parsers) > 1:
         tp = T.select(name=namer('tparser'),id=render_cssid(namer('tparser')))
         if readonly:
             tp(class_='disabled', disabled='disabled')        
         
         for k,v in self.parsers:
             if k == tparser:
                 tp[T.option(selected='selected',value=k)[ v ]]
             else:
                 tp[T.option(value=k)[ v ]]
     else:
         tp = T.input(type='hidden',name=namer('tparser'),id=render_cssid(namer('tparser')),value=self.parsers[0][0])
     ta=T.textarea(name=namer('tvalue'), id=render_cssid(namer('tvalue')), cols=self.cols, rows=self.rows)[tvalue or '']
     if readonly:
         ta(class_='readonly', readonly='readonly')
     tag[tp,T.br,ta]
     return tag
Esempio n. 22
0
    def _renderTag(self, ctx, key, value, converter, disabled):

        def renderOptions(ctx, data):
            if self.noneOption is not None:
                yield T.option(value=iformal.IKey(self.noneOption).key())[iformal.ILabel(self.noneOption).label()]
            if data is None:
                return
            for item in data:
                optValue = iformal.IKey(item).key()
                optLabel = iformal.ILabel(item).label()
                optValue = converter.fromType(optValue)
                option = T.option(value=optValue)[optLabel]
                if optValue == value:
                    option = option(selected='selected')
                yield option

        tag=T.select(name=key, id=render_cssid(key), data=self.options)[renderOptions]
        if disabled:
            tag(class_='disabled', disabled='disabled')
        return tag
Esempio n. 23
0
class ChoiceRenderer(BaseInputRenderer):
    default_select = tags.select(
        id=slot('id'), name=slot('name'),
        render=tags.directive('sequence'))[tags.option(
            pattern="item", value=valToKey,
            render=isSelected)[lambda c, d: iformless.ITyped(c).stringify(d)]]

    def input(self, context, slot, data, name, value):
        tv = data.typedValue
        choices = tv.choices

        if value:
            context.remember(value, csv)
        else:
            context.remember('', csv)

        try:
            selector = context.tag.patternGenerator('selector')
        except NodeNotFound:
            selector = self.default_select

        return selector(data=choices)
Esempio n. 24
0
    def _renderTag(self, ctx, key, value, readonly):
        html = []
        tag=T.textarea(name=key, id=render_cssid(key), cols=self.cols, rows=self.rows)[value or '']
        if readonly:
            tag(class_='readonly', readonly='readonly')
        html.append(tag)
        if self.values is None:
            return html
        
        def renderOptions(ctx,options):
            for value,label in options:
                yield T.option(value=value)[label] 

            
        selecttrigger = T.select(name='%s__selecttrigger'%key, data=self.values)[ renderOptions ]


            
        form = iformal.IForm( ctx )
        js = T.xml("var x = document.getElementById('%(form)s');x.%(key)s.value += x.%(key)s__selecttrigger.options[x.%(key)s__selecttrigger.options.selectedIndex].value + "\\n";"%{'key':key,'form':form.name})
        aonclick = T.a(onclick=js)[ 'add' ]
        html.append(T.div(class_="add")[selecttrigger,aonclick])
        return html
Esempio n. 25
0
class CommandWidget(athena.LiveElement, results.NotifierParent):
    jsClass = u'ControllerModule.CommandWidget'
    
    docFactory = loaders.stan(tags.div(render=tags.directive('liveElement'))[
        tags.table(id="commandWidget", hidden=True)[
        tags.tr[tags.td["cmd"],tags.td["targets"], tags.td["args"]],
        tags.tr[tags.form(id="cmdform",
            action="""javascript:
            var w = Nevow.Athena.Widget.get(document.getElementById('cmdform'));
            var cmd = document.getElementById('cmd');
            cmd = cmd.options[cmd.selectedIndex].value;
            var targets = document.getElementById('targets').value;
            var args = document.getElementById('args').value;
            w.submitCommand(cmd, targets, args);""")[
            
            tags.td[tags.select(id="cmd", name="cmd",
            onchange="Nevow.Athena.Widget.get(this).changeCmd(this.options[cmd.selectedIndex].value);")[
                tags.option(value="execute")["execute"],
                tags.option(value="executeFile")["execute file"],
                tags.option(value="pull")["pull"],
                tags.option(value="reset")["reset"],
                tags.option(value="kill")["kill"],
            ]],
            tags.td[tags.input(type="text", id="targets", name="targets")],
            tags.td[tags.input(type="text", id="args", name="args")],
            tags.td[tags.input(type="submit", value="exec")]
        ]],
        tags.tr[tags.td(colspan='4', style="text-align: center;")[tags.div(id="commandOut")]]
        ]
    ])
    
    def __init__(self, controller):
        self.controller = controller
        reactor.callLater(.1, self.callRemote, 'getIDs')
    
    def execute(self, targets, lines):
        idlist = parseTargets(targets)
        if idlist is False:
            return self.fail(None)
        d = self.controller.execute(idlist, str(lines))
        self.notify(None)
        return d.addCallbacks(self.executeOK, self.fail)
    
    athena.expose(execute)
    
    def executeOK(self, resultList):
        s = ''
        for r in resultList:
            s += resultToHTML(r)
        self.finish(unicode(s))
    
    def executeFile(self, targets, f):
        print f
    
    athena.expose(executeFile)
    
    def pull(self, targets, keystr):
        keys = map(str, keystr.split(','))
        idlist = parseTargets(targets)
        if not idlist or not keys:
            return self.fail(None)
        d = self.controller.pullNamespace(idlist, *keys)
        self.notify(None)
        return d.addCallbacks(self.pullOK, self.fail)
    
    athena.expose(pull)
    
    def pullOK(self, resultList):
        s = ''
        # print resultList
        for r in resultList:
            s += dictToHTML(r)
        return self.finish(s)
    
    def reset(self, targets, _):
        idlist = parseTargets(targets)
        if not idlist:
            return self.fail(None)
        d = self.controller.reset(idlist)
        return d.addCallbacks(self.resetOK, self.fail)
    
    athena.expose(reset)
    
    def resetOK(self, r):
        return self.finish('')
    
    def kill(self, targets, _):
        idlist = parseTargets(targets)
        if not idlist:
            return self.fail(None)
        d = self.controller.kill(idlist)
        return d.addCallbacks(self.killOK, self.fail)
    
    athena.expose(kill)
    
    def killOK(self, r):
        return self.finish('')
    
    def finish(self, s):
        self.notify(None)
        return self.callRemote('commandOutput', unicode(s))
    
    def fail(self, f=None):
        return self.finish('Failure')
Esempio n. 26
0
 def render_choiceOption(self, ctx, choice):
     return T.select(name=choice.getName())[[
         T.option(value=x)[x] for x in choice.getChoices()]]
    def render_listRow(self, ctx: WovenContext, data=None):
        IEventBus("Web").register(self, ITimeEntryChangedEvent)
        listCell = inevow.IQ(ctx).patternGenerator("listCell")
        original = self._timeEntry.original
        self.expanded = False
        st = self._timeEntry.period.startTime()
        et = self._timeEntry.period.endTime(False)
        ctx.fillSlots('index', self._timeEntry.storeID)
        approved = T.input(id='approved', type='checkbox', checked=self._timeEntry.approved)[
            T.Tag('athena-handler')(event='onchange', handler='approvedClicked')
        ]
        te_type = T.input(id='entryType', type='text', disabled=True, value=self._timeEntry.type.name)
        if self._timeEntry.workLocation:
            WLs = self._timeEntry.getEmployee().getWorkLocations()
            missing = False
            if self._timeEntry.workLocation not in WLs:
                WLs.append(self._timeEntry.workLocation)
                missing = True
            workLocationID = T.select(id='workLocation', value=self._timeEntry.workLocation.workLocationID)[
                [T.option(value=i.workLocationID, selected=self._timeEntry.workLocation == i)[i.description] for i in
                 WLs]
            ]
            if missing:
                workLocationID(style='background-color:red')
        else:
            workLocationID = T.input(id='workLocation', disabled=True, value='None')
        if self._timeEntry.subAccount:
            SAs = list(self._timeEntry.getEmployee().getSubAccounts())
            missing = False
            if self._timeEntry.subAccount not in SAs:
                SAs.append(self._timeEntry.subAccount)
                missing = True
            subAccount = T.select(id='subAccount', value=self._timeEntry.subAccount.sub)[
                [T.option(value=i.sub, selected=self._timeEntry.subAccount==i)[i.name] for i in SAs]
            ]
            if missing:
                subAccount(style='background-color:red')
        else:
            subAccount = T.input(id='subAccount', disabled=True, value="None")
        duration = T.input(id='duration', value=formatTimeDelta(self._timeEntry.period.duration()))
        if self._timeEntry.type == IEntryType("Work"):
            ET = T.input(id='endTime', value=et.strftime('%Y-%m-%d %H:%M:%S %Z') if et else 'None')
            et = listCell(data=dict(listItem=ET))
            reject = T.input(id='denied', type='checkbox', checked=self._timeEntry.denied)[
                T.Tag('athena-handler')(event='onchange', handler='deniedClicked')
            ]

            rj = listCell(data=dict(listItem=reject))
            duration(disabled=True)
        else:
            ET = T.input(style='display:none', id='entryType', value=self._timeEntry.type.getTypeName())
            et = listCell(data=dict(listItem=ET))
            reject = T.input(id='denied', type='checkbox', checked=self._timeEntry.denied)
            rj = listCell(data=dict(listItem=reject))

        startTime = T.input(id='startTime', value=st.strftime('%Y-%m-%d %H:%M:%S %Z') if st else 'None')
        if self._timeEntry.employee.timeEntry is self._timeEntry:
            ET(disabled=True)
        if not self.employee.isAdministrator() or self.parent.selectable or self.employee is self._timeEntry.employee:

            workLocationID(disabled=True)
            subAccount(disabled=True)
            startTime(disabled=True)
            ET(disabled=True)
            duration(disabled=True)
            if self._timeEntry.denied or \
                    self._timeEntry.approved or \
                    not self.employee.isSupervisor() or \
                    self._timeEntry.employee not in ISupervisor(self.employee).getEmployees() or \
                    self._timeEntry.subAccount not in ISupervisor(self.employee).getSubAccounts() or \
                    self.parent.selectable or \
                    self.employee is self._timeEntry.employee:
                reject(disabled=True)
                approved(disabled=True)
        startday = self._timeEntry.startTime().date()
        endday = startday.replace(hours=23, minutes=59, seconds=59)

        store = self._timeEntry.store
        q = AND(
            TimeEntry.period==TimePeriod.storeID,
            TimeEntry.employee==self._timeEntry.employee,
            TimeEntry.denied==False,
            TimePeriod._startTime <= endday,
            OR(TimePeriod._endTime >= startday,
               TimePeriod._endTime==None
            )
        )
        if store:
            entries = ICalendarData([i[0] for i in store.query((TimeEntry, TimePeriod), q)]).between(startday, endday)
        else:
            entries = ICalendarData([])

        lastEntryOfDay = entries.entries and entries.entries[-1].startTime() == self._timeEntry.startTime()
        if lastEntryOfDay:
            total = T.input(id='total', value=formatTimeDelta(entries.sumBetween(startday, endday)))
            total(disabled=True)
            total = listCell(data=dict(listItem=total))
        else:
            total = listCell(data=dict(listItem=""))(style='opacity: 0')
        self.preprocess([approved, workLocationID, subAccount, startTime, ET, duration, reject, total])
        r = [listCell(data=dict(listItem=te_type)),
             listCell(data=dict(listItem=workLocationID if not self._showEmployee else T.input(disabled=True, value=self._timeEntry.employee.name))),
             listCell(data=dict(listItem=subAccount)),
             listCell(data=dict(listItem=startTime)),
             et,
             listCell(data=dict(listItem=duration)),
             total,
             listCell(data=dict(listItem=approved)),
             rj]
        if original and original.period:
            workLocationID(title=original.workLocation.description)
            subAccount(title=original.subAccount.name)
            startTime(title=original.startTime().strftime('%Y-%m-%d %H:%M:%S %Z'))
            ET(title=original.endTime(False).strftime('%Y-%m-%d %H:%M:%S %Z') if original.endTime(False) else 'None')
        return r
Esempio n. 28
0
 def render_locations(self, ctx, data):
     return ctx.tag[tags.select(id="location", name="interface")[[
         tags.option(value=i)[j] for i, j in self.getLocations()
     ]]]