render_brand_margins_card($nonce, $ajax); } private static function cogs_feature_enabled() { try { $cls = 'Automattic\\WooCommerce\\Internal\\CostOfGoodsSold\\CostOfGoodsSoldController'; if (function_exists('wc_get_container') && class_exists($cls)) { $ctrl = wc_get_container()->get($cls); if (is_object($ctrl) && method_exists($ctrl, 'feature_is_enabled')) { return (bool) $ctrl->feature_is_enabled(); } } } catch (\Throwable $e) { } return false; } private static function fmt_pct($v) { if ($v === null || $v === '') { return ''; } return rtrim(rtrim(number_format((float) $v, 2, '.', ''), '0'), '.'); } private function render_brand_margins_card($nonce, $ajax) { $default_margin = (int) round(AIEO_DMM::get_gross_margin_pct()); $cogs_on = self::cogs_feature_enabled(); $export_url = $ajax . '?action=aieo_dmm_tools_export_brand_margins&nonce=' . rawurlencode($nonce); global $wpdb; $n_products = 0; if ($cogs_on) { $n_products = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type IN ('product','product_variation') AND post_status IN ('publish','private')"); } list($open, $close) = AIEO_DMM_UI::card(array( 'anchor' => 'brand-margins-cost-of-goods', 'title' => __('Apply margins to Cost of Goods', 'ai-eshop-optimizer'), 'description' => sprintf(__('Set a gross profit margin per brand (Brands → edit → Catalog tab). Brands without one inherit the store default (%d%%). Export to review/bulk-edit margins in a spreadsheet, re-import to apply, then push them into WooCommerce Cost of Goods — cost = regular price × (1 − margin).', 'ai-eshop-optimizer'), $default_margin), )); echo $open; $export = \Rooster\Admin\Ui::button(__('Export brand margins (CSV)', 'ai-eshop-optimizer'), array('href' => $export_url, 'icon' => 'download')); $pick = \Rooster\Admin\Ui::button(__('Import margins (CSV)…', 'ai-eshop-optimizer'), array('icon' => 'upload', 'attrs' => array('id' => 'aieo-bm-import-pick'))); echo '
' . $export . ' ' . \Rooster\Admin\Ui::file( '', array( 'id' => 'aieo-bm-file', 'accept' => '.csv,text/csv,text/plain', 'hidden' => true, 'labelledby' => 'aieo-bm-import-pick' ) ) . ' ' . $pick . '
'; echo ''; $csv = \Rooster\Admin\Guidance::text(__('CSV columns: brand_id, brand, slug, products, margin_percent. Matched by brand_id (then slug). A blank margin_percent = inherit the default.', 'ai-eshop-optimizer')); echo $csv; echo rooster_admin_card_section_html(); $apply_note = \Rooster\Admin\Guidance::text(__('Sets Cost of Goods only on products that don’t have one yet (never overwrites existing/manual costs), and refreshes the product-vitals cost. Runs in batches and fires product-save hooks — run it off-peak. Re-runnable.', 'ai-eshop-optimizer'), 'guidance', array('question' => __('What does applying change?', 'ai-eshop-optimizer'))); echo $apply_note; $job = \Rooster\Admin\States::job(array( 'id' => 'aieo-bm-apply-job', 'state' => 'idle', 'run' => __('Apply margins → Cost of Goods', 'ai-eshop-optimizer'), 'run_attrs' => array('id' => 'aieo-bm-apply'), 'confirm' => $cogs_on ? 'aieo-bm-apply-confirm' : '', 'disabled' => !$cogs_on, 'reason' => $cogs_on ? '' : __('WooCommerce “Cost of Goods Sold” is not enabled — turn it on in WooCommerce → Settings → Advanced → Features before applying.', 'ai-eshop-optimizer'), )); echo $job; if ($cogs_on) { $ask = \Rooster\Admin\States::confirm( 'aieo-bm-apply-confirm', 'replace', __('Apply margins to Cost of Goods?', 'ai-eshop-optimizer'), '' . esc_html(sprintf( _n('Goes through %s product and sets its cost from its brand’s margin when it has none yet.', 'Goes through %s products and sets each cost from its brand’s margin when it has none yet.', $n_products, 'ai-eshop-optimizer'), number_format_i18n($n_products) )) . '
' . esc_html__('Costs already set are never overwritten. It runs in batches and can take a while.', 'ai-eshop-optimizer') . '
', array('confirm' => __('Apply', 'ai-eshop-optimizer')) ); echo $ask; } echo $close; echo ''; } public function ajax_export_brand_margins() { AIEO_DMM::verify_ajax_request(); if (!class_exists('AIEO_DMM_Brand_Extras_Data')) { wp_die(esc_html__('Brand Extras unavailable.', 'ai-eshop-optimizer')); } $tax = 'product_brand'; $terms = get_terms(array('taxonomy' => $tax, 'hide_empty' => false)); nocache_headers(); header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=brand-margins-' . gmdate('Ymd-His') . '.csv'); $out = fopen('php://output', 'w'); fwrite($out, "\xEF\xBB\xBF"); fputcsv($out, array('brand_id', 'brand', 'slug', 'products', 'margin_percent', 'effective_percent'), ',', '"', ''); if (!is_wp_error($terms)) { foreach ($terms as $t) { $row = AIEO_DMM_Brand_Extras_Data::get($tax, $t->term_id); $eff = AIEO_DMM_Brand_Extras_Data::effective_margin_pct($t->term_id, $tax); fputcsv($out, array( (int) $t->term_id, $t->name, $t->slug, (int) $t->count, self::fmt_pct($row['gross_margin']), self::fmt_pct($eff), ), ',', '"', ''); } } fclose($out); exit; } public function ajax_import_brand_margins() { AIEO_DMM::verify_ajax_request(); if (empty($_FILES['file']['tmp_name']) || !is_uploaded_file($_FILES['file']['tmp_name'])) { wp_send_json_error(array('message' => __('No file uploaded.', 'ai-eshop-optimizer'))); } $fh = fopen($_FILES['file']['tmp_name'], 'r'); if (!$fh) { wp_send_json_error(array('message' => __('Could not read the file.', 'ai-eshop-optimizer'))); } $tax = 'product_brand'; $updated = 0; $cleared = 0; $unmatched = 0; $rownum = 0; $col = array(); while (($cells = fgetcsv($fh, 0, ',', '"', '')) !== false) { $rownum++; if ($rownum === 1) { $cells[0] = preg_replace('/^\xEF\xBB\xBF/', '', (string) $cells[0]); } if ($rownum === 1 && !ctype_digit(trim((string) ($cells[0] ?? '')))) { foreach ($cells as $i => $h) { $col[strtolower(trim((string) $h))] = $i; } continue; } $cell = static function ($name, $pos) use ($cells, $col) { if (isset($col[$name]) && isset($cells[$col[$name]])) { return (string) $cells[$col[$name]]; } return isset($cells[$pos]) ? (string) $cells[$pos] : ''; }; $bid = (int) $cell('brand_id', 0); $slug = trim($cell('slug', 2)); $margin = trim($cell('margin_percent', 4)); $term = null; if ($bid > 0) { $t = get_term($bid, $tax); if ($t && !is_wp_error($t)) { $term = $t; } } if (!$term && $slug !== '') { $t = get_term_by('slug', $slug, $tax); if ($t) { $term = $t; } } if (!$term) { $unmatched++; continue; } $margin = str_replace(array('%', ','), array('', '.'), $margin); if ($margin === '') { AIEO_DMM_Brand_Extras_Data::save($tax, (int) $term->term_id, array('gross_margin' => null)); $cleared++; } else { AIEO_DMM_Brand_Extras_Data::save($tax, (int) $term->term_id, array('gross_margin' => (float) $margin)); $updated++; } } fclose($fh); wp_send_json_success(array( 'message' => sprintf( __('Imported — %1$d updated, %2$d set to inherit, %3$d unmatched.', 'ai-eshop-optimizer'), $updated, $cleared, $unmatched ), )); } public function ajax_apply_cogs() { AIEO_DMM::verify_ajax_request(); if (!self::cogs_feature_enabled()) { wp_send_json_error(array('message' => __('Cost of Goods Sold is not enabled in WooCommerce.', 'ai-eshop-optimizer'))); } if (!function_exists('wc_get_product') || !class_exists('AIEO_DMM_Brand_Extras_Data')) { wp_send_json_error(array('message' => __('WooCommerce / Brand Extras unavailable.', 'ai-eshop-optimizer'))); } $offset = isset($_POST['offset']) ? max(0, (int) $_POST['offset']) : 0; @set_time_limit(0); self::suppress_bulk_product_save_hooks(); wp_send_json_success(self::apply_cogs_batch($offset, 150)); } public static function suppress_bulk_product_save_hooks() { $deny = apply_filters('aieo_cogs_bulk_hook_denylist', array( 'Recommendations_Cache', 'Recompute_Queue', 'Core_Brand_Vitals', 'AIEO_DMM_Product_FP', 'AIEO_DMM_Navigator', 'Embedding_Manager', 'DgoraWcas', 'FiboFilters', 'AutomateWoo', 'AIOSEO', 'PixelYourSite', 'Pods', )); $hooks = array('save_post_product', 'woocommerce_update_product', 'woocommerce_new_product', 'woocommerce_process_product_meta', 'save_post', 'updated_post_meta'); foreach ($hooks as $h) { if (empty($GLOBALS['wp_filter'][$h]) || empty($GLOBALS['wp_filter'][$h]->callbacks)) { continue; } foreach ($GLOBALS['wp_filter'][$h]->callbacks as $prio => $cbs) { foreach ($cbs as $key => $cb) { $fn = isset($cb['function']) ? $cb['function'] : null; $cls = is_array($fn) ? (is_object($fn[0]) ? get_class($fn[0]) : (string) $fn[0]) : (is_string($fn) ? $fn : ''); if ($cls === '') { continue; } foreach ($deny as $needle) { if (stripos($cls, $needle) !== false) { unset($GLOBALS['wp_filter'][$h]->callbacks[$prio][$key]); break; } } } } } } public static function apply_cogs_batch($offset, $batch = 150) { global $wpdb; $offset = max(0, (int) $offset); $batch = max(1, (int) $batch); $total = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type IN ('product','product_variation') AND post_status IN ('publish','private')"); $ids = $wpdb->get_col($wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type IN ('product','product_variation') AND post_status IN ('publish','private') ORDER BY ID ASC LIMIT %d OFFSET %d", $batch, $offset )); $vitals = $wpdb->prefix . 'aieo_core_product_vitals'; $have_vitals = ((string) $wpdb->get_var("SHOW TABLES LIKE '{$vitals}'") === $vitals); $updated = 0; $skipped = 0; foreach ((array) $ids as $pid) { $pid = (int) $pid; $product = wc_get_product($pid); if (!$product || $product->is_type('variable')) { $skipped++; continue; } $existing = $product->get_cogs_value(); if ($existing !== null && (float) $existing > 0) { $skipped++; continue; } $base = (float) $product->get_regular_price(); if ($base <= 0) { $base = (float) $product->get_price(); } if ($base <= 0) { $skipped++; continue; } $margin = AIEO_DMM_Brand_Extras_Data::margin_pct_for_product($pid); $cost = round($base * (1 - $margin / 100), 2); if ($cost <= 0) { $skipped++; continue; } $product->set_cogs_value($cost); $product->save(); if ($have_vitals) { $wpdb->query($wpdb->prepare("UPDATE `{$vitals}` SET cost = %f WHERE product_id = %d", $cost, $pid)); } $updated++; } $next = $offset + $batch; $done = (count((array) $ids) < $batch) || $next >= $total; return array( 'updated' => $updated, 'skipped' => $skipped, 'next_offset' => $next, 'total' => $total, 'done' => $done, ); } }