<commit_before>from DateTime import DateTime
from Products.Archetypes.config import REFERENCE_CATALOG
from Products.CMFCore.WorkflowCore import WorkflowException
from Products.CMFCore.utils import getToolByName
from bika.lims.browser import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from bika.lims.utils import sendmail, encode_header
from email.Utils import formataddr
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from bika.lims.config import POINTS_OF_CAPTURE
from email.mime.text import MIMEText
from os.path import join
import App
from smtplib import SMTPRecipientsRefused
import Globals
import re

class Publish(BrowserView):
    """Pre/Re/Publish analysis requests"""
    ar_results = ViewPageTemplateFile("mailtemplates/analysisrequest_results.pt")

    def __init__(self, context, request, action, analysis_requests):
        self.context = context
        self.request = request
        # the workflow transition that invoked us
        self.action = action
        # the list of ARs that we will process.
        # Filter them here so we only publish those with verified analyses.
        workflow = getToolByName(self.context, 'portal_workflow')
        ARs_to_publish = []
        for ar in analysis_requests:
            if workflow.getInfoFor(ar, 'review_state') in ['verified', 'published']:
                ARs_to_publish.append(ar)
            else:
                if ar.getAnalyses(review_state='verified'):
                    ARs_to_publish.append(ar)
                else:
                    if ar.getAnalyses(review_state='published'):
                        ARs_to_publish.append(ar)
        self.analysis_requests = ARs_to_publish

    def __call__(self):

        rc = getToolByName(self.context, REFERENCE_CATALOG)
        workflow = getToolByName(self.context, 'portal_workflow')

        laboratory = self.context.bika_setup.laboratory
        BatchEmail = self.context.bika_setup.getBatchEmail()
        BatchFax = self.context.bika_setup.getBatchFax()

        # group analysis requests by contact
        ARs_by_contact = {}
        for ar in self.analysis_requests:
            contact_uid = ar.getContact().UID()
            if contact_uid not in ARs_by_contact:
                ARs_by_contact[contact_uid] = []
            ARs_by_contact[contact_uid].append(ar)

        for contact_uid, ars in ARs_by_contact.items():
            ars.sort()
            self.contact = ars[0].getContact()
            self.pub_pref = self.contact.getPublicationPreference()
            batch_size = 'email' in self.pub_pref and BatchEmail or \
                         'fax' in self.pub_pref and BatchFax or 1

            # send batches of ARs to each contact
            for b in range(0, len(ars), batch_size):
                self.batch = ars[b:b+batch_size]
                self.any_accredited = False
                self.any_drymatter = False
                # get all services from all requests in this batch into a
                # dictionary:
                #   {'Point Of Capture': {'Category': [service,service,...]}}
                self.services = {}
                for ar in self.batch:
                    if ar.getReportDryMatter():
                        self.any_drymatter = True
                    states = ("verified", "published")
                    for analysis in ar.getAnalyses(full_objects=True,
                                                   review_state=states):
                        service = analysis.getService()
                        poc = POINTS_OF_CAPTURE.getValue(service.getPointOfCapture())
                        cat = service.getCategoryTitle()
                        if poc not in self.services:
                            self.services[poc] = {}
                        if cat not in self.services[poc]:
                            self.services[poc][cat] = []
                        self.services[poc][cat].append(service)
                        if (service.getAccredited()):
                            self.any_accredited = True

                # compose and send email
                if 'email' in self.pub_pref:

                    # render template to utf-8
                    ar_results = self.ar_results().encode("utf-8")

                    # XXX
                    ar_debug_name = '%s_%s.html' % \
                        (self.analysis_requests[0].Title(), self.action)
                    open(join(Globals.INSTANCE_HOME,'var', ar_debug_name),
                                "w").write(ar_results)

                    mime_msg = MIMEMultipart('related')
                    mime_msg['Subject'] = self.get_mail_subject()
                    mime_msg['From'] = formataddr(
                        (encode_header(laboratory.getName()),
                         laboratory.getEmailAddress()))
                    mime_msg['To'] = formataddr(
                        (encode_header(self.contact.getFullname()),
                         self.contact.getEmailAddress()))<commit_msg>Don't write published html to file unless Plone is in debug mode.<commit_after>from DateTime import DateTime
from Products.Archetypes.config import REFERENCE_CATALOG
from Products.CMFCore.WorkflowCore import WorkflowException
from Products.CMFCore.utils import getToolByName
from bika.lims.browser import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from bika.lims.utils import sendmail, encode_header
from email.Utils import formataddr
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from bika.lims.config import POINTS_OF_CAPTURE
from email.mime.text import MIMEText
from os.path import join
import App
from smtplib import SMTPRecipientsRefused
import Globals
import re

class Publish(BrowserView):
    """Pre/Re/Publish analysis requests"""
    ar_results = ViewPageTemplateFile("mailtemplates/analysisrequest_results.pt")

    def __init__(self, context, request, action, analysis_requests):
        self.context = context
        self.request = request
        # the workflow transition that invoked us
        self.action = action
        # the list of ARs that we will process.
        # Filter them here so we only publish those with verified analyses.
        workflow = getToolByName(self.context, 'portal_workflow')
        ARs_to_publish = []
        for ar in analysis_requests:
            if workflow.getInfoFor(ar, 'review_state') in ['verified', 'published']:
                ARs_to_publish.append(ar)
            else:
                if ar.getAnalyses(review_state='verified'):
                    ARs_to_publish.append(ar)
                else:
                    if ar.getAnalyses(review_state='published'):
                        ARs_to_publish.append(ar)
        self.analysis_requests = ARs_to_publish

    def __call__(self):

        rc = getToolByName(self.context, REFERENCE_CATALOG)
        workflow = getToolByName(self.context, 'portal_workflow')

        laboratory = self.context.bika_setup.laboratory
        BatchEmail = self.context.bika_setup.getBatchEmail()
        BatchFax = self.context.bika_setup.getBatchFax()

        # group analysis requests by contact
        ARs_by_contact = {}
        for ar in self.analysis_requests:
            contact_uid = ar.getContact().UID()
            if contact_uid not in ARs_by_contact:
                ARs_by_contact[contact_uid] = []
            ARs_by_contact[contact_uid].append(ar)

        for contact_uid, ars in ARs_by_contact.items():
            ars.sort()
            self.contact = ars[0].getContact()
            self.pub_pref = self.contact.getPublicationPreference()
            batch_size = 'email' in self.pub_pref and BatchEmail or \
                         'fax' in self.pub_pref and BatchFax or 1

            # send batches of ARs to each contact
            for b in range(0, len(ars), batch_size):
                self.batch = ars[b:b+batch_size]
                self.any_accredited = False
                self.any_drymatter = False
                # get all services from all requests in this batch into a
                # dictionary:
                #   {'Point Of Capture': {'Category': [service,service,...]}}
                self.services = {}
                for ar in self.batch:
                    if ar.getReportDryMatter():
                        self.any_drymatter = True
                    states = ("verified", "published")
                    for analysis in ar.getAnalyses(full_objects=True,
                                                   review_state=states):
                        service = analysis.getService()
                        poc = POINTS_OF_CAPTURE.getValue(service.getPointOfCapture())
                        cat = service.getCategoryTitle()
                        if poc not in self.services:
                            self.services[poc] = {}
                        if cat not in self.services[poc]:
                            self.services[poc][cat] = []
                        self.services[poc][cat].append(service)
                        if (service.getAccredited()):
                            self.any_accredited = True

                # compose and send email
                if 'email' in self.pub_pref:

                    # render template to utf-8
                    ar_results = self.ar_results().encode("utf-8")

                    debug_mode = App.config.getConfiguration().debug_mode
                    if not debug_mode:
                        ar_debug_name = '%s_%s.html' % \
                            (self.analysis_requests[0].Title(), self.action)
                        open(join(Globals.INSTANCE_HOME,'var', ar_debug_name),
                             "w").write(ar_results)

                    mime_msg = MIMEMultipart('related')
                    mime_msg['Subject'] = self.get_mail_subject()
                    mime_msg['From'] = formataddr(
                        (encode_header(laboratory.getName()),
                         laboratory.getEmailAddress()))
                    mime_msg['To'] = formataddr(
                        (encode_header(self.contact.getFullname()),
                         self.contact.getEmailAddress()))
{'fraction_non_alphanumeric': 0.08221313072277421, 'fraction_numerical': 0.0011689070718877848, 'mean_word_length': 1.7998363785110445, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5421286', 'n_tokens_mistral': 2765, 'n_tokens_neox': 2626, 'n_words': 612}