コード例 #1
0
ファイル: checkout.py プロジェクト: jkrooskos/occams_lims
def checkout_update(context, request):
    db_session = request.db_session
    vals = filter_aliquot(context, request, state='pending-checkout')

    available_locations = [
        (l.id, l.title)
        for l in db_session.query(models.Location).order_by('title')]

    class CheckoutForm(wtforms.Form):
        location_id = wtforms.SelectField(
            _('Lab Location'),
            description=_('The location of the aliquot'),
            choices=available_locations,
            coerce=int,
            validators=[
                wtforms.validators.DataRequired()])
        sent_date = DateField(
            _(u'Sent Date'),
            description=_(u'Date sent for analysis.'),
            validators=[
                wtforms.validators.Optional(),
                DateRange(min=date(1900, 1, 1))
            ])
        sent_name = wtforms.StringField(
            _(u'Sent Name '),
            description=_(u'The name of the aliquot\'s receiver.'),
            validators=[wtforms.validators.Optional()])
        sent_notes = wtforms.TextAreaField(
            _(u'Sent Notes '),
            description=_(u'Notes about this aliquot\'s destination'),
            validators=[wtforms.validators.Optional()])

    form = CheckoutForm(request.POST, location_id=context.id)

    if request.method == 'POST' and check_csrf_token(request):

        if 'save' in request.POST and form.validate():
            for sample in vals['full_query']:
                apply_changes(form, sample)
            request.session.flash(_(u'Changed saved'), 'success')
            return HTTPOk(json={
                '__next__': request.current_route_path(
                    _route_name='lims.checkout')
            })

    vals.update({
        'form': form
    })

    return vals
コード例 #2
0
ファイル: checkout.py プロジェクト: mstroehle/occams_lims
def checkout_update(context, request):
    db_session = request.db_session
    vals = filter_aliquot(context, request, state='pending-checkout')

    available_locations = [
        (l.id, l.title)
        for l in db_session.query(models.Location).order_by('title')
    ]

    class CheckoutForm(wtforms.Form):
        location_id = wtforms.SelectField(
            _('Lab Location'),
            description=_('The location of the aliquot'),
            choices=available_locations,
            coerce=int,
            validators=[wtforms.validators.DataRequired()])
        sent_date = DateField(_(u'Sent Date'),
                              description=_(u'Date sent for analysis.'),
                              validators=[
                                  wtforms.validators.Optional(),
                                  DateRange(min=date(1900, 1, 1))
                              ])
        sent_name = wtforms.StringField(
            _(u'Sent Name '),
            description=_(u'The name of the aliquot\'s receiver.'),
            validators=[wtforms.validators.Optional()])
        sent_notes = wtforms.TextAreaField(
            _(u'Sent Notes '),
            description=_(u'Notes about this aliquot\'s destination'),
            validators=[wtforms.validators.Optional()])

    form = CheckoutForm(request.POST, location_id=context.id)

    if request.method == 'POST' and check_csrf_token(request):

        if 'save' in request.POST and form.validate():
            for sample in vals['full_query']:
                apply_changes(form, sample)
            request.session.flash(_(u'Changed saved'), 'success')
            return HTTPOk(
                json={
                    '__next__':
                    request.current_route_path(_route_name='lims.checkout')
                })

    vals.update({'form': form})

    return vals
コード例 #3
0
def checked_in(context, request):
    db_session = request.db_session
    vals = filter_aliquot(context, request, state='checked-in')
    aliquot = vals['aliquot']

    available_locations = [
        (l.id, l.title)
        for l in db_session.query(models.Location).order_by('title')
    ]

    if 'checkout' in request.POST:
        conditionally_required = required_if('ui_selected')
    else:
        conditionally_required = wtforms.validators.optional()

    class CheckoutForm(wtforms.Form):
        ui_selected = wtforms.BooleanField()
        id = wtforms.IntegerField(widget=wtforms.widgets.HiddenInput())
        amount = wtforms.DecimalField(places=1,
                                      validators=[conditionally_required])
        freezer = wtforms.StringField(
            validators=[wtforms.validators.optional()])
        rack = wtforms.StringField(validators=[wtforms.validators.optional()])
        box = wtforms.StringField(validators=[wtforms.validators.optional()])
        thawed_num = wtforms.IntegerField(
            validators=[wtforms.validators.optional()])
        location_id = wtforms.SelectField(
            choices=available_locations,
            coerce=int,
            validators=[wtforms.validators.optional()])
        notes = wtforms.TextAreaField(
            validators=[wtforms.validators.optional()])

    class CrudForm(wtforms.Form):
        aliquot = wtforms.FieldList(wtforms.FormField(CheckoutForm))

    form = CrudForm(request.POST, aliquot=aliquot)

    if request.method == 'POST' and check_csrf_token(request):

        if 'save' in request.POST and form.validate():
            for i, entry in enumerate(form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
            request.session.flash(_(u'Changed saved'), 'success')
            return HTTPFound(location=request.current_route_path())

        elif 'pending-checkout' in request.POST and form.validate():
            state = (db_session.query(
                models.AliquotState).filter_by(name='pending-checkout').one())
            updated_count = 0
            for i, entry in enumerate(form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
                if entry.ui_selected.data:
                    aliquot[i].location = context
                    aliquot[i].state = state
                    updated_count += 1
            db_session.flush()
            if updated_count:
                request.session.flash(
                    _(
                        u'${count} aliquot have been changed to the status of '
                        u'${state}',
                        mapping={
                            'count': updated_count,
                            'state': state.title
                        }), 'success')
            else:
                request.session.flash(_(u'Please select Aliquot'), 'warning')
            return HTTPFound(location=request.current_route_path())

    vals.update({
        'form': form,
    })

    return vals
コード例 #4
0
ファイル: aliquot.py プロジェクト: jkrooskos/occams_lims
def aliquot(context, request):
    db_session = request.db_session
    specimen_vals = filter_specimen(context,
                                    request,
                                    page_key='specimenpage',
                                    state='pending-aliquot')

    specimen = specimen_vals['specimen']
    template_values = [{
        'specimen': s,
        'collect_date': date.today()
    } for s in specimen]

    aliquot_vals = filter_aliquot(context,
                                  request,
                                  page_key='aliquotpage',
                                  state='pending')
    aliquot = aliquot_vals['aliquot']

    label_queue = request.session.setdefault(ALIQUOT_LABEL_QUEUE, set())

    class AliquotForm(wtforms.Form):
        ui_selected = wtforms.BooleanField()
        id = wtforms.IntegerField(widget=wtforms.widgets.HiddenInput())
        amount = wtforms.DecimalField(
            places=1, validators=[wtforms.validators.required()])
        collect_date = DateField(validators=[
            wtforms.validators.required(),
            DateRange(min=date(1900, 1, 1))
        ])
        collect_time = TimeField(validators=[
            wtforms.validators.required(),
        ])
        freezer = wtforms.StringField(
            validators=[wtforms.validators.optional()])
        rack = wtforms.StringField(validators=[wtforms.validators.optional()])
        box = wtforms.StringField(validators=[wtforms.validators.optional()])
        notes = wtforms.TextAreaField(
            validators=[wtforms.validators.optional()])

    class SpecimenAliquotForm(AliquotForm):
        count = wtforms.IntegerField(validators=[
            required_if('ui_selected'),
            wtforms.validators.optional()
        ])
        aliquot_type_id = wtforms.SelectField(
            coerce=int, validators=[required_if('ui_selected')])

        def __init__(self, *args, **kw):
            super(AliquotForm, self).__init__(*args, **kw)

            if 'obj' in kw:
                obj = kw['obj']
                if isinstance(obj, models.Specimen):
                    specimen = obj
                elif isinstance(obj, models.Aliquot):
                    specimen = obj.specimen
            else:
                try:
                    specimen = kw['specimen']
                except KeyError:
                    specimen = None

            if specimen:
                self.aliquot_type_id.choices = [
                    (t.id, t.title)
                    for t in specimen.specimen_type.aliquot_types.values()
                ]
            else:
                self.aliquot_type_id.choices = []

    class SpecimenCrudForm(wtforms.Form):
        specimen = wtforms.FieldList(wtforms.FormField(SpecimenAliquotForm))

    class AliquotCrudForm(wtforms.Form):
        aliquot = wtforms.FieldList(wtforms.FormField(AliquotForm))

    # Accomodate WTForm's inability to process multiple forms on the same page
    # by only passing in the appropriate formdata to the target form

    if 'template-form' in request.POST:
        specimen_formdata = request.POST
    else:
        specimen_formdata = None

    if 'aliquot-form' in request.POST:
        aliquot_formdata = request.POST
    else:
        aliquot_formdata = None

    specimen_form = SpecimenCrudForm(specimen_formdata,
                                     specimen=template_values)
    aliquot_form = AliquotCrudForm(aliquot_formdata, aliquot=aliquot)

    def update_print_queue():
        queued = 0
        for entry in aliquot_form.aliquot.entries:
            subform = entry.form
            if subform.ui_selected.data:
                id = subform.id.data
                if id in label_queue:
                    label_queue.discard(id)
                else:
                    queued += 1
                    label_queue.add(id)
                request.session.changed()
        return queued

    if request.method == 'POST' and check_csrf_token(request):

        if not request.has_permission('process'):
            raise HTTPForbidden

        if 'create' in request.POST and specimen_form.validate():
            state = (db_session.query(
                models.AliquotState).filter_by(name='pending').one())
            location = context
            processed_count = 0

            for i, entry in enumerate(specimen_form.specimen.entries):
                subform = entry.form

                # Yes, you are reading this correctly, the original
                # code said it needs to be selected AND set
                if not (subform.ui_selected.data and subform.count.data):
                    continue

                kw = subform.data
                kw['specimen'] = specimen[i]
                kw['state'] = state
                kw['location'] = location
                kw['inventory_date'] = kw['collect_date']
                kw['previous_location'] = location

                # clean up the dictionary
                for field in ['id', 'ui_selected', 'count']:
                    if field in kw.keys():
                        del kw[field]

                count = subform.count.data
                samples = [models.Aliquot(**kw) for i in range(count)]
                db_session.add_all(aliquot)
                db_session.flush()

                processed_count += len(samples)

            if processed_count:
                request.session.changed()
                request.session.flash(
                    _(u'Successfully created %d Aliquot' % processed_count),
                    'success')
            else:
                request.session.flash(_(u'No Aliquot created.'), 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'pending-draw' in request.POST:
            state_name = 'pending-draw'
            state = (db_session.query(
                models.SpecimenState).filter_by(name=state_name).one())
            transitioned_count = 0
            for i, subform in enumerate(specimen_form.specimen.entries):
                if subform.ui_selected.data:
                    specimen[i].state = state
                    transitioned_count += 1
            if transitioned_count:
                db_session.flush()
                request.session.flash(
                    _(
                        u'${count} specimen have been changed to the '
                        u'status of ${state}.',
                        mapping={
                            'count': transitioned_count,
                            'state': state.title
                        }), 'success')
            else:
                request.session.flash(u'Please select specimen', 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'aliquoted' in request.POST:
            state_name = 'aliquoted'
            state = (db_session.query(
                models.SpecimenState).filter_by(name=state_name).one())
            transitioned_count = 0
            for i, subform in enumerate(specimen_form.specimen.entries):
                if subform.ui_selected.data:
                    specimen[i].state = state
                    transitioned_count += 1
            if transitioned_count:
                db_session.flush()
                request.session.flash(
                    _(
                        u'${count} specimen have been changed to the '
                        u'status of ${state}.',
                        mapping={
                            'count': transitioned_count,
                            'state': state.title
                        }), 'success')
            else:
                request.session.flash(u'Please select specimen', 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'save' in request.POST and aliquot_form.validate():
            updated_count = 0
            for i, entry in enumerate(aliquot_form.aliquot.entries):
                if apply_changes(entry.form, aliquot[i]):
                    updated_count += 1
            if updated_count:
                request.session.flash(
                    _(u'Updated ${count} aliquot',
                      mapping={'count': updated_count}), 'success')
            else:
                request.session.flash(_(u'No changes made'), 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'queue' in request.POST and aliquot_form.validate():
            for i, subform in enumerate(aliquot_form.aliquot.entries):
                apply_changes(subform.form, aliquot[i])
            queue_count = update_print_queue()
            if queue_count:
                request.session.flash(u'Aliquot print queue has changed.',
                                      'success')
            else:
                request.session.flash(u'Please select aliquot', 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'checkin' in request.POST and aliquot_form.validate():
            transitioned_count = 0
            state = (db_session.query(
                models.AliquotState).filter_by(name='checked-in').one())
            for i, entry in enumerate(aliquot_form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
                if entry.ui_selected.data:
                    aliquot[i].state = state
                    transitioned_count += 1
            update_print_queue()
            if transitioned_count > 0:
                request.session.flash(
                    _(
                        u'${count} aliquot have been changed to the status '
                        u'of ${state}.',
                        mapping={
                            'count': transitioned_count,
                            'state': state.title
                        }), 'success')
            else:
                request.session.flash(u'Please select aliquot', 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'delete' in request.POST and aliquot_form.validate():
            deleted_count = 0
            for i, entry in enumerate(aliquot_form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
                if entry.ui_selected.data:
                    deleted_count += 1
                    db_session.delete(aliquot[i])
            update_print_queue()
            if deleted_count > 0:
                request.session.flash(
                    _(u'${count} aliquot have been deleted.',
                      mapping={'count': deleted_count}), 'success')
            else:
                request.session.flash(_(u'Please select Aliquot'), 'warning')
            return HTTPFound(location=request.current_route_path())

    return {
        'filter_form': aliquot_vals['filter_form'],
        'has_aliquot': aliquot_vals['has_aliquot'],
        'aliquot': aliquot_vals['aliquot'],
        'aliquot_pager': aliquot_vals['pager'],
        'aliquot_form': aliquot_form,
        'has_labels_queued': len(label_queue),
        'label_queue': label_queue,
        'has_specimen': specimen_vals['has_specimen'],
        'specimen': specimen_vals['specimen'],
        'specimen_pager': specimen_vals['pager'],
        'specimen_form': specimen_form,
    }
コード例 #5
0
ファイル: checkout.py プロジェクト: davidmote/occams_lims
def checkout(context, request):
    db_session = request.db_session
    vals = filter_aliquot(context, request, state='pending-checkout')
    aliquot = vals['aliquot']

    available_locations = [
        (l.id, l.title)
        for l in db_session.query(models.Location).order_by('title')
    ]

    # TODO: the values in this form really should be in the crud form
    # since the receipt depends on the sent loation being unique.
    # If we ever do this, "bulk update" button won't be needed anymore
    class CheckoutForm(wtforms.Form):
        ui_selected = wtforms.BooleanField()
        id = wtforms.IntegerField(widget=wtforms.widgets.HiddenInput())
        location_id = wtforms.SelectField(
            choices=available_locations,
            coerce=int,
            validators=[wtforms.validators.DataRequired()])
        sent_date = DateField(validators=[wtforms.validators.Optional()])
        sent_name = wtforms.StringField(
            validators=[wtforms.validators.Optional()])
        sent_notes = wtforms.TextAreaField(
            validators=[wtforms.validators.Optional()])

    class CrudForm(wtforms.Form):
        aliquot = wtforms.FieldList(wtforms.FormField(CheckoutForm))

    form = CrudForm(request.POST, aliquot=aliquot)

    if request.method == 'POST' and check_csrf_token(request):

        if 'save' in request.POST and form.validate():
            for i, entry in enumerate(form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
            request.session.flash(_(u'Changed saved'), 'success')
            return HTTPFound(location=request.current_route_path())

        elif 'return' in request.POST and form.validate():
            state = (db_session.query(
                models.AliquotState).filter_by(name='checked-in').one())
            updated_count = 0
            for i, entry in enumerate(form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
                if entry.ui_selected.data:
                    aliquot[i].location = context
                    aliquot[i].state = state
                    updated_count += 1
            db_session.flush()
            if updated_count:
                request.session.flash(
                    _(
                        u'${count} aliquot have been changed to the status '
                        u'of ${state}',
                        mapping={
                            'count': updated_count,
                            'state': state.title
                        }), 'success')
            else:
                request.session.flash(_(u'Please select Aliquot'), 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'complete' in request.POST and form.validate():
            state = (db_session.query(
                models.AliquotState).filter_by(name='checked-out').one())
            updated_count = 0
            for i, entry in enumerate(form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
                if entry.ui_selected.data:
                    aliquot[i].state = state
                    updated_count += 1
            db_session.flush()
            if updated_count:
                request.session.flash(
                    _(
                        u'${count} aliquot have been changed to the status '
                        u'of ${state}',
                        mapping={
                            'count': updated_count,
                            'state': state.title
                        }), 'success')
            else:
                request.session.flash(_(u'Please select Aliquot'), 'warning')
            return HTTPFound(location=request.current_route_path())

    vals.update({
        'form': form,
    })

    return vals
コード例 #6
0
ファイル: aliquot.py プロジェクト: razorlabs/occams_lims
def aliquot(context, request):
    db_session = request.db_session
    specimen_vals = filter_specimen(
        context, request, page_key='specimenpage', state='pending-aliquot')

    specimen = specimen_vals['specimen']
    template_values = [
        {'specimen': s, 'collect_date': date.today()}
        for s in specimen
    ]

    aliquot_vals = filter_aliquot(
        context, request, page_key='aliquotpage', state='pending')
    aliquot = aliquot_vals['aliquot']

    label_queue = request.session.setdefault(ALIQUOT_LABEL_QUEUE, set())

    class AliquotForm(wtforms.Form):
        ui_selected = wtforms.BooleanField()
        id = wtforms.IntegerField(
            widget=wtforms.widgets.HiddenInput())
        amount = wtforms.DecimalField(
            places=1,
            validators=[wtforms.validators.required()])
        collect_date = DateField(
            validators=[
                wtforms.validators.required(),
                DateRange(min=date(1900, 1, 1))
            ])
        collect_time = TimeField(
            validators=[
                wtforms.validators.required(),
            ])
        freezer = wtforms.StringField(
            validators=[wtforms.validators.optional()])
        rack = wtforms.StringField(
            validators=[wtforms.validators.optional()])
        box = wtforms.StringField(
            validators=[wtforms.validators.optional()])
        notes = wtforms.TextAreaField(
            validators=[wtforms.validators.optional()])

    class SpecimenAliquotForm(wtforms.Form):
        """
        Similar form to Aliquot, except the fields are conditionally required
        if they are selected
        """

        ui_selected = wtforms.BooleanField()
        id = wtforms.IntegerField(
            widget=wtforms.widgets.HiddenInput())
        amount = wtforms.DecimalField(
            places=1,
            validators=[required_if('ui_selected')])
        collect_date = DateField(
            validators=[
                required_if('ui_selected'),
                DateRange(min=date(1900, 1, 1))
            ])
        collect_time = TimeField(
            validators=[required_if('ui_selected')])
        freezer = wtforms.StringField(
            validators=[wtforms.validators.optional()])
        rack = wtforms.StringField(
            validators=[wtforms.validators.optional()])
        box = wtforms.StringField(
            validators=[wtforms.validators.optional()])
        notes = wtforms.TextAreaField(
            validators=[wtforms.validators.optional()])

        count = wtforms.IntegerField(
            validators=[
                required_if('ui_selected'),
                wtforms.validators.optional()
            ]
        )
        aliquot_type_id = wtforms.SelectField(
            coerce=int,
            validators=[required_if('ui_selected')]
        )

        def __init__(self, *args, **kw):
            super(SpecimenAliquotForm, self).__init__(*args, **kw)

            specimen = None

            if 'obj' in kw:
                obj = kw['obj']
                if isinstance(obj, models.Specimen):
                    specimen = obj
                elif isinstance(obj, models.Aliquot):
                    specimen = obj.specimen
            elif 'specimen' in kw:
                specimen = kw['specimen']

            if specimen:
                self.aliquot_type_id.choices = [
                    (t.id, t.title)
                    for t in specimen.specimen_type.aliquot_types.values()]
            else:
                self.aliquot_type_id.choices = []

    class SpecimenCrudForm(wtforms.Form):
        specimen = wtforms.FieldList(wtforms.FormField(SpecimenAliquotForm))

    class AliquotCrudForm(wtforms.Form):
        aliquot = wtforms.FieldList(wtforms.FormField(AliquotForm))

    # Accomodate WTForm's inability to process multiple forms on the same page
    # by only passing in the appropriate formdata to the target form

    if 'template-form' in request.POST:
        specimen_formdata = request.POST
    else:
        specimen_formdata = None

    if 'aliquot-form' in request.POST:
        aliquot_formdata = request.POST
    else:
        aliquot_formdata = None

    specimen_form = SpecimenCrudForm(specimen_formdata, specimen=template_values)
    aliquot_form = AliquotCrudForm(aliquot_formdata, aliquot=aliquot)

    def update_print_queue():
        queued = 0
        for entry in aliquot_form.aliquot.entries:
            subform = entry.form
            if subform.ui_selected.data:
                id = subform.id.data
                if id in label_queue:
                    label_queue.discard(id)
                else:
                    queued += 1
                    label_queue.add(id)
                request.session.changed()
        return queued

    if request.method == 'POST' and check_csrf_token(request):

        if not request.has_permission('process'):
            raise HTTPForbidden

        if 'create' in request.POST and specimen_form.validate():
            state = (
                db_session.query(models.AliquotState)
                .filter_by(name='pending')
                .one())
            location = context
            processed_count = 0

            for i, entry in enumerate(specimen_form.specimen.entries):
                subform = entry.form

                # Yes, you are reading this correctly, the original
                # code said it needs to be selected AND set
                if not (subform.ui_selected.data and subform.count.data):
                    continue

                kw = subform.data
                kw['specimen'] = specimen[i]
                kw['state'] = state
                kw['location'] = location
                kw['inventory_date'] = kw['collect_date']
                kw['previous_location'] = location

                # clean up the dictionary
                for field in ['id', 'ui_selected', 'count']:
                    if field in kw.keys():
                        del kw[field]

                count = subform.count.data
                samples = [models.Aliquot(**kw) for i in range(count)]
                db_session.add_all(aliquot)
                db_session.flush()

                processed_count += len(samples)

            if processed_count:
                request.session.changed()
                request.session.flash(
                    _(u'Successfully created %d Aliquot' % processed_count),
                    'success')
            else:
                request.session.flash(_(u'No Aliquot created.'), 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'pending-draw' in request.POST:
            state_name = 'pending-draw'
            state = (
                db_session.query(models.SpecimenState)
                .filter_by(name=state_name)
                .one())
            transitioned_count = 0
            for i, subform in enumerate(specimen_form.specimen.entries):
                if subform.ui_selected.data:
                    specimen[i].state = state
                    transitioned_count += 1
            if transitioned_count:
                db_session.flush()
                request.session.flash(
                    _(u'${count} specimen have been changed to the '
                      u'status of ${state}.',
                        mapping={'count': transitioned_count,
                                 'state': state.title}),
                    'success')
            else:
                request.session.flash(u'Please select specimen', 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'aliquoted' in request.POST:
            state_name = 'aliquoted'
            state = (
                db_session.query(models.SpecimenState)
                .filter_by(name=state_name)
                .one())
            transitioned_count = 0
            for i, subform in enumerate(specimen_form.specimen.entries):
                if subform.ui_selected.data:
                    specimen[i].state = state
                    transitioned_count += 1
            if transitioned_count:
                db_session.flush()
                request.session.flash(
                    _(u'${count} specimen have been changed to the '
                      u'status of ${state}.',
                        mapping={'count': transitioned_count,
                                 'state': state.title}),
                    'success')
            else:
                request.session.flash(u'Please select specimen', 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'save' in request.POST and aliquot_form.validate():
            updated_count = 0
            for i, entry in enumerate(aliquot_form.aliquot.entries):
                if apply_changes(entry.form, aliquot[i]):
                    updated_count += 1
            if updated_count:
                request.session.flash(
                    _(u'Updated ${count} aliquot',
                        mapping={'count': updated_count}),
                    'success')
            else:
                request.session.flash(_(u'No changes made'), 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'queue' in request.POST and aliquot_form.validate():
            for i, subform in enumerate(aliquot_form.aliquot.entries):
                apply_changes(subform.form, aliquot[i])
            queue_count = update_print_queue()
            if queue_count:
                request.session.flash(
                    u'Aliquot print queue has changed.', 'success')
            else:
                request.session.flash(u'Please select aliquot', 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'checkin' in request.POST and aliquot_form.validate():
            transitioned_count = 0
            state = (
                db_session.query(models.AliquotState)
                .filter_by(name='checked-in')
                .one())
            for i, entry in enumerate(aliquot_form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
                if entry.ui_selected.data:
                    aliquot[i].state = state
                    transitioned_count += 1
            update_print_queue()
            if transitioned_count > 0:
                request.session.flash(
                    _(u'${count} aliquot have been changed to the status '
                      u'of ${state}.',
                        mapping={'count': transitioned_count,
                                 'state': state.title}),
                    'success')
            else:
                request.session.flash(u'Please select aliquot', 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'delete' in request.POST and aliquot_form.validate():
            deleted_count = 0
            for i, entry in enumerate(aliquot_form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
                if entry.ui_selected.data:
                    deleted_count += 1
                    db_session.delete(aliquot[i])
            update_print_queue()
            if deleted_count > 0:
                request.session.flash(
                    _(u'${count} aliquot have been deleted.',
                        mapping={'count': deleted_count}),
                    'success')
            else:
                request.session.flash(
                    _(u'Please select Aliquot'),
                    'warning')
            return HTTPFound(location=request.current_route_path())

    return {
        'filter_form': aliquot_vals['filter_form'],
        'has_aliquot': aliquot_vals['has_aliquot'],
        'aliquot': aliquot_vals['aliquot'],
        'aliquot_pager': aliquot_vals['pager'],
        'aliquot_form': aliquot_form,

        'has_labels_queued': len(label_queue),
        'label_queue': label_queue,

        'has_specimen': specimen_vals['has_specimen'],
        'specimen': specimen_vals['specimen'],
        'specimen_pager': specimen_vals['pager'],
        'specimen_form': specimen_form,
    }
コード例 #7
0
ファイル: checkout.py プロジェクト: jkrooskos/occams_lims
def checkout(context, request):
    db_session = request.db_session
    vals = filter_aliquot(context, request, state='pending-checkout')
    aliquot = vals['aliquot']

    available_locations = [
        (l.id, l.title)
        for l in db_session.query(models.Location).order_by('title')]

    # TODO: the values in this form really should be in the crud form
    # since the receipt depends on the sent loation being unique.
    # If we ever do this, "bulk update" button won't be needed anymore
    class CheckoutForm(wtforms.Form):
        ui_selected = wtforms.BooleanField()
        id = wtforms.IntegerField(
            widget=wtforms.widgets.HiddenInput())
        location_id = wtforms.SelectField(
            choices=available_locations,
            coerce=int,
            validators=[
                wtforms.validators.DataRequired()])
        sent_date = DateField(
            validators=[
                wtforms.validators.Optional(),
                DateRange(min=date(1900, 1, 1))
            ])
        sent_name = wtforms.StringField(
            validators=[wtforms.validators.Optional()])
        sent_notes = wtforms.TextAreaField(
            validators=[wtforms.validators.Optional()])

    class CrudForm(wtforms.Form):
        aliquot = wtforms.FieldList(wtforms.FormField(CheckoutForm))

    form = CrudForm(request.POST, aliquot=aliquot)

    if request.method == 'POST' and check_csrf_token(request):

        if 'save' in request.POST and form.validate():
            for i, entry in enumerate(form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
            request.session.flash(_(u'Changed saved'), 'success')
            return HTTPFound(location=request.current_route_path())

        elif 'return' in request.POST and form.validate():
            state = (
                db_session.query(models.AliquotState)
                .filter_by(name='checked-in')
                .one())
            updated_count = 0
            for i, entry in enumerate(form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
                if entry.ui_selected.data:
                    aliquot[i].location = context
                    aliquot[i].state = state
                    updated_count += 1
            db_session.flush()
            if updated_count:
                request.session.flash(
                    _(u'${count} aliquot have been changed to the status '
                      u'of ${state}',
                        mapping={
                            'count': updated_count,
                            'state': state.title
                        }),
                    'success')
            else:
                request.session.flash(_(u'Please select Aliquot'), 'warning')
            return HTTPFound(location=request.current_route_path())

        elif 'complete' in request.POST and form.validate():
            state = (
                db_session.query(models.AliquotState)
                .filter_by(name='checked-out')
                .one())
            updated_count = 0
            for i, entry in enumerate(form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
                if entry.ui_selected.data:
                    aliquot[i].state = state
                    updated_count += 1
            db_session.flush()
            if updated_count:
                request.session.flash(
                    _(u'${count} aliquot have been changed to the status '
                      u'of ${state}',
                        mapping={
                            'count': updated_count,
                            'state': state.title
                        }),
                    'success')
            else:
                request.session.flash(_(u'Please select Aliquot'), 'warning')
            return HTTPFound(location=request.current_route_path())

    vals.update({
        'form': form,
    })

    return vals
コード例 #8
0
ファイル: checkin.py プロジェクト: davidmote/occams_lims
def checkin(context, request):
    db_session = request.db_session
    vals = filter_aliquot(context, request, state='checked-out')
    aliquot = vals['aliquot']

    available_locations = [
        (l.id, l.title)
        for l in db_session.query(models.Location).order_by('title')]

    if 'checkin' in request.POST:
        conditionally_required = required_if('ui_selected')
    else:
        conditionally_required = wtforms.validators.optional()

    class CheckinForm(wtforms.Form):
        ui_selected = wtforms.BooleanField()
        id = wtforms.IntegerField(
            widget=wtforms.widgets.HiddenInput())
        amount = wtforms.DecimalField(
            places=1,
            validators=[conditionally_required])
        freezer = wtforms.StringField(
            validators=[wtforms.validators.optional()])
        rack = wtforms.StringField(
            validators=[wtforms.validators.optional()])
        box = wtforms.StringField(
            validators=[wtforms.validators.optional()])
        thawed_num = wtforms.IntegerField(
            validators=[wtforms.validators.optional()])
        location_id = wtforms.SelectField(
            choices=available_locations,
            coerce=int,
            validators=[wtforms.validators.optional()])
        notes = wtforms.TextAreaField(
            validators=[wtforms.validators.optional()])

    class CrudForm(wtforms.Form):
        aliquot = wtforms.FieldList(wtforms.FormField(CheckinForm))

    form = CrudForm(request.POST, aliquot=aliquot)

    if request.method == 'POST' and check_csrf_token(request):

        if 'save' in request.POST and form.validate():
            for i, entry in enumerate(form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
            request.session.flash(_(u'Changed saved'), 'success')
            return HTTPFound(location=request.current_route_path())

        elif 'checkin' in request.POST and form.validate():
            state = (
                db_session.query(models.AliquotState)
                .filter_by(name='checked-in')
                .one())
            updated_count = 0
            for i, entry in enumerate(form.aliquot.entries):
                apply_changes(entry.form, aliquot[i])
                if entry.ui_selected.data:
                    aliquot[i].location = context
                    aliquot[i].state = state
                    updated_count += 1
            db_session.flush()
            if updated_count:
                request.session.flash(
                    _(u'${count} aliquot have been changed to the status of '
                      u'${state}',
                        mapping={
                            'count': updated_count,
                            'state': state.title
                        }),
                    'success')
            else:
                request.session.flash(_(u'Please select Aliquot'), 'warning')
            return HTTPFound(location=request.current_route_path())

    vals.update({
        'form': form,
    })

    return vals
コード例 #9
0
def settings(context, request):
    """
    Manages application-wide settings
    """

    if request.method == 'POST':
        check_csrf_token(request)

    db_session = request.db_session

    specimen_types = (db_session.query(models.SpecimenType).order_by(
        models.SpecimenType.title).all())

    specimen_types_count = len(specimen_types)

    aliquot_types = (db_session.query(models.AliquotType).options(
        orm.joinedload('specimen_type')).join(
            models.AliquotType.specimen_type).order_by(
                models.SpecimenType.title, models.AliquotType.title).all())

    aliquot_types_count = len(specimen_types)

    labs_types = (db_session.query(models.Location).order_by(
        models.Location.title).all())

    class SpecimenTypeForm(wtforms.Form):

        ui_selected = wtforms.BooleanField()

        id = wtforms.HiddenField()

        title = wtforms.StringField(label=_(u'Title'),
                                    description=_(u'The displayed label'),
                                    validators=[
                                        wtforms.validators.input_required(),
                                    ])

        description = wtforms.TextAreaField(
            label=_(u'Description'),
            validators=[wtforms.validators.optional()])

        tube_type = wtforms.StringField(
            label=_(u'Tube Type'), validators=[wtforms.validators.optional()])

        default_tubes = wtforms.IntegerField(
            label=_(u'Default Amount'),
            description=_(u'Default amount to use by default when '
                          u'a new specimen'),
            validators=[wtforms.validators.optional()])

        def validate_title(self, field):
            query = (db_session.query(
                models.SpecimenType).filter_by(name=slugify(field.data)))

            # apparently the removed field remains as None...
            if self.id and self.id.data:
                query = query.filter(models.SpecimenType.id != self.id.data)

            (exists, ) = db_session.query(query.exists()).one()

            if exists:
                raise wtforms.validators.ValidationError(
                    _('A type with a similar name already exists'))

    class SpecimenTypeCrudForm(wtforms.Form):

        types = wtforms.FieldList(wtforms.FormField(SpecimenTypeForm))

    class AliquotTypeForm(wtforms.Form):

        ui_selected = wtforms.BooleanField()

        id = wtforms.HiddenField()

        specimen_type_id = wtforms.SelectField(
            label=_(u'Specimen Type'),
            description=_(
                u'The specimen type this sample type can processed from'),
            choices=[(t.id, t.title) for t in specimen_types],
            coerce=int,
            validators=[wtforms.validators.input_required()])

        title = wtforms.StringField(label=_(u'Title'),
                                    validators=[
                                        wtforms.validators.input_required(),
                                    ])

        description = wtforms.TextAreaField(
            label=_(u'Description'),
            validators=[wtforms.validators.optional()])

        units = wtforms.StringField(
            label=_(u'Measuring Units'),
            description=_(u'The unit of measurement per-sample of this type'),
            validators=[wtforms.validators.input_required()])

        def validate_title(self, field):
            query = (db_session.query(
                models.AliquotType).filter_by(name=slugify(field.data)))

            # apparently the removed field remains as None...
            if self.id and self.id.data:
                query = query.filter(models.AliquotType.id != self.id.data)

            (exists, ) = db_session.query(query.exists()).one()

            if exists:
                raise wtforms.validators.ValidationError(
                    _('A type with a similar name already exists'))

    class AliquotTypeCrudForm(wtforms.Form):

        types = wtforms.FieldList(wtforms.FormField(AliquotTypeForm))

    class LabForm(wtforms.Form):
        ui_selected = wtforms.BooleanField()

        id = wtforms.HiddenField()

        name = wtforms.StringField(label=_(u'Name'),
                                   description=_(u'This is the system name'),
                                   validators=[wtforms.validators.Required()])
        title = wtforms.StringField(
            label=_(u'Title'),
            description=_(u'This is the human readable title'),
            validators=[wtforms.validators.Required()])
        active = wtforms.BooleanField(description=_(
            u'Actives labs will be available in new location dropdowns'),
                                      label=_(u'Active'))
        is_enabled = wtforms.BooleanField(
            description=_(u'Enabled labs will be available on Lims homepage'),
            label=_(u'Enabled'))

    class LabsTypeCrudForm(wtforms.Form):

        types = wtforms.FieldList(wtforms.FormField(LabForm))

    # We need to accomodate WTForm's inability to process multiple forms
    # in the same page by adding a hidden value to check which form
    # was submitted

    lab_type_crud_form = LabsTypeCrudForm(
        request.POST if 'lab-type-crud-form' in request.POST else None,
        types=labs_types,
    )

    lab_add_form = LabForm(request.POST if 'lab-add-form' in
                           request.POST else None)

    del lab_add_form.id
    del lab_add_form.ui_selected

    specimen_type_add_form = SpecimenTypeForm(
        request.POST if 'specimen-type-add-form' in request.POST else None, )

    del specimen_type_add_form.id
    del specimen_type_add_form.ui_selected

    specimen_type_crud_form = SpecimenTypeCrudForm(
        request.POST if 'specimen-type-crud-form' in request.POST else None,
        types=specimen_types,
    )

    aliquot_type_add_form = AliquotTypeForm(
        request.POST if 'aliquot-type-add-form' in request.POST else None)

    del aliquot_type_add_form.id
    del aliquot_type_add_form.ui_selected

    aliquot_type_crud_form = AliquotTypeCrudForm(
        request.POST if 'aliquot-type-crud-form' in request.POST else None,
        types=aliquot_types,
    )

    if 'specimen-type-add-form' in request.POST:
        if specimen_type_add_form.validate():
            data = specimen_type_add_form.data
            data['name'] = slugify(data['title'])
            db_session.add(models.SpecimenType(**data))
            request.session.flash(_(u'Sucessfully added specimen type'),
                                  'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(_(u'Form errors, please revise below'),
                                  'danger')

    elif 'specimen-type-crud-form' in request.POST and 'save' in request.POST:
        if specimen_type_crud_form.validate():
            for i, entry in enumerate(specimen_type_crud_form.types.entries):
                del entry.form.id
                apply_changes(entry.form, specimen_types[i])
            db_session.flush()
            request.session.flash(_(u'Sucessfully updated specimen types'),
                                  'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(_(u'Form errors, please revise below'),
                                  'danger')

    elif 'specimen-type-crud-form' in request.POST \
            and 'delete' in request.POST:
        ids = [
            e.form.id.object_data
            for e in specimen_type_crud_form.types.entries
            if e.form.ui_selected.data
        ]
        if not ids:
            request.session.flash(_(u'No specimen types selected'), 'warning')

        (exists, ) = (db_session.query(
            db_session.query(models.Specimen).filter(
                models.Specimen.specimen_type_id.in_(ids)).exists()).one())

        if not exists:
            count = (db_session.query(models.SpecimenType).filter(
                models.SpecimenType.id.in_(ids)).delete(
                    synchronize_session=False))
            db_session.flush()
            request.session.flash(
                _(u'Deleted {0} specimen types'.format(count)), 'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(
                _(u'Selected types already have specimen collected'), 'danger')

    elif 'aliquot-type-add-form' in request.POST:
        if aliquot_type_add_form.validate():
            data = aliquot_type_add_form.data
            data['name'] = slugify(data['title'])
            db_session.add(models.AliquotType(**data))
            request.session.flash(_(u'Sucessfully added aliquot type'),
                                  'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(_(u'Form errors, please revise below'),
                                  'danger')

    elif 'aliquot-type-crud-form' in request.POST and 'save' in request.POST:
        if aliquot_type_crud_form.validate():
            for i, entry in enumerate(aliquot_type_crud_form.types.entries):
                del entry.form.id
                apply_changes(entry.form, aliquot_types[i])
            db_session.flush()
            request.session.flash(_(u'Sucessfully updated aliquot types'),
                                  'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(_(u'Form errors, please revise below'),
                                  'danger')

    elif 'aliquot-type-crud-form' in request.POST and 'delete' in request.POST:
        ids = [
            e.form.id.object_data for e in aliquot_type_crud_form.types.entries
            if e.form.ui_selected.data
        ]
        if not ids:
            request.session.flash(_(u'No aliquot types selected'), 'warning')

        (exists, ) = (db_session.query(
            db_session.query(models.Aliquot).filter(
                models.Aliquot.aliquot_type_id.in_(ids)).exists()).one())

        if not exists:
            count = (db_session.query(models.AliquotType).filter(
                models.AliquotType.id.in_(ids)).delete(
                    synchronize_session=False))
            request.session.flash(
                _(u'Deleted {0} aliquot types'.format(count)), 'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(
                _(u'Selected types already have aliquot collected'), 'danger')

    elif 'lab-add-form' in request.POST:
        if lab_add_form.validate():
            db_session.add(models.Location(**lab_add_form.data))
            db_session.flush()

            request.session.flash(
                _(u'Sucessfully added lab: {}'.format(
                    lab_add_form.data['title'])), 'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(_(u'Form errors, please revise below'),
                                  'danger')

    elif 'lab-type-crud-form' in request.POST and 'save' in request.POST:
        if lab_type_crud_form.validate():
            for i, entry in enumerate(lab_type_crud_form.types.entries):
                del entry.form.id
                apply_changes(entry.form, labs_types[i])
            db_session.flush()
            request.session.flash(_(u'Sucessfully updated labs'), 'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(_(u'Form errors, please revise below'),
                                  'danger')

    elif 'lab-type-crud-form' in request.POST and 'delete' in request.POST:
        ids = [
            e.form.id.object_data for e in lab_type_crud_form.types.entries
            if e.form.ui_selected.data
        ]

        titles = [
            e.data['title'] for e in lab_type_crud_form.types.entries
            if e.form.ui_selected.data
        ]

        if not ids:
            request.session.flash(_(u'No labs selected'), 'warning')

        (exists, ) = (db_session.query(
            db_session.query(models.Location).filter(
                models.Location.id.in_(ids)).exists()).one())

        if exists:
            count = (db_session.query(models.Location).filter(
                models.Location.id.in_(ids)).delete(synchronize_session=False))
            db_session.flush()

            request.session.flash(
                _(u'Sucessfully deleted labs:  {}'.format(', '.join(titles))),
                'success')

            return HTTPFound(location=request.current_route_path())

    query = (db_session.query(models.Location).order_by(models.Location.title))

    return {
        'specimen_types': specimen_types,
        'specimen_types_count': specimen_types_count,
        'specimen_type_add_form': specimen_type_add_form,
        'specimen_type_crud_form': specimen_type_crud_form,
        'aliquot_types': aliquot_types,
        'aliquot_types_count': aliquot_types_count,
        'aliquot_type_add_form': aliquot_type_add_form,
        'aliquot_type_crud_form': aliquot_type_crud_form,
        'labs_types': labs_types,
        'lab_type_crud_form': lab_type_crud_form,
        'lab_add_form': lab_add_form,
        'labs': query
    }
コード例 #10
0
ファイル: settings.py プロジェクト: davidmote/occams_lims
def settings(context, request):
    """
    Manages application-wide settings
    """

    if request.method == 'POST':
        check_csrf_token(request)

    db_session = request.db_session

    specimen_types = (
        db_session.query(models.SpecimenType)
        .order_by(models.SpecimenType.title)
        .all())

    specimen_types_count = len(specimen_types)

    aliquot_types = (
        db_session.query(models.AliquotType)
        .options(orm.joinedload('specimen_type'))
        .join(models.AliquotType.specimen_type)
        .order_by(
            models.SpecimenType.title,
            models.AliquotType.title)
        .all())

    aliquot_types_count = len(specimen_types)

    labs_types = (
        db_session.query(models.Location)
        .order_by(models.Location.title)
        .all())

    class SpecimenTypeForm(wtforms.Form):

        ui_selected = wtforms.BooleanField()

        id = wtforms.HiddenField()

        title = wtforms.StringField(
            label=_(u'Title'),
            description=_(u'The displayed label'),
            validators=[
                wtforms.validators.input_required(),
            ])

        description = wtforms.TextAreaField(
            label=_(u'Description'),
            validators=[wtforms.validators.optional()])

        tube_type = wtforms.StringField(
            label=_(u'Tube Type'),
            validators=[wtforms.validators.optional()])

        default_tubes = wtforms.IntegerField(
            label=_(u'Default Amount'),
            description=_(
                u'Default amount to use by default when '
                u'a new specimen'),
            validators=[wtforms.validators.optional()])

        def validate_title(self, field):
            query = (
                db_session.query(models.SpecimenType)
                .filter_by(name=slugify(field.data)))

            # apparently the removed field remains as None...
            if self.id and self.id.data:
                query = query.filter(models.SpecimenType.id != self.id.data)

            (exists,) = db_session.query(query.exists()).one()

            if exists:
                raise wtforms.validators.ValidationError(_(
                    'A type with a similar name already exists'))

    class SpecimenTypeCrudForm(wtforms.Form):

        types = wtforms.FieldList(wtforms.FormField(SpecimenTypeForm))

    class AliquotTypeForm(wtforms.Form):

        ui_selected = wtforms.BooleanField()

        id = wtforms.HiddenField()

        specimen_type_id = wtforms.SelectField(
            label=_(u'Specimen Type'),
            description=_(
                u'The specimen type this sample type can processed from'),
            choices=[(t.id, t.title) for t in specimen_types],
            coerce=int,
            validators=[
                wtforms.validators.input_required()
            ])

        title = wtforms.StringField(
            label=_(u'Title'),
            validators=[
                wtforms.validators.input_required(),
            ])

        description = wtforms.TextAreaField(
            label=_(u'Description'),
            validators=[wtforms.validators.optional()])

        units = wtforms.StringField(
            label=_(u'Measuring Units'),
            description=_(u'The unit of measurement per-sample of this type'),
            validators=[wtforms.validators.input_required()])

        def validate_title(self, field):
            query = (
                db_session.query(models.AliquotType)
                .filter_by(name=slugify(field.data)))

            # apparently the removed field remains as None...
            if self.id and self.id.data:
                query = query.filter(models.AliquotType.id != self.id.data)

            (exists,) = db_session.query(query.exists()).one()

            if exists:
                raise wtforms.validators.ValidationError(_(
                    'A type with a similar name already exists'))

    class AliquotTypeCrudForm(wtforms.Form):

        types = wtforms.FieldList(wtforms.FormField(AliquotTypeForm))

    class LabForm(wtforms.Form):
        ui_selected = wtforms.BooleanField()

        id = wtforms.HiddenField()

        name = wtforms.StringField(
            label=_(u'Name'),
            description=_(
                u'This is the system name'),
            validators=[wtforms.validators.Required()])
        title = wtforms.StringField(
            label=_(u'Title'),
            description=_(
                u'This is the human readable title'),
            validators=[wtforms.validators.Required()])
        active = wtforms.BooleanField(
            description=_(
                u'Actives labs will be available in new location dropdowns'),
            label=_(u'Active'))
        is_enabled = wtforms.BooleanField(
            description=_(
                u'Enabled labs will be available on Lims homepage'),
            label=_(u'Enabled'))

    class LabsTypeCrudForm(wtforms.Form):

        types = wtforms.FieldList(wtforms.FormField(LabForm))

    # We need to accomodate WTForm's inability to process multiple forms
    # in the same page by adding a hidden value to check which form
    # was submitted

    lab_type_crud_form = LabsTypeCrudForm(
        request.POST if 'lab-type-crud-form' in request.POST else None,
        types=labs_types,
    )

    lab_add_form = LabForm(
        request.POST if 'lab-add-form' in request.POST else None)

    del lab_add_form.id
    del lab_add_form.ui_selected

    specimen_type_add_form = SpecimenTypeForm(
        request.POST if 'specimen-type-add-form' in request.POST else None,
    )

    del specimen_type_add_form.id
    del specimen_type_add_form.ui_selected

    specimen_type_crud_form = SpecimenTypeCrudForm(
        request.POST if 'specimen-type-crud-form' in request.POST else None,
        types=specimen_types,
    )

    aliquot_type_add_form = AliquotTypeForm(
        request.POST if 'aliquot-type-add-form' in request.POST else None
    )

    del aliquot_type_add_form.id
    del aliquot_type_add_form.ui_selected

    aliquot_type_crud_form = AliquotTypeCrudForm(
        request.POST if 'aliquot-type-crud-form' in request.POST else None,
        types=aliquot_types,
    )

    if 'specimen-type-add-form' in request.POST:
        if specimen_type_add_form.validate():
            data = specimen_type_add_form.data
            data['name'] = slugify(data['title'])
            db_session.add(models.SpecimenType(**data))
            request.session.flash(
                _(u'Sucessfully added specimen type'), 'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(
                _(u'Form errors, please revise below'), 'danger')

    elif 'specimen-type-crud-form' in request.POST and 'save' in request.POST:
        if specimen_type_crud_form.validate():
            for i, entry in enumerate(specimen_type_crud_form.types.entries):
                del entry.form.id
                apply_changes(entry.form, specimen_types[i])
            db_session.flush()
            request.session.flash(
                _(u'Sucessfully updated specimen types'), 'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(
                _(u'Form errors, please revise below'), 'danger')

    elif 'specimen-type-crud-form' in request.POST \
            and 'delete' in request.POST:
        ids = [
            e.form.id.object_data
            for e in specimen_type_crud_form.types.entries
            if e.form.ui_selected.data]
        if not ids:
            request.session.flash(_(u'No specimen types selected'), 'warning')

        (exists,) = (
            db_session.query(
                db_session.query(models.Specimen)
                .filter(models.Specimen.specimen_type_id.in_(ids))
                .exists())
            .one())

        if not exists:
            count = (
                db_session.query(models.SpecimenType)
                .filter(models.SpecimenType.id.in_(ids))
                .delete(synchronize_session=False))
            db_session.flush()
            request.session.flash(
                _(u'Deleted {0} specimen types'.format(count)), 'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(
                _(u'Selected types already have specimen collected'),
                'danger')

    elif 'aliquot-type-add-form' in request.POST:
        if aliquot_type_add_form.validate():
            data = aliquot_type_add_form.data
            data['name'] = slugify(data['title'])
            db_session.add(models.AliquotType(**data))
            request.session.flash(
                _(u'Sucessfully added aliquot type'), 'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(
                _(u'Form errors, please revise below'), 'danger')

    elif 'aliquot-type-crud-form' in request.POST and 'save' in request.POST:
        if aliquot_type_crud_form.validate():
            for i, entry in enumerate(aliquot_type_crud_form.types.entries):
                del entry.form.id
                apply_changes(entry.form, aliquot_types[i])
            db_session.flush()
            request.session.flash(
                _(u'Sucessfully updated aliquot types'), 'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(
                _(u'Form errors, please revise below'), 'danger')

    elif 'aliquot-type-crud-form' in request.POST and 'delete' in request.POST:
        ids = [
            e.form.id.object_data
            for e in aliquot_type_crud_form.types.entries
            if e.form.ui_selected.data]
        if not ids:
            request.session.flash(_(u'No aliquot types selected'), 'warning')

        (exists,) = (
            db_session.query(
                db_session.query(models.Aliquot)
                .filter(models.Aliquot.aliquot_type_id.in_(ids))
                .exists())
            .one())

        if not exists:
            count = (
                db_session.query(models.AliquotType)
                .filter(models.AliquotType.id.in_(ids))
                .delete(synchronize_session=False))
            request.session.flash(
                _(u'Deleted {0} aliquot types'.format(count)), 'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(
                _(u'Selected types already have aliquot collected'),
                'danger')

    elif 'lab-add-form' in request.POST:
        if lab_add_form.validate():
            db_session.add(models.Location(**lab_add_form.data))
            db_session.flush()

            request.session.flash(
                _(u'Sucessfully added lab: {}'.format(
                    lab_add_form.data['title'])), 'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(
                _(u'Form errors, please revise below'), 'danger')

    elif 'lab-type-crud-form' in request.POST and 'save' in request.POST:
        if lab_type_crud_form.validate():
            for i, entry in enumerate(lab_type_crud_form.types.entries):
                del entry.form.id
                apply_changes(entry.form, labs_types[i])
            db_session.flush()
            request.session.flash(
                _(u'Sucessfully updated labs'), 'success')
            return HTTPFound(location=request.current_route_path())
        else:
            request.session.flash(
                _(u'Form errors, please revise below'), 'danger')

    elif 'lab-type-crud-form' in request.POST and 'delete' in request.POST:
        ids = [
            e.form.id.object_data
            for e in lab_type_crud_form.types.entries
            if e.form.ui_selected.data]

        titles = [
            e.data['title']
            for e in lab_type_crud_form.types.entries
            if e.form.ui_selected.data]

        if not ids:
            request.session.flash(_(u'No labs selected'), 'warning')

        (exists,) = (
            db_session.query(
                db_session.query(models.Location)
                .filter(models.Location.id.in_(ids))
                .exists())
            .one())

        if exists:
            count = (
                db_session.query(models.Location)
                .filter(models.Location.id.in_(ids))
                .delete(synchronize_session=False))
            db_session.flush()

            request.session.flash(
                _(u'Sucessfully deleted labs:  {}'.format(
                    ', '.join(titles))), 'success')

            return HTTPFound(location=request.current_route_path())

    query = (
        db_session.query(models.Location)
        .order_by(models.Location.title))

    return {
        'specimen_types': specimen_types,
        'specimen_types_count': specimen_types_count,
        'specimen_type_add_form': specimen_type_add_form,
        'specimen_type_crud_form': specimen_type_crud_form,

        'aliquot_types': aliquot_types,
        'aliquot_types_count': aliquot_types_count,
        'aliquot_type_add_form': aliquot_type_add_form,
        'aliquot_type_crud_form': aliquot_type_crud_form,

        'labs_types': labs_types,
        'lab_type_crud_form': lab_type_crud_form,
        'lab_add_form': lab_add_form,

        'labs': query
    }
コード例 #11
0
ファイル: specimen.py プロジェクト: mstroehle/occams_lims
def specimen(context, request):
    db_session = request.db_session

    vals = filter_specimen(context, request, state=u'pending-draw')
    specimen = vals['specimen']

    # Override specimen with default processing locations on save
    # This was previosly set in the Plone site content object
    # but don't have the resources to properly re-implement this
    # functionality, so this will have to do for now.
    processing_location_name = None
    processing_location = None

    if 'aeh' in db_session.bind.url.database:
        processing_location_name = {
            'richman lab': 'richman lab',
            'avrc': 'richman lab'
        }.get(context.name)
    elif 'cctg' in db_session.bind.url.database:
        processing_location_name = {
            'harbor-ucla-clinic': 'harbor-ucla-clinic',
            'long-beach-clinic': 'long-beach-lab',
            'long-beach-lab': 'long-beach-lab',
            'usc-clinic': 'usc-lab',
            'usc-lab': 'usc-lab',
            'avrc': 'avrc',
        }.get(context.name)
    elif 'mhealth' in db_session.bind.url.database:
        processing_location_name = {
            'avrc': 'avrc',
        }.get(context.name)
    else:
        processing_location_name = None

    if processing_location_name:
        processing_location = (
            db_session.query(models.Location)
            .filter_by(name=processing_location_name)
            .one())

    overriden_specimen = [{
        'id': s.id,
        'tubes': s.tubes,
        'collect_date': s.collect_date,
        'collect_time': s.collect_time,
        'location_id': processing_location and processing_location.id,
        'notes': s.notes
    } for s in specimen if s]

    Form = build_crud_form(context, request)
    form = Form(request.POST, specimen=overriden_specimen)

    label_queue = request.session.setdefault(SPECIMEN_LABEL_QUEUE, set())

    if (request.method == 'POST' and
            check_csrf_token(request) and
            form.validate()):

        if not request.has_permission('process'):
            raise HTTPForbidden

        if 'save' in request.POST:
            updated_count = 0
            for i, subform in enumerate(form.specimen.entries):
                if apply_changes(subform.form, specimen[i]):
                    updated_count += 1
            db_session.flush()
            if updated_count:
                request.session.flash(u'Changes saved', 'success')
            else:
                request.session.flash(u'No changes were saved', 'warning')
            return HTTPFound(location=request.current_route_path())

        if 'queue' in request.POST:
            queue_count = 0
            for i, subform in enumerate(form.specimen.entries):
                apply_changes(subform.form, specimen[i])
                if subform.ui_selected.data:
                    queue_count += 1
                    specimen_id = subform['id'].data
                    if specimen_id in label_queue:
                        label_queue.discard(specimen_id)
                    else:
                        label_queue.add(specimen_id)
            request.session.changed()
            if queue_count:
                request.session.flash(
                    u'Specimen print queue has changed.', 'success')
            else:
                request.session.flash(u'Please select specimen', 'warning')
            return HTTPFound(location=request.current_route_path())

        for state_name in ('not-collected', 'pending-aliquot'):
            if state_name in request.POST:
                state = (
                    db_session.query(models.SpecimenState)
                    .filter_by(name=state_name)
                    .one())
                transitioned_count = 0
                updated_count = 0
                for i, subform in enumerate(form.specimen.entries):
                    if subform.ui_selected.data:
                        specimen[i].state = state
                        transitioned_count += 1
                    if apply_changes(subform.form, specimen[i]):
                        updated_count += 1
                db_session.flush()
                if transitioned_count:
                    request.session.flash(
                        u'%d Specimen have been changed to the status of %s.'
                        % (transitioned_count, state.title),
                        'success')
                else:
                    request.session.flash(u'Please select specimen', 'warning')
                return HTTPFound(location=request.current_route_path())

    vals.update({
        'form': form,
        'has_labels_queued': len(label_queue),
        'label_queue': label_queue,
    })

    return vals