false, 'error' => 'Missing parameters']); exit; } $db->begin(); // Hole das neueste Produkt dieser Rechnung (höchster rang) $sql = "SELECT rowid, rang FROM ".MAIN_DB_PREFIX."facturedet"; $sql .= " WHERE fk_facture = ".(int)$facture_id; $sql .= " ORDER BY rang DESC LIMIT 1"; $resql = $db->query($sql); if (!$resql || $db->num_rows($resql) == 0) { $db->rollback(); echo json_encode(['success' => false, 'error' => 'Kein Produkt gefunden']); exit; } $product = $db->fetch_object($resql); $product_id = $product->rowid; subtotaltitle_debug_log(' → Neustes Produkt: #' . $product_id . ' (rang=' . $product->rang . ')'); // Prüfe ob schon in Manager-Tabelle $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture_lines_manager"; $sql .= " WHERE fk_facturedet = ".(int)$product_id; $resql = $db->query($sql); if ($db->num_rows($resql) == 0) { // Produkt fehlt - hinzufügen $next_order = 1; $sql_max = "SELECT MAX(line_order) as max_order FROM ".MAIN_DB_PREFIX."facture_lines_manager"; $sql_max .= " WHERE fk_facture = ".(int)$facture_id; $resql_max = $db->query($sql_max); if ($obj = $db->fetch_object($resql_max)) { $next_order = ($obj->max_order ? $obj->max_order + 1 : 1); } $sql_ins = "INSERT INTO ".MAIN_DB_PREFIX."facture_lines_manager"; $sql_ins .= " (fk_facture, line_type, fk_facturedet, parent_section, line_order, date_creation)"; $sql_ins .= " VALUES (".(int)$facture_id.", 'product', ".(int)$product_id.", ".(int)$section_id.", ".$next_order.", NOW())"; $db->query($sql_ins); subtotaltitle_debug_log(' → Produkt zu Manager-Tabelle hinzugefügt (line_order=' . $next_order . ')'); } else { // Produkt existiert - UPDATE parent_section subtotaltitle_debug_log('🔵🔵🔵 assign_last_product: Produkt #'.$product_id.' → parent_section='.$section_id); $sql_upd = "UPDATE ".MAIN_DB_PREFIX."facture_lines_manager"; $sql_upd .= " SET parent_section = ".(int)$section_id; $sql_upd .= " WHERE fk_facturedet = ".(int)$product_id; $db->query($sql_upd); subtotaltitle_debug_log(' → parent_section updated'); } // Neu sortieren require_once DOL_DOCUMENT_ROOT.'/custom/subtotaltitle/class/actions_subtotaltitle.class.php'; $hook = new ActionsSubtotalTitle($db); $reflection = new ReflectionClass($hook); $method = $reflection->getMethod('reorderLines'); $method->setAccessible(true); $method->invoke($hook, $facture_id); $method = $reflection->getMethod('syncRangFromManager'); $method->setAccessible(true); $method->invoke($hook, $facture_id); $db->commit(); subtotaltitle_debug_log('✅ Assignment erfolgreich'); echo json_encode(['success' => true, 'product_id' => $product_id]);