本文整理汇总了Python中bika.lims.browser.reports.selection_macros.SelectionMacrosView类的典型用法代码示例。如果您正苦于以下问题:Python SelectionMacrosView类的具体用法?Python SelectionMacrosView怎么用?Python SelectionMacrosView使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SelectionMacrosView类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
示例2: Report
class Report(BrowserView):
implements(IViewView)
default_template = ViewPageTemplateFile("templates/productivity.pt")
template = ViewPageTemplateFile("templates/productivity_samplereceivedvsreported.pt")
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
def __call__(self):
parms = []
titles = []
self.contentFilter = {'portal_type': 'Sample',
'review_state': ['sample_received', 'expired', 'disposed'],
'sort_on': 'getDateReceived'}
val = self.selection_macros.parse_daterange(self.request,
'getDateReceived',
_('Date Received'))
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
# Query the catalog and store results in a dictionary
samples = self.bika_catalog(self.contentFilter)
if not samples:
message = _("No samples matched your query")
self.context.plone_utils.addPortalMessage(message, "error")
return self.default_template()
datalines = {}
footlines = {}
total_received_count = 0;
total_published_count = 0;
for sample in samples:
sample = sample.getObject()
# For each sample, retrieve check is has results published
# and add it to datalines
published = False
analyses = sample.getAnalyses({})
for analysis in analyses:
analysis = analysis.getObject()
if not (analysis.getDateAnalysisPublished() is None):
published = True
break
datereceived = sample.getDateReceived()
monthyear = datereceived.strftime("%B")+" "+datereceived.strftime("%Y")
received = 1
publishedcnt = published and 1 or 0
if (monthyear in datalines):
received = datalines[monthyear]['ReceivedCount']+1
publishedcnt = published and datalines[monthyear]['PublishedCount'] + 1 or datalines[monthyear]['PublishedCount']
ratio = publishedcnt/received
dataline = {'MonthYear': monthyear,
'ReceivedCount': received,
'PublishedCount': publishedcnt,
'UnpublishedCount': received-publishedcnt,
'Ratio':ratio,
'RatioPercentage':('{0:.1g}'.format(ratio*100))+"%"}
datalines[monthyear] = dataline
total_received_count += 1
total_published_count = published and total_published_count+1 or total_published_count
# Footer total data
ratio = total_published_count/total_received_count
footline = {'ReceivedCount': total_received_count,
'PublishedCount' : total_published_count,
'UnpublishedCount' : total_received_count-total_published_count,
'Ratio':ratio,
'RatioPercentage':('{0:.1g}'.format(ratio*100))+"%"}
footlines['Total'] = footline;
self.report_data = {
'parameters': parms,
'datalines': datalines,
'footlines': footlines }
return {'report_title': _('Samples received vs. reported'),
'report_data': self.template()}
示例3: Report
class Report(BrowserView):
implements(IViewView)
default_template = ViewPageTemplateFile("templates/administration.pt")
template = ViewPageTemplateFile("templates/administration_usershistory.pt")
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
def __call__(self):
parms = []
titles = []
rt = getToolByName(self.context, 'portal_repository')
mt = getToolByName(self.context, 'portal_membership')
# Apply filters
self.contentFilter = {'portal_type': ('Analysis',
'AnalysisCategory',
'AnalysisProfile',
'AnalysisRequest',
'AnalysisService',
'AnalysisSpec',
'ARTemplate',
'Attachment',
'Batch',
'Calculation',
'Client',
'Contact',
'Container',
'ContainerType',
'Department',
'DuplicateAnalysis',
'Instrument',
'InstrumentCalibration',
'InstrumentCertification',
'InstrumentMaintenanceTask',
'InstrumentScheduledTask',
'InstrumentType',
'InstrumentValidation',
'Manufacturer'
'Method',
'Preservation',
'Pricelist',
'ReferenceAnalysis',
'ReferenceDefinition',
'ReferenceSample',
'Sample',
'SampleMatrix',
'SamplePoint',
'SampleType',
'Supplier',
'SupplierContact',
'Worksheet',
'WorksheetTemplate'
)}
val = self.selection_macros.parse_daterange(self.request,
'getModificationDate',
_('Modification date'))
if val:
self.contentFilter['modified'] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
user = ''
userfullname = ''
if (self.request.form.get('User', '')!=''):
user = self.request.form['User']
userobj = mt.getMemberById(user)
userfullname = userobj and userobj.getProperty('fullname') or ''
parms.append({'title': _('User'), 'value': ("%s (%s)"%(userfullname,user))})
titles.append(userfullname)
# Query the catalog and store results in a dictionary
entities = self.bika_setup_catalog(self.contentFilter)
if not entities:
message = _("No historical actions matched your query")
self.context.plone_utils.addPortalMessage(message, "error")
return self.default_template()
datalines = []
tmpdatalines = {}
footlines = {}
for entity in entities:
entity = entity.getObject()
entitytype = _(entity.__class__.__name__)
# Workflow states retrieval
for workflowid, workflow in entity.workflow_history.iteritems():
for action in workflow:
actiontitle = _('Created')
if not action['action'] or (action['action'] and action ['action']=='create'):
if workflowid=='bika_inactive_workflow':
continue
actiontitle=_('Created')
#.........这里部分代码省略.........
示例4: Report
class Report(BrowserView):
implements(IViewView)
default_template = ViewPageTemplateFile("templates/productivity.pt")
template = ViewPageTemplateFile(
"templates/productivity_samplereceivedvsreported.pt")
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
def __call__(self):
parms = []
titles = []
self.contentFilter = {'portal_type': 'Sample',
'review_state': ['sample_received', 'expired',
'disposed'],
'sort_on': 'getDateReceived'}
val = self.selection_macros.parse_daterange(self.request,
'getDateReceived',
_('Date Received'))
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
# Query the catalog and store results in a dictionary
samples = self.bika_catalog(self.contentFilter)
if not samples:
message = _("No samples matched your query")
self.context.plone_utils.addPortalMessage(message, "error")
return self.default_template()
datalines = {}
footlines = {}
total_received_count = 0
total_published_count = 0
for sample in samples:
sample = sample.getObject()
# For each sample, retrieve check is has results published
# and add it to datalines
published = False
analyses = sample.getAnalyses({})
for analysis in analyses:
analysis = analysis.getObject()
if not (analysis.getDateAnalysisPublished() is None):
published = True
break
datereceived = sample.getDateReceived()
monthyear = datereceived.strftime("%B") + " " + datereceived.strftime(
"%Y")
received = 1
publishedcnt = published and 1 or 0
if (monthyear in datalines):
received = datalines[monthyear]['ReceivedCount'] + 1
publishedcnt = published and datalines[monthyear][
'PublishedCount'] + 1 or \
datalines[monthyear]['PublishedCount']
ratio = publishedcnt / received
dataline = {'MonthYear': monthyear,
'ReceivedCount': received,
'PublishedCount': publishedcnt,
'UnpublishedCount': received - publishedcnt,
'Ratio': ratio,
'RatioPercentage': '%02d' % (
100 * (float(publishedcnt) / float(received))) + '%'}
datalines[monthyear] = dataline
total_received_count += 1
total_published_count = published and total_published_count + 1 or total_published_count
# Footer total data
ratio = total_published_count / total_received_count
footline = {'ReceivedCount': total_received_count,
'PublishedCount': total_published_count,
'UnpublishedCount': total_received_count - total_published_count,
'Ratio': ratio,
'RatioPercentage': '%02d' % (100 * (
float(total_published_count) / float(
total_received_count))) + '%'
}
footlines['Total'] = footline
self.report_data = {
'parameters': parms,
'datalines': datalines,
'footlines': footlines}
if self.request.get('output_format', '') == 'CSV':
import csv
import StringIO
import datetime
fieldnames = [
'MonthYear',
#.........这里部分代码省略.........
示例5: Report
class Report(BrowserView):
implements(IViewView)
template = ViewPageTemplateFile(
"templates/qualitycontrol_resultspersamplepoint.pt")
# if unsuccessful we return here:
default_template = ViewPageTemplateFile("templates/qualitycontrol.pt")
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
def get_analysis_spec(self, analysis):
rr = dicts_to_dict(analysis.aq_parent.getResultsRange(), 'keyword')
return rr.get(analysis.getKeyword(), None)
def ResultOutOfRange(self, analysis):
"""Template wants to know, is this analysis out of range? We scan
IResultOutOfRange adapters, and return True if any IAnalysis adapters
trigger a result. """
adapters = getAdapters((analysis, ), IResultOutOfRange)
spec = self.get_analysis_spec(analysis)
for name, adapter in adapters:
if not spec:
return False
if adapter(specification=spec):
return True
def __call__(self):
MinimumResults = self.context.bika_setup.getMinimumResults()
warning_icon = "<img " + \
"src='" + self.portal_url + "/++resource++bika.lims.images/warning.png' " + \
"height='9' width='9'/>"
error_icon = "<img " + \
"src='" + self.portal_url + "/++resource++bika.lims.images/exclamation.png' " + \
"height='9' width='9'/>"
header = _("Results per sample point")
subheader = _(
"Analysis results for per sample point and analysis service")
self.contentFilter = {'portal_type': 'Analysis',
'review_state': ['verified', 'published']}
parms = []
titles = []
val = self.selection_macros.parse_client(self.request)
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
val = self.selection_macros.parse_samplepoint(self.request)
sp_uid = val
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
val = self.selection_macros.parse_sampletype(self.request)
st_uid = val
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
val = self.selection_macros.parse_analysisservice(self.request)
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
else:
message = _("No analysis services were selected.")
self.context.plone_utils.addPortalMessage(message, 'error')
return self.default_template()
val = self.selection_macros.parse_daterange(self.request,
'getDateSampled',
'DateSampled')
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
val = self.selection_macros.parse_state(self.request,
'bika_worksheetanalysis_workflow',
'worksheetanalysis_review_state',
'Worksheet state')
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
# Query the catalog and store analysis data in a dict
analyses = {}
out_of_range_count = 0
in_shoulder_range_count = 0
analysis_count = 0
proxies = self.bika_analysis_catalog(self.contentFilter)
#.........这里部分代码省略.........
示例6: Report
class Report(BrowserView):
implements(IViewView)
default_template = ViewPageTemplateFile("templates/productivity.pt")
template = ViewPageTemplateFile("templates/productivity_dataentrydaybook.pt")
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
def __call__(self):
parms = []
titles = []
# Apply filters
self.contentFilter = {'portal_type': 'AnalysisRequest'}
val = self.selection_macros.parse_daterange(self.request,
'getDateCreated',
_('Date Created'))
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
# Query the catalog and store results in a dictionary
ars = self.bika_catalog(self.contentFilter)
if not ars:
message = _("No Analysis Requests matched your query")
self.context.plone_utils.addPortalMessage(message, "error")
return self.default_template()
datalines = {}
footlines = {}
totalcreatedcount = len(ars)
totalreceivedcount = 0
totalpublishedcount = 0
totalanlcount = 0
totalreceptionlag = 0
totalpublicationlag = 0
for ar in ars:
ar = ar.getObject()
datecreated = ar.created()
datereceived = ar.getDateReceived()
datepublished = ar.getDatePublished()
receptionlag = 0
publicationlag = 0
anlcount = len(ar.getAnalyses())
dataline = {
"AnalysisRequestID": ar.getRequestID(),
"DateCreated": self.ulocalized_time(datecreated),
"DateReceived": self.ulocalized_time(datereceived),
"DatePublished": self.ulocalized_time(datepublished),
"ReceptionLag": receptionlag,
"PublicationLag": publicationlag,
"TotalLag": receptionlag + publicationlag,
"BatchID": ar.getBatch(),
"SampleID": ar.getSample().Title(),
"SampleType": ar.getSampleTypeTitle(),
"NumAnalyses": anlcount,
"ClientID": ar.aq_parent.id,
"Creator": ar.Creator(),
"Remarks": ar.getRemarks()
}
datalines[ar.getRequestID()] = dataline
totalreceivedcount += ar.getDateReceived() and 1 or 0
totalpublishedcount += ar.getDatePublished() and 1 or 0
totalanlcount += anlcount
totalreceptionlag += receptionlag
totalpublicationlag += publicationlag
# Footer total data
totalreceivedcreated_ratio = float(totalreceivedcount) / float(totalcreatedcount)
totalpublishedcreated_ratio = float(totalpublishedcount) / float(totalcreatedcount)
totalpublishedreceived_ratio = float(totalpublishedcount) / float(totalreceivedcount)
footline = {'Created': totalcreatedcount,
'Received': totalreceivedcount,
'Published': totalpublishedcount,
'ReceivedCreatedRatio': totalreceivedcreated_ratio,
'ReceivedCreatedRatioPercentage': ('{0:.0f}'.format(totalreceivedcreated_ratio * 100)) + "%",
'PublishedCreatedRatio': totalpublishedcreated_ratio,
'PublishedCreatedRatioPercentage': ('{0:.0f}'.format(totalpublishedcreated_ratio * 100)) + "%",
'PublishedReceivedRatio': totalpublishedreceived_ratio,
'PublishedReceivedRatioPercentage': ('{0:.0f}'.format(totalpublishedreceived_ratio * 100)) + "%",
'AvgReceptionLag': ('{0:.1f}'.format(totalreceptionlag / totalcreatedcount)),
'AvgPublicationLag': ('{0:.1f}'.format(totalpublicationlag / totalcreatedcount)),
'AvgTotalLag': ('{0:.1f}'.format((totalreceptionlag + totalpublicationlag) / totalcreatedcount)),
'NumAnalyses': totalanlcount
}
footlines['Total'] = footline
self.report_data = {'parameters': parms,
'datalines': datalines,
'footlines': footlines}
#.........这里部分代码省略.........
示例7: Report
class Report(BrowserView):
implements(IViewView)
default_template = ViewPageTemplateFile("templates/productivity.pt")
template = ViewPageTemplateFile(
"templates/productivity_analysesperdepartment.pt")
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
def __call__(self):
parms = []
titles = []
# Apply filters
self.contentFilter = {'portal_type': 'Analysis'}
val = self.selection_macros.parse_daterange(self.request,
'getDateRequested',
_('Date Requested'))
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
val = self.selection_macros.parse_state(self.request,
'bika_analysis_workflow',
'getAnalysisState',
_('Analysis State'))
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
# Query the catalog and store results in a dictionary
analyses = self.bika_analysis_catalog(self.contentFilter)
if not analyses:
message = _("No analyses matched your query")
self.context.plone_utils.addPortalMessage(message, "error")
return self.default_template()
groupby = self.request.form.get('GroupingPeriod', '')
if (groupby != ''):
parms.append({"title": _("Grouping period"), "value": _(groupby)})
datalines = {}
footlines = {}
totalcount = len(analyses)
totalpublishedcount = 0
totalperformedcount = 0
for analysis in analyses:
analysis = analysis.getObject()
analysisservice = analysis.getService()
department = analysisservice.getDepartment()
department = department.Title() if department else ''
daterequested = analysis.created()
group = ''
if groupby == 'Day':
group = self.ulocalized_time(daterequested)
elif groupby == 'Week':
group = daterequested.strftime(
"%Y") + ", " + daterequested.strftime("%U")
elif groupby == 'Month':
group = daterequested.strftime(
"%B") + " " + daterequested.strftime("%Y")
elif groupby == 'Year':
group = daterequested.strftime("%Y")
else:
group = ''
dataline = {'Group': group, 'Requested': 0, 'Performed': 0,
'Published': 0, 'Departments': {}}
deptline = {'Department': department, 'Requested': 0, 'Performed': 0,
'Published': 0}
if (group in datalines):
dataline = datalines[group]
if (department in dataline['Departments']):
deptline = dataline['Departments'][department]
grouptotalcount = dataline['Requested'] + 1
groupperformedcount = dataline['Performed']
grouppublishedcount = dataline['Published']
depttotalcount = deptline['Requested'] + 1
deptperformedcount = deptline['Performed']
deptpubishedcount = deptline['Published']
workflow = getToolByName(self.context, 'portal_workflow')
arstate = workflow.getInfoFor(analysis.aq_parent, 'review_state', '')
if (arstate == 'published'):
deptpubishedcount += 1
grouppublishedcount += 1
totalpublishedcount += 1
if (analysis.getResult()):
deptperformedcount += 1
groupperformedcount += 1
totalperformedcount += 1
#.........这里部分代码省略.........
示例8: Report
class Report(BrowserView):
implements(IViewView)
template = ViewPageTemplateFile(
"templates/qualitycontrol_referenceanalysisqc.pt")
# if unsuccessful we return here:
default_template = ViewPageTemplateFile("templates/qualitycontrol.pt")
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
def __call__(self):
header = _("Reference analysis QC")
subheader = _("Reference analysis quality control graphs ")
MinimumResults = self.context.bika_setup.getMinimumResults()
warning_icon = "<img src='" + self.portal_url + "/++resource++bika.lims.images/warning.png' height='9' width='9'/>"
error_icon = "<img src='" + self.portal_url + "/++resource++bika.lims.images/exclamation.png' height='9' width='9'/>"
self.parms = []
titles = []
sample_uid = self.request.form.get('ReferenceSampleUID', '')
sample = self.reference_catalog.lookupObject(sample_uid)
if not sample:
message = _("No reference sample was selected.")
self.context.plone_utils.addPortalMessage(message, 'error')
return self.default_template()
self.parms.append(
{'title': _("Reference Sample"), 'value': sample.Title()})
titles.append(sample.Title())
service_uid = self.request.form.get('ReferenceServiceUID', '')
service = self.reference_catalog.lookupObject(service_uid)
if not service:
message = _("No analysis services were selected.")
self.context.plone_utils.addPortalMessage(message, 'error')
return self.default_template()
self.contentFilter = {'portal_type': 'ReferenceAnalysis',
'review_state': ['verified', 'published'],
'path': {
"query": "/".join(sample.getPhysicalPath()),
"level": 0}}
self.parms.append(
{'title': _("Analysis Service"), 'value': service.Title()})
titles.append(service.Title())
val = self.selection_macros.parse_daterange(self.request,
'getDateVerified',
'DateVerified')
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
self.parms.append(val['parms'])
titles.append(val['titles'])
proxies = self.bika_analysis_catalog(self.contentFilter)
if not proxies:
message = _("No analyses matched your query")
self.context.plone_utils.addPortalMessage(message, 'error')
return self.default_template()
# Compile a list with all relevant analysis data
analyses = []
out_of_range_count = 0
results = []
capture_dates = []
plotdata = ""
tabledata = []
for analysis in proxies:
analysis = analysis.getObject()
service = analysis.getService()
resultsrange = \
[x for x in sample.getReferenceResults() if x['uid'] == service_uid][
0]
try:
result = float(analysis.getResult())
results.append(result)
except:
result = analysis.getResult()
capture_dates.append(analysis.getResultCaptureDate())
if result < float(resultsrange['min']) or result > float(
resultsrange['max']):
out_of_range_count += 1
try:
precision = str(analysis.getPrecision())
except:
precision = "2"
#.........这里部分代码省略.........
示例9: Report
class Report(BrowserView):
implements(IViewView)
template = ViewPageTemplateFile("templates/qualitycontrol_resultspersamplepoint.pt")
# if unsuccessful we return here:
default_template = ViewPageTemplateFile("templates/qualitycontrol.pt")
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
def __call__(self):
MinimumResults = self.context.bika_setup.getMinimumResults()
warning_icon = (
"<img "
+ "src='"
+ self.portal_url
+ "/++resource++bika.lims.images/warning.png' "
+ "height='9' width='9'/>"
)
error_icon = (
"<img "
+ "src='"
+ self.portal_url
+ "/++resource++bika.lims.images/exclamation.png' "
+ "height='9' width='9'/>"
)
header = _("Results per sample point")
subheader = _("Analysis results for per sample point and analysis service")
self.contentFilter = {
"portal_type": "Analysis",
"review_state": ["verified", "published"],
"sort_on": "getDateSampled",
}
spec = self.request.form.get("spec", "lab")
spec_title = (spec == "lab") and _("Lab") or _("Client")
parms = []
titles = []
val = self.selection_macros.parse_client(self.request)
if val:
self.contentFilter[val["contentFilter"][0]] = val["contentFilter"][1]
parms.append(val["parms"])
titles.append(val["titles"])
val = self.selection_macros.parse_samplepoint(self.request)
sp_uid = val
if val:
self.contentFilter[val["contentFilter"][0]] = val["contentFilter"][1]
parms.append(val["parms"])
titles.append(val["titles"])
val = self.selection_macros.parse_sampletype(self.request)
st_uid = val
if val:
self.contentFilter[val["contentFilter"][0]] = val["contentFilter"][1]
parms.append(val["parms"])
titles.append(val["titles"])
val = self.selection_macros.parse_analysisservice(self.request)
if val:
self.contentFilter[val["contentFilter"][0]] = val["contentFilter"][1]
parms.append(val["parms"])
else:
message = _("No analysis services were selected.")
self.context.plone_utils.addPortalMessage(message, "error")
return self.default_template()
val = self.selection_macros.parse_daterange(self.request, "getDateSampled", "DateSampled")
if val:
self.contentFilter[val["contentFilter"][0]] = val["contentFilter"][1]
parms.append(val["parms"])
titles.append(val["titles"])
val = self.selection_macros.parse_state(
self.request, "bika_worksheetanalysis_workflow", "worksheetanalysis_review_state", "Worksheet state"
)
if val:
self.contentFilter[val["contentFilter"][0]] = val["contentFilter"][1]
parms.append(val["parms"])
# Query the catalog and store analysis data in a dict
analyses = {}
out_of_range_count = 0
in_shoulder_range_count = 0
analysis_count = 0
proxies = self.bika_analysis_catalog(self.contentFilter)
if not proxies:
message = _("No analyses matched your query")
self.context.plone_utils.addPortalMessage(message, "error")
return self.default_template()
cached_specs = {} # keyed by parent_folder
#.........这里部分代码省略.........
示例10: Report
class Report(BrowserView):
implements(IViewView)
default_template = ViewPageTemplateFile("templates/productivity.pt")
template = ViewPageTemplateFile("templates/productivity_dailysamplesreceived.pt")
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
def __call__(self):
parms = []
titles = []
self.contentFilter = {'portal_type': 'Sample',
'review_state': ['sample_received', 'expired', 'disposed'],
'sort_on': 'getDateReceived'}
val = self.selection_macros.parse_daterange(self.request,
'getDateReceived',
_('Date Received'))
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
# Query the catalog and store results in a dictionary
samples = self.bika_catalog(self.contentFilter)
if not samples:
message = _("No samples matched your query")
self.context.plone_utils.addPortalMessage(message, "error")
return self.default_template()
datalines = []
analyses_count = 0
for sample in samples:
sample = sample.getObject()
# For each sample, retrieve the analyses and generate
# a data line for each one
analyses = sample.getAnalyses({})
for analysis in analyses:
analysis = analysis.getObject()
dataline = {'AnalysisKeyword': analysis.getKeyword(),
'AnalysisTitle': analysis.getServiceTitle(),
'SampleID': sample.getSampleID(),
'SampleType': sample.getSampleType().Title(),
'SampleDateReceived': self.ulocalized_time(sample.getDateReceived(), long_format=1),
'SampleSamplingDate': self.ulocalized_time(sample.getSamplingDate())}
datalines.append(dataline)
analyses_count += 1
# Footer total data
footlines = []
footline = {'TotalCount': analyses_count}
footlines.append(footline)
self.report_data = {
'parameters': parms,
'datalines': datalines,
'footlines': footlines }
return {'report_title': _('Daily samples received'),
'report_data': self.template()}
示例11: Report
class Report(BrowserView):
implements(IViewView)
template = ViewPageTemplateFile("templates/qualitycontrol_referenceanalysisqc.pt")
# if unsuccessful we return here:
default_template = ViewPageTemplateFile("templates/qualitycontrol.pt")
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
def __call__(self):
MinimumResults = self.context.bika_setup.getMinimumResults()
warning_icon = "<img " +\
"src='"+self.portal_url+"/++resource++bika.lims.images/warning.png' " +\
"height='9' width='9'/>"
error_icon = "<img " +\
"src='"+self.portal_url+"/++resource++bika.lims.images/exclamation.png' " +\
"height='9' width='9'/>"
header = _("Reference analysis QC")
subheader = _("Reference analysis quality control graphs ")
self.contentFilter = {'portal_type': 'ReferenceAnalysis',
'review_state': ['verified', 'published'],
}
self.parms = []
titles = []
sample_uid = self.request.form.get('ReferenceSampleUID', '')
sample = self.reference_catalog.lookupObject(sample_uid)
if not sample:
message = _("No reference sample was selected.")
self.context.plone_utils.addPortalMessage(message, 'error')
return self.default_template()
self.parms.append({'title':_("Reference Sample"),'value':sample.Title()})
titles.append(sample.Title())
service_uid = self.request.form.get('ReferenceServiceUID', '')
service = self.reference_catalog.lookupObject(service_uid)
if not service:
message = _("No analysis services were selected.")
self.context.plone_utils.addPortalMessage(message, 'error')
return self.default_template()
self.contentFilter['path'] = {"query": "/".join(sample.getPhysicalPath()),
"level" : 0 }
keyword = service.getKeyword()
unit = service.getUnit()
service_title = "%s (%s)" % (service.Title(), service.getKeyword())
try:
precision = str(service.getPrecision())
except:
precision = "2"
self.parms.append({'title':_("Analysis Service"),'value':service.Title()})
titles.append(service.Title())
val = self.selection_macros.parse_daterange(self.request,
'getDateVerified',
'DateVerified')
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
self.parms.append(val['parms'])
titles.append(val['titles'])
# GET min/max for range checking
proxies = self.bika_analysis_catalog(self.contentFilter)
if not proxies:
message = _("No analyses matched your query")
self.context.plone_utils.addPortalMessage(message, 'error')
return self.default_template()
## Compile a list with all relevant analysis data
analyses = []
out_of_range_count = 0
in_shoulder_range_count = 0
plot_data = ""
formatted_results = []
results = []
tabledata = []
for analysis in proxies:
analysis = analysis.getObject()
analyses.append(analysis)
try:
result = float(analysis.getResult())
except ValueError:
pass
results.append(result)
captured = self.ulocalized_time(analysis.getResultCaptureDate(), long_format=1)
analyst = analysis.getAnalyst()
title = analysis.getId()
formatted_result = str("%." + precision + "f")%result
formatted_results.append(formatted_result)
tabledata.append({_("Analysis"): title,
_("Result"): formatted_result,
_("Analyst"): analyst,
_("Captured"): captured})
#.........这里部分代码省略.........
示例12: Report
class Report(BrowserView):
implements(IViewView)
default_template = ViewPageTemplateFile("templates/productivity.pt")
template = ViewPageTemplateFile("templates/productivity_dataentrydaybook.pt")
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
def __call__(self):
parms = []
titles = []
# Apply filters
self.contentFilter = {'portal_type': 'AnalysisRequest'}
val = self.selection_macros.parse_daterange(self.request,
'getDateCreated',
_('Date Created'))
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
# Query the catalog and store results in a dictionary
ars = self.bika_catalog(self.contentFilter)
if not ars:
message = _("No Analysis Requests matched your query")
self.context.plone_utils.addPortalMessage(message, "error")
return self.default_template()
datalines = {}
footlines = {}
totalcreatedcount = len(ars)
totalreceivedcount = 0
totalpublishedcount = 0
totalanlcount = 0
totalreceptionlag = 0
totalpublicationlag = 0
for ar in ars:
ar = ar.getObject()
datecreated = ar.created()
datereceived = ar.getDateReceived()
datepublished = ar.getDatePublished()
receptionlag = 0
publicationlag = 0
anlcount = len(ar.getAnalyses())
dataline = {
"AnalysisRequestID": ar.getRequestID(),
"DateCreated": self.ulocalized_time(datecreated),
"DateReceived": self.ulocalized_time(datereceived),
"DatePublished": self.ulocalized_time(datepublished),
"ReceptionLag": receptionlag,
"PublicationLag": publicationlag,
"TotalLag": receptionlag + publicationlag,
"BatchID": ar.getBatch(),
"SampleID": ar.getSample().Title(),
"SampleType": ar.getSampleTypeTitle(),
"NumAnalyses": anlcount,
"ClientID": ar.aq_parent.id,
"Creator": ar.Creator(),
"Remarks": ar.getRemarks()
}
datalines[ar.getRequestID()] = dataline
totalreceivedcount += ar.getDateReceived() and 1 or 0
totalpublishedcount += ar.getDatePublished() and 1 or 0
totalanlcount += anlcount
totalreceptionlag += receptionlag
totalpublicationlag += publicationlag
# Footer total data
totalreceivedcreated_ratio = float(totalreceivedcount)/float(totalcreatedcount)
totalpublishedcreated_ratio = float(totalpublishedcount)/float(totalcreatedcount)
totalpublishedreceived_ratio = float(totalpublishedcount)/float(totalreceivedcount)
footline = {'Created': totalcreatedcount,
'Received': totalreceivedcount,
'Published': totalpublishedcount,
'ReceivedCreatedRatio': totalreceivedcreated_ratio,
'ReceivedCreatedRatioPercentage': ('{0:.0f}'.format(totalreceivedcreated_ratio*100))+"%",
'PublishedCreatedRatio': totalpublishedcreated_ratio,
'PublishedCreatedRatioPercentage': ('{0:.0f}'.format(totalpublishedcreated_ratio*100))+"%",
'PublishedReceivedRatio': totalpublishedreceived_ratio,
'PublishedReceivedRatioPercentage': ('{0:.0f}'.format(totalpublishedreceived_ratio*100))+"%",
'AvgReceptionLag': ('{0:.1f}'.format(totalreceptionlag/totalcreatedcount)),
'AvgPublicationLag': ('{0:.1f}'.format(totalpublicationlag/totalcreatedcount)),
'AvgTotalLag': ('{0:.1f}'.format((totalreceptionlag+totalpublicationlag)/totalcreatedcount)),
'NumAnalyses': totalanlcount
}
footlines['Total'] = footline;
self.report_data = {'parameters': parms,
'datalines': datalines,
#.........这里部分代码省略.........
示例13: Report
class Report(BrowserView):
implements(IViewView)
default_template = ViewPageTemplateFile("templates/productivity.pt")
template = ViewPageTemplateFile("templates/productivity_analysesperdepartment.pt")
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
def __call__(self):
parms = []
titles = []
# Apply filters
self.contentFilter = {'portal_type': 'Analysis'}
val = self.selection_macros.parse_daterange(self.request,
'getDateRequested',
_('Date Requested'))
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
val = self.selection_macros.parse_state(self.request,
'bika_analysis_workflow',
'getAnalysisState',
_('Analysis State'))
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
# Query the catalog and store results in a dictionary
analyses = self.bika_analysis_catalog(self.contentFilter)
if not analyses:
message = _("No analyses matched your query")
self.context.plone_utils.addPortalMessage(message, "error")
return self.default_template()
groupby = self.request.form.get('GroupingPeriod', '')
if (groupby != ''):
parms.append({"title": _("Grouping period"), "value": _(groupby)})
datalines = {}
footlines = {}
totalcount = len(analyses)
totalpublishedcount = 0
totalperformedcount = 0
for analysis in analyses:
analysis = analysis.getObject()
analysisservice = analysis.getService()
department = analysisservice.getDepartment().Title()
daterequested = analysis.created()
group = ''
if groupby == 'Day':
group = self.ulocalized_time(daterequested)
elif groupby == 'Week':
group = daterequested.strftime("%Y") + ", " + daterequested.strftime("%U")
elif groupby == 'Month':
group = daterequested.strftime("%B") + " " + daterequested.strftime("%Y")
elif groupby == 'Year':
group = daterequested.strftime("%Y")
else :
group = ''
dataline = {'Group': group, 'Requested': 0, 'Performed': 0, 'Published': 0, 'Departments': {} }
deptline = {'Department':department, 'Requested':0, 'Performed': 0, 'Published': 0 }
if (group in datalines):
dataline = datalines[group]
if (department in dataline['Departments']):
deptline = dataline['Departments'][department]
grouptotalcount = dataline['Requested']+1
groupperformedcount = dataline['Performed']
grouppublishedcount = dataline['Published']
depttotalcount = deptline['Requested']+1
deptperformedcount = deptline['Performed']
deptpubishedcount = deptline['Published']
workflow = getToolByName(self.context, 'portal_workflow')
arstate = workflow.getInfoFor(analysis.aq_parent, 'review_state', '')
if (arstate == 'published'):
deptpubishedcount += 1
grouppublishedcount += 1
totalpublishedcount += 1
if (analysis.getResult()):
deptperformedcount += 1
groupperformedcount += 1
totalperformedcount += 1
group_performedrequested_ratio = float(groupperformedcount)/float(grouptotalcount)
group_publishedperformed_ratio = groupperformedcount > 0 and float(grouppublishedcount)/float(groupperformedcount) or 0
anl_performedrequested_ratio = float(deptperformedcount)/float(depttotalcount)
anl_publishedperformed_ratio = deptperformedcount > 0 and float(deptpubishedcount)/float(deptperformedcount) or 0
#.........这里部分代码省略.........
示例14: Report
class Report(BrowserView):
implements(IViewView)
default_template = ViewPageTemplateFile("templates/productivity.pt")
template = ViewPageTemplateFile(
"templates/productivity_dailysamplesreceived.pt")
def __init__(self, context, request, report=None):
super(Report, self).__init__(context, request)
self.report = report
self.selection_macros = SelectionMacrosView(self.context, self.request)
def __call__(self):
parms = []
titles = []
self.contentFilter = {'portal_type': 'Sample',
'review_state': ['sample_received', 'expired',
'disposed'],
'sort_on': 'getDateReceived'}
val = self.selection_macros.parse_daterange(self.request,
'getDateReceived',
_('Date Received'))
if val:
self.contentFilter[val['contentFilter'][0]] = val['contentFilter'][1]
parms.append(val['parms'])
titles.append(val['titles'])
# Query the catalog and store results in a dictionary
samples = self.bika_catalog(self.contentFilter)
if not samples:
message = _("No samples matched your query")
self.context.plone_utils.addPortalMessage(message, "error")
return self.default_template()
datalines = []
analyses_count = 0
for sample in samples:
sample = sample.getObject()
# For each sample, retrieve the analyses and generate
# a data line for each one
analyses = sample.getAnalyses({})
for analysis in analyses:
analysis = analysis.getObject()
sd = sample.getSamplingDate()
dataline = {'AnalysisKeyword': analysis.getKeyword(),
'AnalysisTitle': analysis.getServiceTitle(),
'SampleID': sample.getSampleID(),
'SampleType': sample.getSampleType().Title(),
'SampleDateReceived': self.ulocalized_time(
sample.getDateReceived(), long_format=1),
'SampleSamplingDate': self.ulocalized_time(
sd, long_format=1) if sd else ''
}
datalines.append(dataline)
analyses_count += 1
# Footer total data
footlines = []
footline = {'TotalCount': analyses_count}
footlines.append(footline)
self.report_data = {
'parameters': parms,
'datalines': datalines,
'footlines': footlines}
if self.request.get('output_format', '') == 'CSV':
import csv
import StringIO
import datetime
fieldnames = [
'SampleID',
'SampleType',
'SampleSamplingDate',
'SampleDateReceived',
'AnalysisTitle',
'AnalysisKeyword',
]
output = StringIO.StringIO()
dw = csv.DictWriter(output, fieldnames=fieldnames)
dw.writerow(dict((fn, fn) for fn in fieldnames))
for row in datalines:
dw.writerow(row)
report_data = output.getvalue()
output.close()
date = datetime.datetime.now().strftime("%Y%m%d%H%M")
setheader = self.request.RESPONSE.setHeader
setheader('Content-Type', 'text/csv')
setheader("Content-Disposition",
"attachment;filename=\"dailysamplesreceived_%s.csv\"" % date)
self.request.RESPONSE.write(report_data)
else:
return {'report_title': _('Daily samples received'),
'report_data': self.template()}