productRepository = $productRepository; $this->logger = $logger; } /** * Add cost variables before processing template */ public function beforeProcessTemplate($subject, array $variables = []) { if (!$this->isProcessing) { $this->logger->info('TemplatePlugin: beforeProcessTemplate called'); // Check if we have an order in variables if (isset($variables['order']) && $variables['order'] instanceof Order) { $this->logger->info('TemplatePlugin: Found order ' . $variables['order']->getIncrementId()); $variables = $this->addCostVariables($variables, $variables['order']); } } return [$variables]; } /** * Hook into setVars to add our variables */ public function afterSetVars($subject, $result, $variables) { // Only process once to avoid infinite loop if (!$this->isProcessing && is_array($variables) && isset($variables['order']) && $variables['order'] instanceof Order) { $this->isProcessing = true; $this->logger->info('TemplatePlugin: afterSetVars called - adding cost variables'); // Add cost variables $enhancedVariables = $this->addCostVariables($variables, $variables['order']); // Set variables back $subject->setVars($enhancedVariables); $this->isProcessing = false; } return $result; } /** * Add cost variables to the variables array */ protected function addCostVariables($variables, $order) { // Check if we already added these variables if (isset($variables['items_html'])) { $this->logger->info('Cost variables already exist, skipping'); return $variables; } try { // Build ONLY the table rows (tbody content) $itemsHtml = ''; $totalCost = 0; $itemCount = 0; foreach ($order->getAllVisibleItems() as $item) { $itemCount++; try { $product = $this->productRepository->getById($item->getProductId()); $cost = (float)($product->getCost() ?: $product->getData('cost') ?: 0); $this->logger->info('Product ' . $item->getSku() . ' cost: ' . $cost); } catch (\Exception $e) { $this->logger->error('Could not load product: ' . $e->getMessage()); $cost = 0; } $qty = (float) $item->getQtyOrdered(); $rowTotal = $cost * $qty; $totalCost += $rowTotal; // Just the row content $itemsHtml .= '
| Item | '; $completeTableHtml .= 'SKU | '; $completeTableHtml .= 'Qty | '; $completeTableHtml .= 'Unit Cost | '; $completeTableHtml .= 'Total Cost | '; $completeTableHtml .= '
|---|---|---|---|---|
| Subtotal: | '; $completeTableHtml .= '' . $this->formatPrice($totalCost, $order) . ' | '; $completeTableHtml .= '|||
| Shipping: | '; $completeTableHtml .= '' . $this->formatPrice($shippingCost, $order) . ' | '; $completeTableHtml .= '|||
| Grand Total: | '; $completeTableHtml .= '' . $this->formatPrice($totalCost + $shippingCost, $order) . ' | '; $completeTableHtml .= '|||