NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

public function emailView()
{
try {

// 🔴 FIX 1: Kill any IMAP output leakage
ob_start();

$client = Client::account('gmail');
$client->connect();

$folder = $client->getFolder('INBOX');

$messages = $folder->query()->unseen()->get();

// 🔴 FIX 2: REMOVE dd(), use log only
Log::info('Unseen email count', ['count' => $messages->count()]);

if ($messages->count() === 0) {

// 🔴 FIX 3: Clean buffer before response
ob_end_clean();

return response()->json([
'status' => 'info',
'message' => 'No unseen emails found.'
]);
}

$emails = [];
$workorderdata = null;

foreach ($messages as $message) {

$attachments = $message->getAttachments();

$senderEmail = $message->from->first()->mail;
$date = $message->date->first();
$formattedDate = $date->format('Y-m-d H:i:s');
$senderName = $message->from->first()->personal;

foreach ($attachments as $attachment) {

if ($attachment->getExtension() == 'pdf') {

$filename = $attachment->getName();
$path = 'attachments/' . $message->getMsglist() . '_' . $filename;

Storage::disk('public')->put($path, $attachment->getContent());

$parser = new Parser();
$absolutePath = Storage::disk('public')->path($path);
$pdf = $parser->parseFile($absolutePath);
$fullText = $pdf->getText();

$tokens = array_map('trim', preg_split('/R/', $fullText));

$raw_field = $tokens[50] ?? '';
preg_match('/^([a-zA-Zs]*)([0-9].*)$/', $raw_field, $matches);

$extracted_name = $matches[1] ?? '';
$extracted_address = $matches[2] ?? $raw_field;

$final_contact = empty($extracted_name) ? 'null' : trim($extracted_name);

$data = [
'PRISM ID:' => $tokens[5] ?? 'Not Found',
'PO #:' => $tokens[6] ?? 'Not Found',
'Const Type:' => $tokens[7] ?? 'Not Found',
'Work Order Date:' => $tokens[8] ?? 'Not Found',
'Vendor Name:' => $tokens[9] ?? 'Not Found',
'Work Order #:' => $tokens[17] ?? 'Not Found',
'PO Amount:' => '1659.62',
'Const Coordinator:' => $tokens[14] ?? 'Not Found',
'Est. Completion:' => $tokens[15] ?? 'Not Found',
'Issued By:' => $tokens[16] ?? 'Not Found',
'Job' => trim(($tokens[21] ?? '') . ' ' . ($tokens[22] ?? '')),
'Job Address' => trim($extracted_address . ' ' . ($tokens[24] ?? '')),
'Site Contact Name' => $final_contact,
'Site Phone' => $tokens[25] ?? 'Not Found',
'Comments:' => $tokens[26] ?? 'Not Found',
];

preg_match('/PO Amount:s*([d.]+)/i', $fullText, $matches);
if (!empty($matches[1])) {
$data['PO Amount:'] = $matches[1];
}

preg_match_all(
'/^s*([^s]+)s+(.*?)s+([0-9.]+)s+([^s]+)s+([0-9.]+)s+([0-9.]+)s*$/im',
$fullText,
$matches,
PREG_SET_ORDER
);

$inventoryItems = [];

foreach ($matches as $match) {
$inventoryItems[] = [
'Code' => $match[1],
'Description' => $match[2],
'Quantity' => (int) $match[3],
'UOM' => $match[4],
'Rate' => (float) $match[5],
'Amount' => (float) $match[6],
];
}

if (!empty($inventoryItems)) {
$dataToInsert = collect($inventoryItems)->map(function ($item) {
return [
'item_code' => $item['Code'],
'item_description' => $item['Description'],
'quantity' => $item['Quantity'],
'item_UOM' => $item['UOM'],
'item_rate' => $item['Rate'],
'total_amount' => $item['Amount'],
'created_by' => Auth::id(),
'updated_by' => Auth::id(),
'created_at' => now(),
'updated_at' => now(),
];
})->toArray();
}

$workOrder = [
'prism_id' => $data['PRISM ID:'],
'workorder_prism_id' => $data['Work Order #:'],
'po_number' => $data['PO #:'],
'po_amount' => $data['PO Amount:'],
'vendor_name' => $data['Vendor Name:'],
'workorder_sender_email' => $senderEmail,
'recived_date_time' => $formattedDate,
'details' => $dataToInsert ?? [],
];

$workorderdata = $this->storeWorkOrderData($workOrder);
}
}

// 🔴 FIX 4: Mark seen ONLY after successful processing
if ($workorderdata) {
$message->setFlag('Seen');
}
}

// 🔴 FIX 5: Clean buffer before success response
ob_end_clean();

return response()->json([
'status' => 'success',
'message' => 'Emails processed successfully.',
'data' => $workorderdata
]);

} catch (Exception $e) {

ob_end_clean();

Log::error($e->getMessage());

return response()->json([
'status' => 'error',
'message' => 'Emails processed failed.'
]);
}
}
     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.