Beispiel #1
0
 def _initFormParams(self):
     super(PatientsView, self)._initFormParams()
     if _b('Add') in self.context_actions:
         # We need to create the new element in the patients original url to avoid a creation error.
         self.context_actions[_b(
             'Add'
         )]['url'] = self.portal_url + '/patients/createObject?type_name=Patient'
 def _initFormParams(self):
     mtool = getToolByName(self.context, 'portal_membership')
     addPortalMessage = self.context.plone_utils.addPortalMessage
     if mtool.checkPermission(AddPatient, self.context):
         clients = self.context.clients.objectIds()
         if clients:
             self.context_actions[_b('Add')] = {
                 'url': 'createObject?type_name=Patient',
                 'icon': '++resource++bika.lims.images/add.png'
             }
         else:
             msg = _("Cannot create patients without any system clients configured.")
             addPortalMessage(self.context.translate(msg))
     if mtool.checkPermission(ViewPatients, self.context):
         self.review_states[0]['transitions'].append({'id':'deactivate'})
         self.review_states.append(
             {'id': 'inactive',
              'title': _b('Dormant'),
              'contentFilter': {'inactive_state': 'inactive'},
              'transitions': [{'id':'activate'}, ],
              'columns': ['getPatientID', 'getClientPatientID',
                          'Title', 'getGender', 'getAgeSplittedStr',
                          'getBirthDate', 'getCitizenship', 'getPrimaryReferrer']})
         self.review_states.append(
             {'id': 'all',
              'title': _b('All'),
              'contentFilter':{},
              'transitions':[{'id':'empty'}, ],
              'columns': ['Title', 'getPatientID', 'getClientPatientID',
                          'getGender', 'getAgeSplittedStr',
                          'getBirthDate', 'getCitizenship',
                          'getPrimaryReferrer']})
         stat = self.request.get("%s_review_state" % self.form_id, 'default')
         self.show_select_column = stat != 'all'
Beispiel #3
0
    def _initFormParams(self):
        mtool = getToolByName(self.context, 'portal_membership')
        addPortalMessage = self.context.plone_utils.addPortalMessage
        can_add_patients = mtool.checkPermission(AddPatient, self.context)

        if not can_add_patients and IClient.providedBy(self.context):
            # The user logged in is a Contact from this Client?
            # Tip: when a client contact is created, bika.lims assigns that
            # contact as the owner of the client, so he/she can access to the
            # Client he/she is owner of but not to the rest of Clients.
            # See bika.lims.browser.contact._link_user(userid)
            client = self.context
            owners = client.users_with_local_role('Owner')
            member = mtool.getAuthenticatedMember()
            can_add_patients = member.id in owners

        if can_add_patients:
            # TODO Performance tweak. Is this really needed?
            clients = self.context.clients.objectIds()
            if clients:
                add_patient_url = '{}/patients/createObject?type_name=Patient'\
                                  .format(self.portal_url)
                self.context_actions[_b('Add')] = {
                    'url': add_patient_url,
                    'icon': '++resource++bika.lims.images/add.png'
                }
            else:
                msg = _("Cannot create patients without any system clients "
                        "configured.")
                addPortalMessage(self.context.translate(msg))

        if mtool.checkPermission(ViewPatients, self.context):
            self.review_states[0]['transitions'].append({'id': 'deactivate'})
            self.review_states.append({
                'id': 'inactive',
                'title': _b('Dormant'),
                'contentFilter': {
                    'inactive_state': 'inactive'
                },
                'transitions': [
                    {
                        'id': 'activate'
                    },
                ],
                'columns': self.get_columns()
            })
            self.review_states.append({
                'id': 'all',
                'title': _b('All'),
                'contentFilter': {},
                'transitions': [
                    {
                        'id': 'empty'
                    },
                ],
                'columns': self.get_columns()
            })
            stat = self.request.get("%s_review_state" % self.form_id,
                                    'default')
            self.show_select_column = stat != 'all'
Beispiel #4
0
    def __init__(self, context, request):
        super(RegionsView, self).__init__(context, request)
        self.catalog = "bika_setup_catalog"
        self.contentFilter = {"portal_type": "Country", "sort_on": "sortable_title"}
        self.context_actions = {
            _("Add country"): {"url": "createObject?type_name=Country", "icon": "++resource++bika.lims.images/add.png"}
        }
        self.icon = self.portal_url + "/++resource++bika.wine.images/region.png"
        self.title = self.context.translate(_("Regions"))
        self.description = ""
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = True
        self.pagesize = 25

        self.columns = {"Title": {"title": _("Country"), "index": "sortable_title"}}

        self.review_states = [
            {
                "id": "default",
                "title": _b("Active"),
                "contentFilter": {"inactive_state": "active"},
                "transitions": [{"id": "deactivate"}],
                "columns": ["Title"],
            },
            {
                "id": "inactive",
                "title": _b("Inactive"),
                "contentFilter": {"inactive_state": "inactive"},
                "transitions": [{"id": "activate"}],
                "columns": ["Title"],
            },
            {"id": "all", "title": _b("All"), "contentFilter": {}, "columns": ["Title"]},
        ]
Beispiel #5
0
 def __init__(self, context, request):
     super(AnalysisRequestsView, self).__init__(context, request)
     self.columns['DataDeValidade'] = {'title': _b('Data de Validade')}
     self.columns['PrevisaoDeEntrega'] = {'title': _b('Previsao de Entrega')}
     
     for rs in self.review_states:
         i = rs['columns'].index('BatchID') + 1
         rs['columns'].insert(i, 'DataDeValidade')
         rs['columns'].insert(i, 'PrevisaoDeEntrega')
Beispiel #6
0
 def _initFormParams(self):
     mtool = getToolByName(self.context, "portal_membership")
     addPortalMessage = self.context.plone_utils.addPortalMessage
     if mtool.checkPermission(AddPatient, self.context):
         clients = self.context.clients.objectIds()
         if clients:
             self.context_actions[_b("Add")] = {
                 "url": "createObject?type_name=Patient",
                 "icon": "++resource++bika.lims.images/add.png",
             }
         else:
             msg = _("Cannot create patients without any system clients configured.")
             addPortalMessage(self.context.translate(msg))
     if mtool.checkPermission(ViewPatients, self.context):
         self.review_states[0]["transitions"].append({"id": "deactivate"})
         self.review_states.append(
             {
                 "id": "inactive",
                 "title": _b("Dormant"),
                 "contentFilter": {"inactive_state": "inactive"},
                 "transitions": [{"id": "activate"}],
                 "columns": [
                     "getPatientID",
                     "getClientPatientID",
                     "Title",
                     "getGender",
                     "getAgeSplittedStr",
                     "getBirthDate",
                     "getCitizenship",
                     "getPrimaryReferrer",
                 ],
             }
         )
         self.review_states.append(
             {
                 "id": "all",
                 "title": _b("All"),
                 "contentFilter": {},
                 "transitions": [{"id": "empty"}],
                 "columns": [
                     "Title",
                     "getPatientID",
                     "getClientPatientID",
                     "getGender",
                     "getAgeSplittedStr",
                     "getBirthDate",
                     "getCitizenship",
                     "getPrimaryReferrer",
                 ],
             }
         )
         stat = self.request.get("%s_review_state" % self.form_id, "default")
         self.show_select_column = stat != "all"
Beispiel #7
0
    def __call__(self):
        form = self.request.form
        plone.protect.CheckAuthenticator(form)
        action, came_from = WorkflowAction._get_form_workflow_action(self)

        if action == 'submit':

            objects = WorkflowAction._get_selected_items(self)
            if not objects:
                message = self.context.translate(
                    _b("No analyses have been selected"))
                self.context.plone_utils.addPortalMessage(message, 'info')
                self.destination_url = self.context.absolute_url() + \
                    "/batchbook"
                self.request.response.redirect(self.destination_url)
                return

            for ar_uid, ar in objects.items():
                for analysis in ar.getAnalyses(full_objects=True):
                    kw = analysis.getKeyword()
                    values = form.get(kw)
                    analysis.setResult(values[0][ar_uid])
                    if values[0][ar_uid]:
                        doActionFor(analysis, 'submit')

            message = self.context.translate(_p("Changes saved."))
            self.context.plone_utils.addPortalMessage(message, 'info')
            self.request.response.redirect(self.request.get('URL'))
            return

        else:

            WorkflowAction.__call__(self)
    def __init__(self, context, request):
        super(ContactsView, self).__init__(context, request)
        self.catalog = "portal_catalog"
        self.contentFilter = {
            'portal_type': 'VaccinationCenterContact',
            'sort_on':'sortable_title',
            'path': {
                "query": "/".join(context.getPhysicalPath()),
                "level" : 0
            }
        }
        self.context_actions = {_('Add'):
            {'url': 'createObject?type_name=VaccinationCenterContact',
             'icon': '++resource++bika.lims.images/add.png'}
        }
        self.show_table_only = False
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = True
        self.pagesize = 50
        self.icon = self.portal_url + "/++resource++bika.health.images/vaccinationcenter_contact_big.png"
        self.title = _b("Contacts")

        self.columns = {
            'getFullname': {'title': _('Full Name')},
            'getEmailAddress': {'title': _('Email Address')},
            'getBusinessPhone': {'title': _('Business Phone')},
            'getMobilePhone': {'title': _('Mobile Phone')},
            'getFax': {'title': _('Fax')},
        }

        self.review_states = [
            {'id':'default',
             'title': _('Active'),
             'contentFilter': {'inactive_state': 'active'},
             'transitions': [{'id':'deactivate'}, ],
             'columns': ['getFullname',
                         'getEmailAddress',
                         'getBusinessPhone',
                         'getMobilePhone',
                         'getFax']},
            {'id':'inactive',
             'title': _('Dormant'),
             'contentFilter': {'inactive_state': 'inactive'},
             'transitions': [{'id':'activate'}, ],
             'columns': ['getFullname',
                         'getEmailAddress',
                         'getBusinessPhone',
                         'getMobilePhone',
                         'getFax']},
            {'id':'all',
             'title': _('All'),
             'contentFilter':{},
             'columns': ['getFullname',
                         'getEmailAddress',
                         'getBusinessPhone',
                         'getMobilePhone',
                         'getFax']},
        ]
Beispiel #9
0
    def __init__(self, context, request):
        super(CountryRegionsView, self).__init__(context, request)
        self.catalog = 'bika_setup_catalog'
        path = "/".join(self.context.getPhysicalPath())
        self.contentFilter = {'portal_type': 'Region',
                              'sort_on': 'sortable_title',
                              'path': {'query': path, 'level': 0}
                              }
        self.context_actions = {
            _('Add Region'): {
                'url': 'createObject?type_name=Region',
                'icon': '++resource++bika.lims.images/add.png'
            }
        }
        self.icon = self.portal_url + \
            "/++resource++bika.wine.images/region.png"
        self.title = self.context.Title()
        self.description = ""
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = True
        self.pagesize = 25

        self.columns = {
            'Title': {'title': _('Region'),
                      'index': 'sortable_title'},
        }

        self.review_states = [
            {'id': 'default',
             'title': _b('Active'),
             'contentFilter': {'inactive_state': 'active'},
             'transitions': [{'id': 'deactivate'}, ],
             'columns': ['Title']},
            {'id': 'inactive',
             'title': _b('Inactive'),
             'contentFilter': {'inactive_state': 'inactive'},
             'transitions': [{'id': 'activate'}, ],
             'columns': ['Title']},
            {'id': 'all',
             'title': _b('All'),
             'contentFilter': {},
             'columns': ['Title']},
        ]

        return super(CountryRegionsView, self).__init__(context, request)
Beispiel #10
0
    def __init__(self, context, request):
        super(PatientsView, self).__init__(context, request)

        self.catalog = 'bika_patient_catalog'

        self.contentFilter = {'portal_type': 'Patient',
                              'sort_on': 'sortable_title'}
        self.context_actions = {}
        self.title = self.context.translate(_("Patients"))
        self.icon = self.portal_url + "/++resource++bika.health.images/patient_big.png"
        self.description = ""
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = False
        self.pagesize = 25

        self.columns = {

            'Title': {'title': _('Patient'),
                      'index': 'sortable_title'},

            'getPatientID': {'title': _('Patient ID'),
                             'index': 'getPatientID'},

            'getClientPatientID': {'title': _('Client PID'),
                            'index': 'getClientPatientID'},

            'getGender': {'title': _('Gender'),
                          'index': 'getGender',
                          'toggle': True},

            'getAgeSplittedStr': {'title': _('Age'),
                                  'index': 'getAgeSplittedStr',
                                  'toggle': True},

            'getBirthDate': {'title': _('BirthDate'),
                             'index': 'getBirthDate',
                             'toggle': True},

            'getCitizenship': {'title': _('Citizenship'),
                               'index': 'getCitizenship',
                               'toggle': True},

            'getPrimaryReferrer': {'title': _('Primary Referrer'),
                                   'index': 'getPrimaryReferrerTitle',
                                   'toggle': True},

        }

        self.review_states = [
            {'id': 'default',
             'title': _b('Active'),
             'contentFilter': {'inactive_state': 'active'},
             'transitions': [],
             'columns': ['getPatientID', 'getClientPatientID',
                         'Title', 'getGender', 'getAgeSplittedStr',
                         'getBirthDate', 'getCitizenship', 'getPrimaryReferrer']},
        ]
Beispiel #11
0
    def __init__(self, context, request):
        super(CultivarsView, self).__init__(context, request)
        self.catalog = 'bika_setup_catalog'
        self.contentFilter = {'portal_type': 'Cultivar',
                              'sort_on': 'sortable_title'}
        self.context_actions = {
            _b('Add'): {
                'url': 'createObject?type_name=Cultivar',
                'icon': '++resource++bika.lims.images/add.png'
            }
        }
        self.icon = self.portal_url + \
            "/++resource++bika.wine.images/winetype_big.png"
        self.title = self.context.translate(_("Cultivars"))
        self.description = ""
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = True
        self.pagesize = 25

        self.columns = {
            'Title': {'title': _('Cultivar'),
                      'index': 'sortable_title'},
            'Description': {'title': _b('Description'),
                            'index': 'description',
                            'toggle': True},
        }

        self.review_states = [
            {'id': 'default',
             'title': _b('Active'),
             'contentFilter': {'inactive_state': 'active'},
             'transitions': [{'id': 'deactivate'}, ],
             'columns': ['Title', 'Description']},
            {'id': 'inactive',
             'title': _b('Inactive'),
             'contentFilter': {'inactive_state': 'inactive'},
             'transitions': [{'id': 'activate'}, ],
             'columns': ['Title', 'Description']},
            {'id': 'all',
             'title': _b('All'),
             'contentFilter': {},
             'columns': ['Title', 'Description']},
        ]
Beispiel #12
0
    def __init__(self, context, request):
        super(BatchFolderContentsView, self).__init__(context, request)

        self.columns = {
            'BatchID': {'title': _('Batch ID')},
            'Title': {'title': _b('Title')},
            'WorksOrderID': {'title': _('Works Order ID')},
            'BlendNumber': {'title': _('Blend Name')},
            'Description': {'title': _b('Description')},
            'state_title': {'title': _b('State'), 'sortable': False},
        }

        self.review_states = [  # leave these titles and ids alone
            {'id': 'default',
             'title': _b('All'),
             'contentFilter': {},
             'columns': ['BatchID',
                         'Title',
                         'BlendNumber',
                         'WorksOrderID',
                         'Description',
                         'state_title', ]
             },
            {'id': 'open',  # in bika.lims, this is 'default'.
             'contentFilter': {'cancellation_state': 'active',
                               'review_state': ['open',
                                                'received',
                                                'to_be_verified',
                                                'verified']},
             'title': _b('Open'),
             'columns': ['BatchID',
                         'Title',
                         'BlendNumber',
                         'WorksOrderID',
                         'Description',
                         'state_title', ]
             },
            {'id': 'closed',
             'contentFilter': {'review_state': 'closed'},
             'title': _b('Closed'),
             'columns': ['BatchID',
                         'Title',
                         'BlendNumber',
                         'WorksOrderID',
                         'Description',
                         'state_title', ]
             },
            {'id': 'cancelled',
             'title': _b('Cancelled'),
             'contentFilter': {'cancellation_state': 'cancelled'},
             'columns': ['BatchID',
                         'Title',
                         'BlendNumber',
                         'WorksOrderID',
                         'Description',
                         'state_title', ]
             },
        ]
Beispiel #13
0
 def __call__(self):
     mtool = getToolByName(self.context, 'portal_membership')
     # New Patient: Use this space to equip the add form with client UID
     if mtool.checkPermission(AddPatient, self.context):
         clients = self.context.clients.objectIds()
         if clients:
             self.context_actions[_b('Add')] = {
                 'url': 'createObject?type_name=Patient',
                 'icon': '++resource++bika.lims.images/add.png'
             }
Beispiel #14
0
    def validate_service(self, request, uid):
        """Validates the specs values from request for the service uid. Returns
        a non-translated message if the validation failed.
        """
        logger.info("Validating......")
        message = BaseValidator.validate_service(self, request, uid)
        if message:
            # Somehow, failed a validation for one or more of the default
            # range fields (min, max, error, warn_min, warn_max)
            return message

        spec_min = get_record_value(request, uid, "min")
        spec_max = get_record_value(request, uid, "max")
        min_panic = get_record_value(request, uid, "minpanic")
        max_panic = get_record_value(request, uid, "maxpanic")

        # minpanic must be below min and below maxpanic
        if not min_panic and not max_panic:
            # Neither min_panic nor max_panic values are set, dismiss
            return None

        if min_panic:
            if not api.is_floatable(min_panic):
                return _b("'{}' value must be numeric or empty").format(
                    _("Min panic"))
            if api.to_float(min_panic) > api.to_float(spec_min):
                return _b("'{}' value must be below '{}").format(
                    _("Min panic"), _("Min"))

        if max_panic:
            if not api.is_floatable(min_panic):
                return _b("'{}' value must be numeric or empty").format(
                    _("Max panic"))
            if api.to_float(min_panic) > api.to_float(spec_max):
                return _b("'{}' value must be above '{}").format(
                    _("Max panic"), _("Max"))

        return None
Beispiel #15
0
    def __init__(self, context, request):
        super(PatientsView, self).__init__(context, request)

        self.catalog = "bika_patient_catalog"

        self.contentFilter = {"portal_type": "Patient", "sort_on": "sortable_title"}
        self.context_actions = {}
        self.title = self.context.translate(_("Patients"))
        self.icon = self.portal_url + "/++resource++bika.health.images/patient_big.png"
        self.description = ""
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = False
        self.pagesize = 25

        self.columns = {
            "Title": {"title": _("Patient"), "index": "sortable_title"},
            "getPatientID": {"title": _("Patient ID"), "index": "getPatientID"},
            "getClientPatientID": {"title": _("Client PID"), "index": "getClientPatientID"},
            "getGender": {"title": _("Gender"), "index": "getGender", "toggle": True},
            "getAgeSplittedStr": {"title": _("Age"), "index": "getAgeSplittedStr", "toggle": True},
            "getBirthDate": {"title": _("BirthDate"), "index": "getBirthDate", "toggle": True},
            "getCitizenship": {"title": _("Citizenship"), "index": "getCitizenship", "toggle": True},
            "getPrimaryReferrer": {"title": _("Primary Referrer"), "index": "getPrimaryReferrerTitle", "toggle": True},
        }

        self.review_states = [
            {
                "id": "default",
                "title": _b("Active"),
                "contentFilter": {"inactive_state": "active"},
                "transitions": [],
                "columns": [
                    "getPatientID",
                    "getClientPatientID",
                    "Title",
                    "getGender",
                    "getAgeSplittedStr",
                    "getBirthDate",
                    "getCitizenship",
                    "getPrimaryReferrer",
                ],
            }
        ]
Beispiel #16
0
class BatchSchemaExtender(object):
    adapts(IBatch)
    implements(IOrderableSchemaExtender)

    fields = [
        # ExtComputedField('ClientID',
        #     expression="context.Schema()['Client'].get(context) and context.Schema()['Client'].get(context).ID() or None",
        # ),
        # ExtComputedField('ClientUID',
        #     expression="context.Schema()['Client'].get(context) and context.Schema()['Client'].get(context).UID() or None",
        # ),
        # ExtComputedField('ClientTitle',
        #     expression="context.Schema()['Client'].get(context) and context.Schema()['Client'].get(context).Title() or None",
        # ),
        ExtReferenceField(
            'Doctor',
            required=1,
            multiValued=0,
            allowed_types=('Doctor', ),
            referenceClass=HoldingReference,
            relationship='BatchDoctor',
            widget=ReferenceWidget(
                label=_("Doctor"),
                description="",
                render_own_label=False,
                visible={
                    'edit': 'visible',
                    'view': 'visible'
                },
                base_query={'inactive_state': 'active'},
                catalog_name='portal_catalog',
                showOn=True,
                colModel=[
                    {
                        'columnName': 'DoctorID',
                        'width': '20',
                        'label': _('Doctor ID')
                    },
                    {
                        'columnName': 'Title',
                        'width': '80',
                        'label': _('Full Name')
                    },
                ],
                add_button={
                    'visible': True,
                    'url': 'doctors/portal_factory/Doctor/new/edit',
                    'return_fields': ['Firstname', 'Surname'],
                    'js_controllers': [
                        '#doctor-base-edit',
                    ],
                    'overlay_handler': 'HealthDoctorOverlayHandler',
                },
                edit_button={
                    'visible': True,
                    # url with the root to create/edit a object.
                    'url': 'doctors/portal_factory/Doctor',
                    'return_fields': ['Firstname', 'Surname'],
                    'js_controllers': [
                        '#doctor-base-edit',
                    ],
                    'overlay_handler': 'HealthDoctorOverlayHandler',
                }),
        ),
        # ExtComputedField('DoctorID',
        #     expression="context.Schema()['Doctor'].get(context) and context.Schema()['Doctor'].get(context).ID() or None",
        # ),
        # ExtComputedField('DoctorUID',
        #     expression="context.Schema()['Doctor'].get(context) and context.Schema()['Doctor'].get(context).UID() or None",
        # ),
        # ExtComputedField('DoctorTitle',
        #     expression="context.Schema()['Doctor'].get(context) and context.Schema()['Doctor'].get(context).Title() or None",
        # ),
        ExtReferenceField(
            'Patient',
            required=1,
            multiValued=0,
            allowed_types=('Patient', ),
            referenceClass=HoldingReference,
            relationship='BatchPatient',
            widget=ReferenceWidget(
                label=_("Patient"),
                description="",
                render_own_label=False,
                visible={
                    'edit': 'visible',
                    'view': 'visible'
                },
                base_query={'inactive_state': 'active'},
                catalog_name='bika_patient_catalog',
                showOn=True,
                colModel=[{
                    'columnName': 'getPatientID',
                    'width': '20',
                    'label': _('Patient ID')
                }, {
                    'columnName': 'Title',
                    'width': '40',
                    'label': _('Full Name')
                }, {
                    'columnName': 'PatientIdentifiers',
                    'width': '40',
                    'label': _('Additional Identifiers')
                }],
                add_button={
                    'visible': True,
                    'url': 'patients/portal_factory/Patient/new/edit',
                    'return_fields': ['Firstname', 'Surname'],
                    'js_controllers': [
                        '#patient-base-edit',
                    ],
                    'overlay_handler': 'HealthPatientOverlayHandler',
                },
                edit_button={
                    'visible': True,
                    # url with the root to create/edit a object.
                    'url': 'patients/portal_factory/Patient',
                    'return_fields': ['Firstname', 'Surname'],
                    'js_controllers': [
                        '#patient-base-edit',
                    ],
                    'overlay_handler': 'HealthPatientOverlayHandler',
                }),
        ),
        # ExtComputedField('PatientID',
        #     expression="context.Schema()['Patient'].get(context) and context.Schema()['Patient'].get(context).ID() or None",
        # ),
        # ExtComputedField('PatientUID',
        #     expression="context.Schema()['Patient'].get(context) and context.Schema()['Patient'].get(context).UID() or None",
        # ),
        # ExtComputedField('PatientTitle',
        #     expression="context.Schema()['Patient'].get(context) and context.Schema()['Patient'].get(context).Title() or None",
        # ),
        ExtDateTimeField(
            'OnsetDate',
            widget=DateTimeWidget(label=_('Onset Date'), ),
        ),
        ExtStringField(
            'PatientBirthDate',
            widget=StringWidget(visible=False, ),
        ),
        ExtRecordsField(
            'PatientAgeAtCaseOnsetDate',
            widget=SplittedDateWidget(
                label=_('Patient Age at Case Onset Date'), ),
        ),
        ExtBooleanField(
            'OnsetDateEstimated',
            default=False,
            widget=BooleanWidget(label=_("Onset Date Estimated"), ),
        ),
        ExtRecordsField(
            'ProvisionalDiagnosis',
            type='provisionaldiagnosis',
            subfields=('Code', 'Title', 'Description', 'Onset'),
            # Temporary fix: https://github.com/bikalabs/bika.health/issues/89
            #required_subfields=('Title'),
            subfield_sizes={
                'Code': 7,
                'Title': 20,
                'Description': 35,
                'Onset': 10
            },
            subfield_labels={
                'Code': _('Code'),
                'Title': _('Provisional diagnosis'),
                'Description': _('Description'),
                'Onset': _('Onset')
            },
            subfield_types={'Onset': 'datepicker_nofuture'},
            widget=RecordsWidget(
                label='Provisional diagnosis',
                combogrid_options={
                    'Title': {
                        'colModel': [{
                            'columnName': 'Code',
                            'width': '10',
                            'label': _('Code')
                        }, {
                            'columnName': 'Title',
                            'width': '30',
                            'label': _('Title')
                        }, {
                            'columnName': 'Description',
                            'width': '60',
                            'label': _('Description')
                        }],
                        'url':
                        'getsymptomsbytitle',
                        'showOn':
                        True,
                        'width':
                        "650px",
                    },
                    'Code': {
                        'colModel': [{
                            'columnName': 'Code',
                            'width': '10',
                            'label': _('Code')
                        }, {
                            'columnName': 'Title',
                            'width': '30',
                            'label': _('Title')
                        }, {
                            'columnName': 'Description',
                            'width': '60',
                            'label': _('Description')
                        }],
                        'url':
                        'getsymptomsbycode',
                        'showOn':
                        True,
                        'width':
                        "650px",
                    },
                    'Description': {
                        'colModel': [{
                            'columnName': 'Code',
                            'width': '10',
                            'label': _('Code')
                        }, {
                            'columnName': 'Title',
                            'width': '30',
                            'label': _('Title')
                        }, {
                            'columnName': 'Description',
                            'width': '60',
                            'label': _('Description')
                        }],
                        'url':
                        'getsymptomsbydesc',
                        'showOn':
                        True,
                        'width':
                        "650px",
                    },
                },
            ),
        ),
        ExtTextField(
            'AdditionalNotes',
            default_content_type='text/plain',
            allowable_content_types=('text/plain', ),
            default_output_type="text/plain",
            widget=TextAreaWidget(label=_('Additional notes'), ),
        ),
        ExtLinesField(
            'CaseStatus',
            vocabulary=getCaseStatus(),
            widget=MultiSelectionWidget(format='checkbox',
                                        label=_("Case status")),
        ),
        ExtLinesField(
            'CaseOutcome',
            vocabulary=getCaseOutcome(),
            widget=MultiSelectionWidget(format='checkbox',
                                        label=_("Case outcome")),
        ),
        ExtRecordsField(
            'Symptoms',
            type='symptoms',
            subfields=('UID', 'Title', 'Description', 'Severity'),
            widget=CaseSymptomsWidget(label='Symptoms', ),
        ),
        ExtRecordsField(
            'AetiologicAgents',
            type='aetiologicagents',
            subfields=('Title', 'Description', 'Subtype'),
            subfield_sizes={
                'Title': 15,
                'Description': 25,
                'Subtype': 10
            },
            subfield_labels={
                'Title': _('Aetiologic agent'),
                'Description': _b('Description'),
                'Subtype': _('Subtype')
            },
            # Temporary fix: https://github.com/bikalabs/bika.health/issues/89
            # required_subfields=('Title'),
            widget=RecordsWidget(
                label='Aetiologic agents',
                combogrid_options={
                    'Title': {
                        'colModel': [{
                            'columnName': 'Title',
                            'width': '30',
                            'label': _('Aetiologic agent')
                        }, {
                            'columnName': 'Description',
                            'width': '60',
                            'label': _b('Description')
                        }, {
                            'columnName': 'Subtype',
                            'width': '30',
                            'label': _('Subtype')
                        }],
                        'url':
                        'getaetiologicagents',
                        'showOn':
                        True,
                        'width':
                        "650px",
                    },
                },
            ),
        ),
        ExtIntegerField(
            'HoursFasting',
            required=0,
            widget=IntegerWidget(label=_('Hours fasting'), ),
        ),
        ExtRecordsField(
            'PatientCondition',
            widget=CasePatientConditionWidget(label='Patient condition', ),
        ),
        ExtRecordsField(
            'MenstrualStatus',
            widget=CaseMenstrualStatusWidget(label='Menstrual status', ),
        ),
        ExtRecordsField(
            'BasalBodyTemperature',
            widget=CaseBasalBodyTempWidget(label='Basal body temperature', ),
        ),
        ExtStringField(
            'ClientPatientID',
            searchable=True,
            required=0,
            widget=ReferenceWidget(
                label=_b("Client Patient ID"),
                size=12,
                colModel=[
                    {
                        'columnName': 'id',
                        'width': '20',
                        'label': _('Patient ID'),
                        'align': 'left'
                    },
                    {
                        'columnName': 'ClientPatientID',
                        'width': '20',
                        'label': _('Client PID'),
                        'align': 'left'
                    },
                    {
                        'columnName': 'Title',
                        'width': '60',
                        'label': _('Fullname'),
                        'align': 'left'
                    },
                    {
                        'columnName': 'UID',
                        'hidden': True
                    },
                ],
                ui_item='ClientPatientID',
                search_query='',
                discard_empty=('ClientPatientID', ),
                search_fields=('ClientPatientID', ),
                portal_types=('Patient', ),
                render_own_label=False,
                visible={
                    'edit': 'visible',
                    'view': 'visible',
                    'add': 'visible'
                },
                catalog_name='bika_patient_catalog',
                base_query={'inactive_state': 'active'},
                showOn=True,
            ),
        ),
    ]

    def __init__(self, context):
        self.context = context

    def getOrder(self, schematas):
        schematas['default'] = [
            'id',
            'title',
            'description',
            'BatchID',
            'ClientPatientID',
            'Patient',
            # 'PatientID',
            # 'PatientUID',
            # 'PatientTitle',
            'Client',
            # 'ClientID',
            # 'ClientUID',
            # 'ClientTitle',
            'ClientBatchID',
            'Doctor',
            # 'DoctorID',
            # 'DoctorUID',
            # 'DoctorTitle',
            'BatchDate',
            'OnsetDate',
            'PatientAgeAtCaseOnsetDate',
            'OnsetDateEstimated',
            'HoursFasting',
            'PatientCondition',
            'BasalBodyTemperature',
            'MenstrualStatus',
            'Symptoms',
            'ProvisionalDiagnosis',
            'CaseStatus',
            'CaseOutcome',
            'AetiologicAgents',
            'AdditionalNotes',
            'Remarks',
            'PatientBirthDate',
            'BatchLabels',
            'InheritedObjects',
            'InheritedObjectsUI',
        ]
        return schematas

    def getFields(self):
        return self.fields
Beispiel #17
0
    def __init__(self, context, request):
        super(PatientsView, self).__init__(context, request)

        self.catalog = CATALOG_PATIENT_LISTING

        self.contentFilter = {
            'portal_type': 'Patient',
            'sort_on': 'getPatientID',
            'sort_order': 'reverse'
        }
        self.context_actions = {}
        self.title = self.context.translate(_("Patients"))
        self.icon = self.portal_url + "/++resource++bika.health.images/patient_big.png"
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = False

        self.columns = {
            'Title': {
                'title': _('Patient'),
                'index': 'Title'
            },
            'getPatientID': {
                'title': _('Patient ID'),
            },
            'getClientPatientID': {
                'title': _('Client PID'),
                'sortable': False
            },
            'getGender': {
                'title': _('Gender'),
                'toggle': True,
                'sortable': False
            },
            'getAgeSplittedStr': {
                'title': _('Age'),
                'toggle': True,
                'sortable': False
            },
            'getBirthDate': {
                'title': _('BirthDate'),
                'toggle': True,
                'sortable': False
            },
            'getPrimaryReferrer': {
                'title': _('Primary Referrer'),
                'toggle': True,
                'sortable': False
            },
        }

        self.review_states = [
            {
                'id': 'default',
                'title': _b('Active'),
                'contentFilter': {
                    'inactive_state': 'active'
                },
                'transitions': [],
                'columns': self.get_columns()
            },
        ]
    def __init__(self, context, request):
        super(ContactsView, self).__init__(context, request)
        self.catalog = "portal_catalog"
        self.contentFilter = {
            'portal_type': 'VaccinationCenterContact',
            'sort_on': 'sortable_title',
            'path': {
                "query": "/".join(context.getPhysicalPath()),
                "level": 0
            }
        }
        self.context_actions = {
            _('Add'): {
                'url': 'createObject?type_name=VaccinationCenterContact',
                'icon': '++resource++bika.lims.images/add.png'
            }
        }
        self.show_table_only = False
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = True
        self.pagesize = 50
        self.icon = self.portal_url + "/++resource++bika.health.images/vaccinationcenter_contact_big.png"
        self.title = _b("Contacts")

        self.columns = {
            'getFullname': {
                'title': _('Full Name')
            },
            'getEmailAddress': {
                'title': _('Email Address')
            },
            'getBusinessPhone': {
                'title': _('Business Phone')
            },
            'getMobilePhone': {
                'title': _('Mobile Phone')
            },
            'getFax': {
                'title': _('Fax')
            },
        }

        self.review_states = [
            {
                'id':
                'default',
                'title':
                _('Active'),
                'contentFilter': {
                    'inactive_state': 'active'
                },
                'transitions': [
                    {
                        'id': 'deactivate'
                    },
                ],
                'columns': [
                    'getFullname', 'getEmailAddress', 'getBusinessPhone',
                    'getMobilePhone', 'getFax'
                ]
            },
            {
                'id':
                'inactive',
                'title':
                _('Dormant'),
                'contentFilter': {
                    'inactive_state': 'inactive'
                },
                'transitions': [
                    {
                        'id': 'activate'
                    },
                ],
                'columns': [
                    'getFullname', 'getEmailAddress', 'getBusinessPhone',
                    'getMobilePhone', 'getFax'
                ]
            },
            {
                'id':
                'all',
                'title':
                _('All'),
                'contentFilter': {},
                'columns': [
                    'getFullname', 'getEmailAddress', 'getBusinessPhone',
                    'getMobilePhone', 'getFax'
                ]
            },
        ]
Beispiel #19
0
 def _initFormParams(self):
     super(ClientPatientsView, self)._initFormParams()
     if _b('Add') in self.context_actions:
         self.context_actions[_b('Add')]['url'] = '../../patients/createObject?type_name=Patient'
Beispiel #20
0
class BatchSchemaExtender(object):
    adapts(IBatch)
    implements(IOrderableSchemaExtender)

    fields = [
        ExtReferenceField(
            'Doctor',
            required=1,
            multiValued=0,
            allowed_types=('Doctor', ),
            referenceClass=HoldingReference,
            relationship='BatchDoctor',
            widget=ReferenceWidget(
                label=_("Doctor"),
                description="",
                render_own_label=False,
                visible={
                    'edit': 'visible',
                    'view': 'visible'
                },
                base_query={'is_active': True},
                catalog_name='portal_catalog',
                showOn=True,
                colModel=[
                    {
                        'columnName': 'DoctorID',
                        'width': '20',
                        'label': _('Doctor ID')
                    },
                    {
                        'columnName': 'Title',
                        'width': '80',
                        'label': _('Full Name')
                    },
                ],
            ),
        ),
        ExtReferenceField(
            'Patient',
            required=1,
            multiValued=0,
            allowed_types=('Patient', ),
            referenceClass=HoldingReference,
            relationship='BatchPatient',
            widget=ReferenceWidget(
                label=_("Patient"),
                description="",
                render_own_label=False,
                visible={
                    'edit': 'visible',
                    'view': 'visible'
                },
                catalog_name='bikahealth_catalog_patient_listing',
                search_fields=('listing_searchable_text', ),
                base_query={
                    'is_active': True,
                    'sort_limit': 50,
                    'sort_on': 'getPatientID',
                    'sort_order': 'ascending'
                },
                colModel=[
                    {
                        'columnName': "getPatientID",
                        'width': '30',
                        'label': _('PID'),
                        'align': 'left'
                    },
                    {
                        'columnName': "getClientPatientID",
                        'width': '30',
                        'label': _('CPID'),
                        'align': 'left'
                    },
                    {
                        'columnName': 'Title',
                        'width': '30',
                        'label': _('Title'),
                        'align': 'left'
                    },
                ],
                showOn=True,
            ),
        ),
        ExtDateTimeField(
            'OnsetDate',
            required=1,
            widget=DateTimeWidget(label=_('Onset Date'), ),
        ),
        ExtRecordsField(
            'PatientAgeAtCaseOnsetDate',
            widget=SplittedDateWidget(
                label=_('Patient Age at Case Onset Date'), ),
        ),
        ExtBooleanField(
            'OnsetDateEstimated',
            default=False,
            widget=BooleanWidget(label=_("Onset Date Estimated"), ),
        ),
        ExtRecordsField(
            'ProvisionalDiagnosis',
            type='provisionaldiagnosis',
            subfields=('Code', 'Title', 'Description', 'Onset'),
            # Temporary fix: https://github.com/bikalabs/bika.health/issues/89
            #required_subfields=('Title'),
            subfield_sizes={
                'Code': 7,
                'Title': 20,
                'Description': 35,
                'Onset': 10
            },
            subfield_labels={
                'Code': _('Code'),
                'Title': _('Provisional diagnosis'),
                'Description': _('Description'),
                'Onset': _('Onset')
            },
            subfield_types={'Onset': 'datepicker_nofuture'},
            widget=RecordsWidget(
                label='Provisional diagnosis',
                combogrid_options={
                    'Title': {
                        'colModel': [{
                            'columnName': 'Code',
                            'width': '10',
                            'label': _('Code')
                        }, {
                            'columnName': 'Title',
                            'width': '30',
                            'label': _('Title')
                        }, {
                            'columnName': 'Description',
                            'width': '60',
                            'label': _('Description')
                        }],
                        'url':
                        'getsymptomsbytitle',
                        'showOn':
                        True,
                        'width':
                        "650px",
                    },
                    'Code': {
                        'colModel': [{
                            'columnName': 'Code',
                            'width': '10',
                            'label': _('Code')
                        }, {
                            'columnName': 'Title',
                            'width': '30',
                            'label': _('Title')
                        }, {
                            'columnName': 'Description',
                            'width': '60',
                            'label': _('Description')
                        }],
                        'url':
                        'getsymptomsbycode',
                        'showOn':
                        True,
                        'width':
                        "650px",
                    },
                    'Description': {
                        'colModel': [{
                            'columnName': 'Code',
                            'width': '10',
                            'label': _('Code')
                        }, {
                            'columnName': 'Title',
                            'width': '30',
                            'label': _('Title')
                        }, {
                            'columnName': 'Description',
                            'width': '60',
                            'label': _('Description')
                        }],
                        'url':
                        'getsymptomsbydesc',
                        'showOn':
                        True,
                        'width':
                        "650px",
                    },
                },
            ),
        ),
        ExtTextField(
            'AdditionalNotes',
            default_content_type='text/plain',
            allowable_content_types=('text/plain', ),
            default_output_type="text/plain",
            widget=TextAreaWidget(label=_('Additional notes'), ),
        ),
        ExtLinesField(
            'CaseStatus',
            vocabulary=getCaseStatus(),
            widget=MultiSelectionWidget(format='checkbox',
                                        label=_("Case status")),
        ),
        ExtLinesField(
            'CaseOutcome',
            vocabulary=getCaseOutcome(),
            widget=MultiSelectionWidget(format='checkbox',
                                        label=_("Case outcome")),
        ),
        ExtRecordsField(
            'Symptoms',
            type='symptoms',
            subfields=('UID', 'Title', 'Description', 'Severity'),
            widget=CaseSymptomsWidget(label='Symptoms', ),
        ),
        ExtRecordsField(
            'AetiologicAgents',
            type='aetiologicagents',
            subfields=('Title', 'Description', 'Subtype'),
            subfield_sizes={
                'Title': 15,
                'Description': 25,
                'Subtype': 10
            },
            subfield_labels={
                'Title': _('Aetiologic agent'),
                'Description': _b('Description'),
                'Subtype': _('Subtype')
            },
            # Temporary fix: https://github.com/bikalabs/bika.health/issues/89
            # required_subfields=('Title'),
            widget=RecordsWidget(
                label='Aetiologic agents',
                combogrid_options={
                    'Title': {
                        'colModel': [{
                            'columnName': 'Title',
                            'width': '30',
                            'label': _('Aetiologic agent')
                        }, {
                            'columnName': 'Description',
                            'width': '60',
                            'label': _b('Description')
                        }, {
                            'columnName': 'Subtype',
                            'width': '30',
                            'label': _('Subtype')
                        }],
                        'url':
                        'getaetiologicagents',
                        'showOn':
                        True,
                        'width':
                        "650px",
                    },
                },
            ),
        ),
        ExtIntegerField(
            'HoursFasting',
            required=0,
            widget=IntegerWidget(label=_('Hours fasting'), ),
        ),
        ExtRecordsField(
            'PatientCondition',
            widget=CasePatientConditionWidget(label='Patient condition', ),
        ),
        ExtRecordsField(
            'MenstrualStatus',
            widget=CaseMenstrualStatusWidget(label='Menstrual status', ),
        ),
        ExtRecordsField(
            'BasalBodyTemperature',
            widget=CaseBasalBodyTempWidget(label='Basal body temperature', ),
        ),
        ExtStringField(
            'ClientPatientID',
            required=0,
            widget=ReferenceWidget(
                label=_b("Client Patient ID"),
                size=20,
                visible={
                    'edit': 'invisible',
                    'view': 'visible',
                    'add': 'edit'
                },
                catalog_name='bikahealth_catalog_patient_listing',
                portal_types=('Patient', ),
                search_fields=('getClientPatientID', ),
                base_query={
                    'is_active': True,
                    'sort_limit': 50,
                    'sort_on': 'getClientPatientID',
                    'sort_order': 'ascending'
                },
                force_all=False,
                colModel=[
                    {
                        'columnName': "getPatientID",
                        'width': '30',
                        'label': _('PID'),
                        'align': 'left'
                    },
                    {
                        'columnName': "getClientPatientID",
                        'width': '30',
                        'label': _('CPID'),
                        'align': 'left'
                    },
                    {
                        'columnName': 'Title',
                        'width': '30',
                        'label': _('Fullname'),
                        'align': 'left'
                    },
                    # UID is required in colModel
                    {
                        'columnName': 'UID',
                        'hidden': True
                    },
                ],
                ui_item="getClientPatientID",
                showOn=False,
            ),
        ),
    ]

    def __init__(self, context):
        self.context = context

    def getOrder(self, schematas):
        schematas['default'] = [
            'id',
            'title',
            'description',
            'BatchID',
            'Client',
            'ClientBatchID',
            'ClientPatientID',
            'Patient',
            'Doctor',
            'BatchDate',
            'OnsetDate',
            'OnsetDateEstimated',
            'PatientAgeAtCaseOnsetDate',
            'HoursFasting',
            'PatientCondition',
            'BasalBodyTemperature',
            'MenstrualStatus',
            'Symptoms',
            'ProvisionalDiagnosis',
            'CaseStatus',
            'CaseOutcome',
            'AetiologicAgents',
            'AdditionalNotes',
            'Remarks',
            'BatchLabels',
        ]
        return schematas

    def getFields(self):
        return self.fields
Beispiel #21
0
    def __call__(self):

        pc = self.portal_catalog
        bc = self.bika_catalog
        bsc = self.bika_setup_catalog
        self.checkPermission = self.context.portal_membership.checkPermission
        self.now = DateTime()
        self.SamplingWorkflowEnabled = self.context.bika_setup.getSamplingWorkflowEnabled()

        # Client details (if client is associated)
        self.client = None
        client_uid = hasattr(self.context, 'getClientUID') and self.context.getClientUID()
        if client_uid:
            proxies = pc(portal_type='Client', UID=client_uid)
        if proxies:
            self.client = proxies[0].getObject()
            client_address = self.client.getPostalAddress() \
                or self.contact.getBillingAddress() \
                or self.contact.getPhysicalAddress()
            if client_address:
                _keys = ['address', 'city', 'state', 'zip', 'country']
                _list = [client_address.get(v) for v in _keys if client_address.get(v)]
                self.client_address = "<br/>".join(_list).replace("\n", "<br/>")
                if self.client_address.endswith("<br/>"):
                    self.client_address = self.client_address[:-5]
            else:
                self.client_address = None

        # Reporter
        self.member = self.context.portal_membership.getAuthenticatedMember()
        self.username = self.member.getUserName()
        self.reporter = self.user_fullname(self.username)
        self.reporter_email = self.user_email(self.username)
        self.reporter_signature = ""
        c = [x for x in self.bika_setup_catalog(portal_type='LabContact')
             if x.getObject().getUsername() == self.username]
        if c:
            sf = c[0].getObject().getSignature()
            if sf:
                self.reporter_signature = sf.absolute_url() + "/Signature"

        # laboratory
        self.laboratory = self.context.bika_setup.laboratory
        self.accredited = self.laboratory.getLaboratoryAccredited()
        lab_address = self.laboratory.getPrintAddress()
        if lab_address:
            _keys = ['address', 'city', 'state', 'zip', 'country']
            _list = [lab_address.get(v) for v in _keys if lab_address.get(v)]
            self.lab_address = "<br/>".join(_list).replace("\n", "<br/>")
            if self.lab_address.endswith("<br/>"):
                self.lab_address = self.lab_address[:-5]
        else:
            self.lab_address = None

        # Analysis Request results
        self.ars = []
        self.ar_headers = [_b("Request ID"),
                           _b("Date Requested"),
                           _b("Sample Type"),
                           _b("Sample Point")]
        self.analysis_headers = [_b("Analysis Service"),
                                 _b("Method"),
                                 _b("Result"),
                                 _b("Analyst")]
        for ar in self.context.getAnalysisRequests():
            datecreated = ar.created()
            datereceived = ar.getDateReceived()
            datepublished = ar.getDatePublished()
            datalines = []
            for analysis in ar.getAnalyses(full_objects=True):
                method = analysis.getMethod()
                sample = ar.getSample()
                result = analysis.getResult()
                try:
                    precision = analysis.getPrecision()
                    if not precision:
                        precision = "2"
                    result = float(result)
                    formatted_result = str("%." + precision + "f") % result
                except (TypeError, ValueError):
                    precision = "2"
                    formatted_result = result
                datalines.append({_b("Analysis Service"): analysis.Title(),
                                  _b("Method"): method and method.Title() or "",
                                  _b("Result"): formatted_result,
                                  _b("Analyst"): self.user_fullname(analysis.getAnalyst()),
                                  _b("Remarks"): analysis.getRemarks()})
            self.ars.append({
                _b("Request ID"): ar.getRequestID(),
                _b("Date Requested"): self.ulocalized_time(datecreated),  # requested->created
                _b("Sample Type"): sample.getSampleType() and sample.getSampleType().Title() or '',
                _b("Sample Point"): sample.getSamplePoint() and sample.getSamplePoint().Title() or '',
                _b("datalines"): datalines,
            })

        # Create Report
        fn = self.context.Title() + " " + self.ulocalized_time(self.now)
        report_html = self.template()

        debug_mode = App.config.getConfiguration().debug_mode
        if debug_mode:
            open(os.path.join(Globals.INSTANCE_HOME, 'var', fn + ".html"),
                 "w").write(report_html)

        pisa.showLogging()
        ramdisk = StringIO()
        pdf = pisa.CreatePDF(report_html, ramdisk)
        pdf_data = ramdisk.getvalue()
        ramdisk.close()

        if debug_mode:
            open(os.path.join(Globals.INSTANCE_HOME, 'var', fn + ".pdf"),
                 "wb").write(pdf_data)

        # Email to who?

        # Send PDF to browser
        if not pdf.err:
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'application/pdf')
            setheader("Content-Disposition", "attachment;filename=\"%s\"" % fn)
            self.request.RESPONSE.write(pdf_data)
Beispiel #22
0
    def __init__(self, context, request):
        super(BatchFolderContentsView, self).__init__(context, request)

        self.columns = {
            'BatchID': {
                'title': _('Batch ID')
            },
            'Title': {
                'title': _b('Title')
            },
            'WorksOrderID': {
                'title': _('Works Order ID')
            },
            'BlendNumber': {
                'title': _('Blend Name')
            },
            'Description': {
                'title': _b('Description')
            },
            'state_title': {
                'title': _b('State'),
                'sortable': False
            },
        }

        self.review_states = [  # leave these titles and ids alone
            {
                'id':
                'default',
                'title':
                _b('All'),
                'contentFilter': {},
                'columns': [
                    'BatchID',
                    'Title',
                    'BlendNumber',
                    'WorksOrderID',
                    'Description',
                    'state_title',
                ]
            },
            {
                'id':
                'open',  # in bika.lims, this is 'default'.
                'contentFilter': {
                    'cancellation_state':
                    'active',
                    'review_state':
                    ['open', 'received', 'to_be_verified', 'verified']
                },
                'title':
                _b('Open'),
                'columns': [
                    'BatchID',
                    'Title',
                    'BlendNumber',
                    'WorksOrderID',
                    'Description',
                    'state_title',
                ]
            },
            {
                'id':
                'closed',
                'contentFilter': {
                    'review_state': 'closed'
                },
                'title':
                _b('Closed'),
                'columns': [
                    'BatchID',
                    'Title',
                    'BlendNumber',
                    'WorksOrderID',
                    'Description',
                    'state_title',
                ]
            },
            {
                'id':
                'cancelled',
                'title':
                _b('Cancelled'),
                'contentFilter': {
                    'cancellation_state': 'cancelled'
                },
                'columns': [
                    'BatchID',
                    'Title',
                    'BlendNumber',
                    'WorksOrderID',
                    'Description',
                    'state_title',
                ]
            },
        ]
Beispiel #23
0
    def __init__(self, context, request):
        super(CountryRegionsView, self).__init__(context, request)
        self.catalog = 'bika_setup_catalog'
        path = "/".join(self.context.getPhysicalPath())
        self.contentFilter = {
            'portal_type': 'Region',
            'sort_on': 'sortable_title',
            'path': {
                'query': path,
                'level': 0
            }
        }
        self.context_actions = {
            _('Add Region'): {
                'url': 'createObject?type_name=Region',
                'icon': '++resource++bika.lims.images/add.png'
            }
        }
        self.icon = self.portal_url + \
            "/++resource++bika.wine.images/region.png"
        self.title = self.context.Title()
        self.description = ""
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = True
        self.pagesize = 25

        self.columns = {
            'Title': {
                'title': _('Region'),
                'index': 'sortable_title'
            },
        }

        self.review_states = [
            {
                'id': 'default',
                'title': _b('Active'),
                'contentFilter': {
                    'inactive_state': 'active'
                },
                'transitions': [
                    {
                        'id': 'deactivate'
                    },
                ],
                'columns': ['Title']
            },
            {
                'id': 'inactive',
                'title': _b('Inactive'),
                'contentFilter': {
                    'inactive_state': 'inactive'
                },
                'transitions': [
                    {
                        'id': 'activate'
                    },
                ],
                'columns': ['Title']
            },
            {
                'id': 'all',
                'title': _b('All'),
                'contentFilter': {},
                'columns': ['Title']
            },
        ]

        return super(CountryRegionsView, self).__init__(context, request)
    def __init__(self, context, request):
        super(TransportConditionsView, self).__init__(context, request)
        self.catalog = 'bika_setup_catalog'
        self.contentFilter = {
            'portal_type': 'TransportCondition',
            'sort_on': 'sortable_title'
        }
        self.context_actions = {
            _b('Add'): {
                'url': 'createObject?type_name=TransportCondition',
                'icon': '++resource++bika.lims.images/add.png'
            }
        }
        self.icon = self.portal_url + \
            "/++resource++bika.wine.images/transportcondition_big.png"
        self.title = self.context.translate(_("Transport conditions"))
        self.description = ""
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = True
        self.pagesize = 25

        self.columns = {
            'Title': {
                'title': _('Transport condition'),
                'index': 'sortable_title'
            },
            'Description': {
                'title': _b('Description'),
                'index': 'description',
                'toggle': True
            },
        }

        self.review_states = [
            {
                'id': 'default',
                'title': _b('Active'),
                'contentFilter': {
                    'inactive_state': 'active'
                },
                'transitions': [
                    {
                        'id': 'deactivate'
                    },
                ],
                'columns': ['Title', 'Description']
            },
            {
                'id': 'inactive',
                'title': _b('Inactive'),
                'contentFilter': {
                    'inactive_state': 'inactive'
                },
                'transitions': [
                    {
                        'id': 'activate'
                    },
                ],
                'columns': ['Title', 'Description']
            },
            {
                'id': 'all',
                'title': _b('All'),
                'contentFilter': {},
                'columns': ['Title', 'Description']
            },
        ]
Beispiel #25
0
    def __call__(self):

        pc = self.portal_catalog
        bc = self.bika_catalog
        bsc = self.bika_setup_catalog
        self.checkPermission = self.context.portal_membership.checkPermission
        self.now = DateTime()
        self.SamplingWorkflowEnabled = self.context.bika_setup.getSamplingWorkflowEnabled(
        )

        # Client details (if client is associated)
        self.client = None
        client_uid = hasattr(self.context,
                             'getClientUID') and self.context.getClientUID()
        if client_uid:
            proxies = pc(portal_type='Client', UID=client_uid)
        if proxies:
            self.client = proxies[0].getObject()
            client_address = self.client.getPostalAddress() \
                or self.contact.getBillingAddress() \
                or self.contact.getPhysicalAddress()
            if client_address:
                _keys = ['address', 'city', 'state', 'zip', 'country']
                _list = [
                    client_address.get(v) for v in _keys
                    if client_address.get(v)
                ]
                self.client_address = "<br/>".join(_list).replace(
                    "\n", "<br/>")
                if self.client_address.endswith("<br/>"):
                    self.client_address = self.client_address[:-5]
            else:
                self.client_address = None

        # Reporter
        self.member = self.context.portal_membership.getAuthenticatedMember()
        self.username = self.member.getUserName()
        self.reporter = self.user_fullname(self.username)
        self.reporter_email = self.user_email(self.username)
        self.reporter_signature = ""
        c = [
            x for x in self.bika_setup_catalog(portal_type='LabContact')
            if x.getObject().getUsername() == self.username
        ]
        if c:
            sf = c[0].getObject().getSignature()
            if sf:
                self.reporter_signature = sf.absolute_url() + "/Signature"

        # laboratory
        self.laboratory = self.context.bika_setup.laboratory
        self.accredited = self.laboratory.getLaboratoryAccredited()
        lab_address = self.laboratory.getPrintAddress()
        if lab_address:
            _keys = ['address', 'city', 'state', 'zip', 'country']
            _list = [lab_address.get(v) for v in _keys if lab_address.get(v)]
            self.lab_address = "<br/>".join(_list).replace("\n", "<br/>")
            if self.lab_address.endswith("<br/>"):
                self.lab_address = self.lab_address[:-5]
        else:
            self.lab_address = None

        # Analysis Request results
        self.ars = []
        self.ar_headers = [
            _b("Request ID"),
            _b("Date Requested"),
            _b("Sample Type"),
            _b("Sample Point")
        ]
        self.analysis_headers = [
            _b("Analysis Service"),
            _b("Method"),
            _b("Result"),
            _b("Analyst")
        ]
        for ar in self.context.getAnalysisRequests():
            datecreated = ar.created()
            datereceived = ar.getDateReceived()
            datepublished = ar.getDatePublished()
            datalines = []
            for analysis in ar.getAnalyses(full_objects=True):
                method = analysis.getMethod()
                sample = ar.getSample()
                result = analysis.getResult()
                try:
                    precision = analysis.getPrecision()
                    if not precision:
                        precision = "2"
                    result = float(result)
                    formatted_result = str("%." + precision + "f") % result
                except (TypeError, ValueError):
                    precision = "2"
                    formatted_result = result
                datalines.append({
                    _b("Analysis Service"):
                    analysis.Title(),
                    _b("Method"):
                    method and method.Title() or "",
                    _b("Result"):
                    formatted_result,
                    _b("Analyst"):
                    self.user_fullname(analysis.getAnalyst()),
                    _b("Remarks"):
                    analysis.getRemarks()
                })
            self.ars.append({
                _b("Request ID"):
                ar.getRequestID(),
                _b("Date Requested"):
                self.ulocalized_time(datecreated),  # requested->created
                _b("Sample Type"):
                sample.getSampleType() and sample.getSampleType().Title()
                or '',
                _b("Sample Point"):
                sample.getSamplePoint() and sample.getSamplePoint().Title()
                or '',
                _b("datalines"):
                datalines,
            })

        # Create Report
        fn = self.context.Title() + " " + self.ulocalized_time(self.now)
        report_html = self.template()

        debug_mode = App.config.getConfiguration().debug_mode
        if debug_mode:
            open(os.path.join(Globals.INSTANCE_HOME, 'var', fn + ".html"),
                 "w").write(report_html)

        pisa.showLogging()
        ramdisk = StringIO()
        pdf = pisa.CreatePDF(report_html, ramdisk)
        pdf_data = ramdisk.getvalue()
        ramdisk.close()

        if debug_mode:
            open(os.path.join(Globals.INSTANCE_HOME, 'var', fn + ".pdf"),
                 "wb").write(pdf_data)

        # Email to who?

        # Send PDF to browser
        if not pdf.err:
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'application/pdf')
            setheader("Content-Disposition", "attachment;filename=\"%s\"" % fn)
            self.request.RESPONSE.write(pdf_data)