Error in Invoice Generation

User
{
"success": false,
"result": "error",
"message": "Error in create zip reportUndefined array key "data""
}
foreach ($request->ids as $id)
{
$cryptID=Crypt::encrypt($id);

$filename=$pdfController->generateInvoice($cryptID,1);

if(file_exists('/home/u923455722/domains/webholzer.in/public_html/public/pdfs/invoices/'.$filename))
{
$files[]='/home/u923455722/domains/webholzer.in/public_html/public/pdfs/invoices/'.$filename; // Example file path

}
//break;
}

public function generateInvoice($paymentID, $savePdf='')
{

$paymentID = Crypt::decrypt($paymentID);

$paymentDetails=Payments::find($paymentID);
$project_id=$paymentDetails->project_id;
$order_id=$paymentDetails->order_id;
$projects=Project::where(['id'=>$project_id])->first();

$getCorporatedesign = getCorporatedesign($project_id);
// pre($getCorporatedesign); die;

if($getCorporatedesign['details']) {
if($getCorporatedesign['details']['corporatedesign'] == 'client') {
$client_id = $getCorporatedesign['details']['id'] ?? '0';
$clientno = sprintf('%03d', $client_id);
} else {
$coach_id = $getCorporatedesign['details']['id'] ?? '0';
$clientno = sprintf('%03d', $coach_id);
}

$salutation = $getCorporatedesign['details']['salutation'];
$first_name = $getCorporatedesign['details']['first_name'];
$last_name = $getCorporatedesign['details']['last_name'];
$fullname = $salutation.' '.$first_name.' '.$last_name;

$company_name = $getCorporatedesign['details']['company_name'];
$address = ($getCorporatedesign['details']['address1'] ?? '')." ".($getCorporatedesign['details']['address2'] ?? '');
$city = $getCorporatedesign['details']['city'];
$zip_code = $getCorporatedesign['details']['zip_code'];
$country_id = $getCorporatedesign['details']['country_id'];
$country = getCountryName($country_id) ?? 'Germany';
}

$invoices=[];
$projectInvoiceDetails = $projects->paymentInvoiceDetails($paymentID);
$invoices[] = $projectInvoiceDetails;

$invoice_date = convertDateTimeToFormatDate($paymentDetails->transaction_date_time);
$invoice_number = date("Y/m/d",strtotime($paymentDetails->transaction_date_time))."/".$clientno.'/'.$paymentDetails->invoice_number;

// Manual Testing
$langId = 1; // 1: English, 3: German
$vat_comp = '';

$html="";

$html.="

<style>
body{ background:url(/img/invoice_bg.jpg) no-repeat center center; background-size: 1000px 500px;height:100vh;font-family: 'SwitzerRegular', sans-serif;}
        .table_invoice{ width:1080px; margin:100px auto 100px; font-family:'SwitzerRegular', sans-serif; font-size:16px; line-height:24px;padding:0px 40px}

        table.table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
        }
        table.table thead tr, table.table tfoot tr {
            background-color: white;
            border-radius: 20px;
            padding: 0px;
        }
        table.table thead tr th{text-align:left; padding:10px 5px}
        table.table tfoot tr td{text-align:left; padding:10px 5px; font-weight:bold;}  

        table.table  td{     color: #090607;}
  
        table.table  tbody tr {
            padding: 10px 0; 
        }

        table.table  tbody td {
            padding: 20px 5px; 
        }

        table.table  tbody tr + tr {
            margin-top: 10px; 
        }
      
        table.table thead th:first-child, tfoot td:first-child {
            border-top-left-radius: 20px;
            border-bottom-left-radius: 20px;
        }
        table.table thead th:last-child, table.table tfoot td:last-child {
            border-top-right-radius: 20px;
            border-bottom-right-radius: 20px;
        }
        table.table  tbody td {
            padding: 10px 20px;
        }
      
        .cardBtn{  color:#fff; color:#fff; font-size:24px; border-radius:30px; text-decoration:none;
            background:#1f75ff; padding:10px 40px; font-weight:bold;
        }
</style>

";
$html.='

';

if($langId == 1) {

$html .= '

##Company_Name##
'.$first_name.' '.$last_name.''.$address.''.$zip_code." ".$city.''.$country.'

INVOICE

Customer ID
'.$clientno.'

Invoice number
'.$invoice_number.'

Invoice date
'.$invoice_date.'
';
if($vat_comp!=''){
$html .= '
VAT
'.$vat_comp.'
';
}
$html .= '

Hi '.$fullname.'

Thank you for choosing feedback4you GmbH. We have prepared an invoice for the following services:

Service
Order ID
QTY
Price/unit
Net
VAT
Gross

';
$netTotal = '0';
$grossTotal = '0';
foreach ($invoices as $inv)
{
if(is_array($inv) && !is_null($inv))
{
$netTotal = ($inv['number_of_participants'] * $inv['perUnitPrice']);
$grossTotal = ($netTotal + $inv['vat_amount']);
if($inv['coupon_value'] > 0) {
$grossTotal = (($netTotal – $inv['coupon_value']) + $inv['vat_amount']);
}

$html .= '
'.$inv['project_name'].'
'.$inv['order_id'].'
'.$inv['number_of_participants'].'
'.euroFormat($inv['perUnitPrice'], true).'
'.euroFormat($netTotal, true).'
'.euroFormat($inv['vat_amount'], true).'
'.euroFormat($grossTotal, true).'
';
}
}
if($inv['coupon_value'] > 0) {
$html .= '

Coupon Applied
 
 
'.euroFormat($inv['coupon_value'], true).'
';
}
$html .= '

Total
'.euroFormat($netTotal, true).'
'.euroFormat($inv['vat_amount'], true).'
'.euroFormat($grossTotal, true).'

';

if($country!='Germany'){
$html .= 'Reverse-Charge';
}
$html .= ' The service date corresponds with the invoice date.
The payment will be processed through electronic payment method:

'.ucfirst($paymentDetails->payment_method).'

If you have any questions or require assistance, our customer service is here to help:
##Email##

This is an automatically generated invoice and is valid without a manual signature.

';
} else {
$html .= '

##Company_Name##
'.$first_name.' '.$last_name.''.$address.''.$zip_code." ".$city.''.$country.'

INVOICE

Kundennummer
'.$clientno.'

Rechnungsnummer
'.$invoice_number.'

Rechnungsdatum
'.$invoice_date.'
';
if($vat_comp!=''){
$html .= '
USt-IdNr.
'.$vat_comp.'
';
}
$html .= '

Hallo '.$fullname.'

Vielen Dank, dass Sie sich für die feedback4you GmbH entschieden haben. Wir haben eine Rechnung für die folgenden Leistungen vorbereit:

Leistung
Bestell-ID
Menge
Preis/Einhei
Netto
MwSt.
Brutto

';
$netTotal = '0';
$grossTotal = '0';
foreach ($invoices as $inv)
{
if(is_array($inv) && !is_null($inv))
{
$netTotal = ($inv['number_of_participants'] * $inv['perUnitPrice']);
$grossTotal = ($netTotal + $inv['vat_amount']);
if($inv['coupon_value'] > 0) {
$grossTotal = (($netTotal – $inv['coupon_value']) + $inv['vat_amount']);
}

$html .= '
'.$inv['project_name'].'
'.$inv['order_id'].'
'.$inv['number_of_participants'].'
'.euroFormat($inv['perUnitPrice'], true).'
'.euroFormat($netTotal, true).'
'.euroFormat($inv['vat_amount'], true).'
'.euroFormat($grossTotal, true).'
';
}
}
if($inv['coupon_value'] > 0) {
$html .= '

Gutschein angewendet
 
 
'.euroFormat($inv['coupon_value'], true).'
';
}
$html .= '

Gesamtbetrag
'.euroFormat($netTotal, true).'
'.euroFormat($inv['vat_amount'], true).'
'.euroFormat($grossTotal, true).'

Das Leistungsdatum entspricht dem Rechnungsdatum.
Die Zahlung wird über ein elektronisches Zahlungsmittelabgewickelt.

Credit Card

Falls Sie Fragen haben oder Unterstützung benötigen, steht Ihnen unser Kundenservice gerne zur Verfügung:
##Email##

Dies ist eine automatisch generierte Rechnung und ist ohne Unterschrift gültig.

';

}

$html .= '

';

$find = array("##Company_Name##","##Address1##","##Pincode##","##CityName##","##Phone##","##Email##","##Country##");
$replace = array($company_name,'Stefan-George-Ring 24','D-81929','Munchen',"+49 89 12 50 90 528","billing@feedback4you.com","Germany");
$html = str_replace($find, $replace, $html);
$mpdf = app('mpdf');
$mpdf->SetDisplayMode('fullpage');

//echo $html; die();

$header = '';
$footer = '

feedback4you GmbH
VAT: DE123451234

Birkenfeldstr. 8
85649 Brunnthal
Germany
billing@feedback4you.com

Sparkasse Freising Moosburg
IBAN: DE30 7005 1003 0026 1254 92
BIC: BYLADEM1FSI

';

//$mpdf->WriteHTML($stylesheet, 1);
$mpdf->SetHTMLHeader($header, '', true);
$mpdf->SetHTMLFooter($footer);

$mpdf->WriteHTML($html);

// Output the PDF (inline in the browser)
// Output PDF as a string
$pdfContent = $mpdf->Output('', 'S');
//$filename = date('Ymd').'_invoice_report.pdf';
$filename = $order_id.'_invoice.pdf';

if($savePdf == '1') {
//echo $html; die();

$storagePath = public_path('pdfs/invoices');
file_put_contents($storagePath . '/' . $filename, $pdfContent);

return $filename;

} else {
// Return PDF response
return Response::make($pdfContent, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="' . $filename . '"',
]);
}
}

Assistant
The error you're encountering indicates an issue with the array key `data` being undefined when processing the request. Based on the provided code, here are a few steps to help identify and resolve the problem:

### **Potential Issues**
1. **Undefined `data` key in `$getCorporatedesign`**
The function `getCorporatedesign($project_id)` might not always return an array containing the key `details`. If it's `null` or missing keys, it can cause the error. Check the structure and ensure that `$getCorporatedesign['details']` exists before accessing its keys.

2. **Invoice data not being generated correctly**
The `paymentInvoiceDetails($paymentID)` function in the `$projects` model might not return the expected structure or could be missing data.

3. **Empty `$invoices` array**
If the `$invoices` array is empty, operations like accessing `$inv['coupon_value']` will fail.

4. **File paths and file existence**
Ensure that files are being generated correctly and exist at the specified path. A missing file might lead to an empty `$files` array.

### **Debugging Steps**
1. **Validate `getCorporatedesign` Output**
Add a debug check:

$getCorporatedesign = getCorporatedesign($project_id);
   if (!is_array($getCorporatedesign) || !isset($getCorporatedesign['details'])) {
       return response()->json(['success' => false, 'message' => 'Invalid corporate design data.']);
   }

2. **Validate `paymentInvoiceDetails`**
Before using `$projectInvoiceDetails`:

if (empty($projectInvoiceDetails) || !is_array($projectInvoiceDetails)) {
       return response()->json(['success' => false, 'message' => 'Invoice details not found for payment ID: ' . $paymentID]);
   }

3. **Check File Existence Before Adding**
Verify file paths:

$filePath = '/home/u923455722/domains/webholzer.in/public_html/public/pdfs/invoices/'.$filename;
   if (!file_exists($filePath)) {
       return response()->json(['success' => false, 'message' => 'File not found: ' . $filePath]);
   }

4. **Handle Undefined Keys in `$inv`**
Ensure `$inv` contains all expected keys:

foreach ($invoices as $inv) {
       if (!isset($inv['project_name'], $inv['order_id'], $inv['number_of_participants'], $inv['perUnitPrice'], $inv['vat_amount'])) {
           return response()->json(['success' => false, 'message' => 'Missing data in invoice details.']);
       }
   }

### **Revised Code Snippets**

#### Handling `getCorporatedesign`

$getCorporatedesign = getCorporatedesign($project_id);
if (!is_array($getCorporatedesign) || !isset($getCorporatedesign['details'])) {
    $getCorporatedesign['details'] = [
        'corporatedesign' => 'default',
        'id' => '0',
        'salutation' => '',
        'first_name' => '',
        'last_name' => '',
        'company_name' => '',
        'address1' => '',
        'address2' => '',
        'city' => '',
        'zip_code' => '',
        'country_id' => null,
    ];
}

#### Validate Invoice Data

$projectInvoiceDetails = $projects->paymentInvoiceDetails($paymentID);
if (!$projectInvoiceDetails) {
    return response()->json(['success' => false, 'message' => 'No invoice details found.']);
}
$invoices[] = $projectInvoiceDetails;

#### Secure File Path Handling

$filePath = '/home/u923455722/domains/webholzer.in/public_html/public/pdfs/invoices/' . $filename;
if (file_exists($filePath)) {
    $files[] = $filePath;
} else {
    return response()->json(['success' => false, 'message' => 'File not found: ' . $filePath]);
}

### **Next Steps**
– Debug and log outputs to identify where the process fails:

Log::info('Debug Data', ['getCorporatedesign' => $getCorporatedesign, 'invoices' => $invoices]);

– Ensure that all edge cases for missing or malformed data are handled gracefully.

With these changes, you should be able to pinpoint the issue and ensure the process completes successfully. Let me know if you need further clarification!

User
save mdf in folder
Assistant
To save the generated PDF (`mdf` in your context) in a specific folder, you can use a PDF generation library like Dompdf or TCPDF. Here's a streamlined process to save the PDF file in your desired folder:

### Steps:

1. **Generate PDF content**:
Ensure the `$html` content is prepared correctly, as shown in your example.

2. **Use a PDF generation library**:
For this example, we'll use **Dompdf**, which is simple and effective.

3. **Save the PDF file**:
Use the `stream` or `output` method provided by Dompdf to save the file.

### Code Example

use DompdfDompdf;
use DompdfOptions;
use IlluminateSupportFacadesFile;

public function generateInvoice($paymentID, $savePdf = '')
{
    $paymentID = Crypt::decrypt($paymentID);
    
    // Prepare invoice data as per your existing logic
    $paymentDetails = Payments::find($paymentID);
    $project_id = $paymentDetails->project_id;
    $order_id = $paymentDetails->order_id;
    $projects = Project::where(['id' => $project_id])->first();
    
    $html = '<h1>Invoice Content Goes Here</h1>'; // Your existing HTML generation logic here

    // Configure Dompdf
    $options = new Options();
    $options->set('isHtml5ParserEnabled', true);
    $options->set('isRemoteEnabled', true);

    $dompdf = new Dompdf($options);
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();

    // Save PDF to a specific folder
    $output = $dompdf->output();

    // Specify the folder path
    $folderPath = public_path('pdfs/invoices'); // Example: `/public/pdfs/invoices`

    // Create folder if it doesn't exist
    if (!File::exists($folderPath)) {
        File::makeDirectory($folderPath, 0755, true, true);
    }

    // Define file name
    $fileName = 'invoice_' . $paymentDetails->invoice_number . '.pdf';
    $filePath = $folderPath . '/' . $fileName;

    // Save the file
    file_put_contents($filePath, $output);

    // Return file path for further use
    return $fileName;
}

### Key Points

1. **File Path**:
– The PDF file will be saved in `/public/pdfs/invoices/`. Adjust this path according to your project structure.

2. **Folder Creation**:
– If the folder does not exist, it's created dynamically using Laravel's `File` facade.

3. **Return Value**:
– The method returns the filename. You can modify it to return the full path or any other response needed.

4. **Dependencies**:
– Install Dompdf via Composer:

composer require dompdf/dompdf

Let me know if you need help integrating this code!

Leave a Comment

Your email address will not be published. Required fields are marked *