Untitled

 avatar
unknown
plain_text
a year ago
9.0 kB
1
Indexable
# First Tab: eDoc Tool
class OutlookDropTarget(wx.FileDropTarget):
    def __init__(self, window):
        wx.FileDropTarget.__init__(self)
        self.window = window

    def OnDropFiles(self, x, y, filenames):
        # This function is triggered when files are dropped onto the eDoc Tool window.
        # It sets the attachment path in the window and updates the file label.
        if filenames:
            file_path = filenames[0]
            self.window.attachment_path = file_path
            self.window.update_file_label()

class OutlookApp(wx.Panel):
    def __init__(self, parent, *args, **kw):
        super(OutlookApp, self).__init__(parent, *args, **kw)

        # Initialize variables for attachment path and clipboard
        self.attachment_path = None
        self.last_clipboard = None

        # Set up the user interface for the eDoc Tool
        self.setup_ui()

    def setup_ui(self):
        # Create a vertical box sizer to arrange elements vertically
        sizer = wx.BoxSizer(wx.VERTICAL)

        # Add an instruction label
        instruction_label = wx.StaticText(self, label="Press Windows+Shift+S to take a screenshot of CW references, then press the button to insert them below.")
        sizer.Add(instruction_label, 0, wx.ALL, 10)

        # Add space between the instruction label and the Capture Screenshot button
        sizer.Add((0, 0), 1)  # Add a spacer to remove the space

        # Add Capture Screenshot button
        capture_button = wx.Button(self, label="Insert CW references from screenshot")
        capture_button.Bind(wx.EVT_BUTTON, self.on_capture)
        sizer.Add(capture_button, 0, wx.ALIGN_CENTER | wx.ALL, 10)

        # Set up Tesseract OCR path and environment variable
        # pytesseract.pytesseract.tesseract_cmd = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tesseract', 'tesseract.exe')  # When compiling EXE
        # pytesseract.pytesseract.tesseract_cmd = r'C:\Users\ArthurBalan\Documents\Tools\Tesseract-OCR\tesseract.exe'         # When using on my PC
        # os.environ['TESSDATA_PREFIX'] = r'C:\Users\ArthurBalan\Documents\Tools\Tesseract-OCR\tessdata'                      # When using on my PC       

        # Add label for entering shipment numbers
        label_shipment_numbers = wx.StaticText(self, label="Enter shipment numbers (one per line):")
        sizer.Add(label_shipment_numbers, 0, wx.ALL, 10)

        # Add a text box for entering shipment numbers
        self.text_box_shipment_numbers = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_WORDWRAP, size=(150, 150))
        sizer.Add(self.text_box_shipment_numbers, 0, wx.EXPAND | wx.ALL, 10)

        # Create a horizontal box sizer to arrange elements horizontally
        hsizer = wx.BoxSizer(wx.HORIZONTAL)

        # Add labels and dropdowns for selecting CW file type and document type
        label_cw_file_type = wx.StaticText(self, label="Select CW file type:")
        hsizer.Add(label_cw_file_type, 0, wx.ALL, 10)

        choices_cw_file_type = ["BKG: Bookings", "SHP: Shipments"]
        self.combo_cw_file_type = wx.Choice(self, choices=choices_cw_file_type)
        hsizer.Add(self.combo_cw_file_type, 0, wx.ALL, 10)

        label_document_type = wx.StaticText(self, label="Select document type:")
        hsizer.Add(label_document_type, 0, wx.ALL, 10)

        choices_document_type = ["BKC - Booking confirmation", "BKG - Booking request",
                                  "CIV - Commercial invoice", "PKG - Packing list", "EMA - Email"]
        self.combo_document_type = wx.Choice(self, choices=choices_document_type)
        hsizer.Add(self.combo_document_type, 0, wx.ALL, 10)

        sizer.Add(hsizer, 0, wx.EXPAND | wx.ALL, 10)

        # Add button for browsing or dragging and dropping files
        self.drop_area_button = wx.Button(self, label="Browse or Drag and Drop File", size=(200, 130))
        self.drop_area_button.Bind(wx.EVT_BUTTON, self.on_browse_file)
        self.drop_area_button.SetDropTarget(OutlookDropTarget(self))
        sizer.Add(self.drop_area_button, 0, wx.EXPAND | wx.ALL, 10)

        # Add buttons for preparing and sending drafts to Outlook
        button_prepare_draft = wx.Button(self, label="Send draft to Outlook", size=(300, 60))
        button_prepare_draft.Bind(wx.EVT_BUTTON, self.on_send_to_outlook)
        sizer.Add(button_prepare_draft, 0, wx.ALIGN_CENTER | wx.ALL, 10)

        button_send_and_confirm = wx.Button(self, label="Send directly to CW as eDoc (USE WITH CAUTION!)", size=(300, 60))
        button_send_and_confirm.Bind(wx.EVT_BUTTON, self.on_send_and_confirm)
        sizer.Add(button_send_and_confirm, 0, wx.ALIGN_CENTER | wx.ALL, 10)

        # Set the panel sizer
        self.SetSizerAndFit(sizer)

    def on_capture(self, event):
        # This function captures the clipboard data, extracts text using Tesseract OCR,
        # and cleans the text before setting it in the shipment numbers text box.
        win32clipboard.OpenClipboard()
        try:
            clipboard_data = win32clipboard.GetClipboardData(win32clipboard.CF_BITMAP)
            if clipboard_data:
                image = ImageGrab.grabclipboard()
                if image:
                    extracted_text = pytesseract.image_to_string(image, config='--psm 6')

                    # Post-processing to remove non-alphanumeric characters
                    cleaned_text = re.sub(r'[^a-zA-Z0-9\n ]', '', extracted_text)

                    # Split the cleaned text into individual words
                    words = cleaned_text.split()

                    # Extract references starting with 'SV' and display them one per line
                    references_starting_with_sv = [ref.strip() for ref in words if ref.startswith('SV')]

                    # Set the cleaned text in the shipment numbers text box
                    self.text_box_shipment_numbers.SetValue('\n'.join(references_starting_with_sv))
        except TypeError:
            print("Clipboard data is not in CF_BITMAP format")
        finally:
            win32clipboard.CloseClipboard()

    def on_send_to_outlook(self, event):
        # This function sends emails with selected parameters to Outlook.
        self.send_emails(display_only=True)

    def on_send_and_confirm(self, event):
        # This function sends emails with selected parameters to Outlook and displays a confirmation dialog.
        self.send_emails(display_only=False)
        self.button_send_and_confirm.Enable()  # Re-enable the button after sending emails

    def send_emails(self, display_only):
        # This function prepares and sends emails to Outlook with selected parameters.
        shipment_numbers = self.text_box_shipment_numbers.GetValue().splitlines()
        cw_file_type = self.combo_cw_file_type.GetString(self.combo_cw_file_type.GetSelection())
        document_type = self.combo_document_type.GetString(self.combo_document_type.GetSelection())

        if cw_file_type and document_type and self.attachment_path:
            outlook = win32com.client.Dispatch('Outlook.Application')

            # Display a confirmation dialog
            if not display_only:
                confirm_dialog = wx.MessageDialog(self, "Are you sure you want to send these emails?", "Confirm Send", wx.YES_NO | wx.ICON_QUESTION)
                if confirm_dialog.ShowModal() != wx.ID_YES:
                    return  # If the user does not confirm, stop here

            for reference in shipment_numbers:
                reference = reference.strip()
                if reference:
                    email_subject = "[ediDocManager {} {} {}]".format(cw_file_type.split(':')[0], document_type.split('-')[0].strip(), reference)

                    mail = outlook.CreateItem(0)
                    mail.To = 'email@email.com'
                    mail.Subject = email_subject
                    mail.HTMLBody = "<p></p>"
                    mail.Attachments.Add(self.attachment_path)

                    if not display_only:
                        mail.Send()  # Send the email
                    else:
                        mail.Display()  # Just display the email

            wx.MessageBox("Emails processed successfully!", "Success", wx.OK | wx.ICON_INFORMATION)
        else:
            wx.MessageBox("Please select CW file type, document type, and drop a file.", "Error", wx.OK | wx.ICON_ERROR)

    def on_browse_file(self, event):
        # This function opens a file dialog for browsing files and updates the attachment path.
        with wx.FileDialog(self, "Open", wildcard="All files (*.*)|*.*", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:
            if fileDialog.ShowModal() == wx.ID_CANCEL:
                return
            self.attachment_path = fileDialog.GetPath()
            self.update_file_label()

    def update_file_label(self):
        # This function updates the label on the drop area button with the current attachment path.
        self.drop_area_button.SetLabel(self.attachment_path)
Leave a Comment