codes(); if (!is_array($resp) || empty($resp['ok'])) { return 'skipped'; } if (empty($resp['enabled'])) { update_option('atcwc_inf_codes', array(), false); return 'off'; } $created = (array) get_option('atcwc_codes_created', array()); $disabled_us = (array) get_option('atcwc_codes_disabled', array()); // Impronta delle regole applicate a ogni coupon creato da noi: lo si // ritocca solo quando cambiano, cosi' una modifica fatta a mano dal // merchant non viene cancellata a ogni giro. $rules_applied = (array) get_option('atcwc_codes_rules', array()); $results = array(); $cache = array(); foreach ((array) ($resp['codes'] ?? array()) as $c) { $code = (string) $c['code']; $key = strtolower($code); $active = !empty($c['active']); $row = self::coupon_by_code($code); if (!$row) { if (!$active) { $results[] = array('code' => $code, 'state' => 'disabled'); continue; } $type = $c['discount_type'] ?? null; $value = (float) ($c['discount_value'] ?? 0); $rules = isset($c['rules']) && is_array($c['rules']) ? $c['rules'] : array(); if (!in_array($type, array('percentage', 'fixed'), true) || $value <= 0 || !self::create_coupon($code, $type, $value, $rules)) { $results[] = array('code' => $code, 'state' => 'error'); continue; } $created[] = $key; $rules_applied[$key] = self::rules_fingerprint($rules); $row = self::coupon_by_code($code); $results[] = array('code' => $code, 'state' => 'created', 'discount' => self::discount_label($row)); } elseif (!$active) { if ('publish' === $row['post_status']) { self::set_coupon_active((int) $row['ID'], false); $disabled_us[] = $key; } $results[] = array('code' => $code, 'state' => 'disabled', 'discount' => self::discount_label($row)); } else { if ('publish' !== $row['post_status'] && in_array($key, $disabled_us, true)) { self::set_coupon_active((int) $row['ID'], true); $disabled_us = array_values(array_diff($disabled_us, array($key))); } // Regole cambiate in piattaforma: si aggiornano i coupon creati // da noi. Con una piattaforma che non le manda non si tocca nulla. if (in_array($key, $created, true) && isset($c['rules']) && is_array($c['rules'])) { $print = self::rules_fingerprint($c['rules']); if (($rules_applied[$key] ?? null) !== $print) { $coupon = new WC_Coupon((int) $row['ID']); self::apply_rules($coupon, $c['rules']); if ($coupon->save()) { $rules_applied[$key] = $print; } } } $results[] = array('code' => $code, 'state' => in_array($key, $created, true) ? 'created' : 'linked', 'discount' => self::discount_label($row)); } if ($active) { $entry = array('code' => $code, 'referral_code' => $c['referral_code'] ?? null, 'orders_year' => (int) ($c['orders_year'] ?? 0)); // Con cosa si puo' usare insieme (0.21.0): solo per i coupon // creati da noi, gli unici a cui valgono le regole. Lo legge // il controllo nel carrello (check_combination). if (in_array($key, $created, true) && isset($c['rules']) && is_array($c['rules'])) { $entry['combine'] = self::combine_flags($c['rules']); } $cache[] = $entry; } } // Un codice tolto a un influencer e dato a un altro compare in tutte e // due le liste: vale quello in uso, il coupon non si spegne. $in_use = array_map(static function ($c) { return strtolower((string) $c['code']); }, (array) ($resp['codes'] ?? array())); foreach ((array) ($resp['retired'] ?? array()) as $code) { if (in_array(strtolower((string) $code), $in_use, true)) { continue; } $row = self::coupon_by_code((string) $code); if ($row && 'publish' === $row['post_status']) { self::set_coupon_active((int) $row['ID'], false); $disabled_us[] = strtolower((string) $code); } $results[] = array('code' => (string) $code, 'state' => 'disabled'); } update_option('atcwc_codes_created', array_values(array_unique($created)), false); update_option('atcwc_codes_disabled', array_values(array_unique($disabled_us)), false); update_option('atcwc_inf_codes', $cache, false); update_option('atcwc_codes_rules', array_intersect_key($rules_applied, array_flip(array_unique($created))), false); if ($results) { $api->codes_sync($results); } $recovered = 0; foreach ((array) ($resp['recover'] ?? array()) as $r) { $recovered += self::send_recovery($api, (string) $r['code'], (string) ($r['since'] ?? gmdate('Y') . '-01-01')); } return array('synced' => count($results), 'recovered_orders' => $recovered); } /* Codici sconto dell'ordine, nell'ordine in cui sono stati applicati: con due codici di influencer diversi vince il primo. */ public static function order_codes(WC_Order $order) { return array_values(array_filter(array_map('strval', $order->get_coupon_codes()))); } /* Vero se l'ordine usa uno dei codici degli influencer in uso (elenco aggiornato a ogni manutenzione): quegli ordini partono anche senza cookie, perche' il codice vince sul link. */ public static function has_influencer_code(WC_Order $order) { $codes = array_map('strtolower', self::order_codes($order)); if (!$codes) { return false; } $known = array_map(static function ($c) { return strtolower((string) $c['code']); }, (array) get_option('atcwc_inf_codes', array())); return (bool) array_intersect($codes, $known); } /** * Codice dell'influencer per "Il mio account", con lo sconto com'e' * davvero nel negozio. Codice e ordini arrivano al momento con il * riepilogo; se la piattaforma non li manda si usa l'elenco della * manutenzione. Coupon spento o mancante: niente riquadro. */ public static function for_affiliate($referral_code, $summary_r) { if (is_array($summary_r) && array_key_exists('discount_code', $summary_r)) { $live = $summary_r['discount_code']; $list = is_array($live) && !empty($live['code']) ? array(array('code' => $live['code'], 'referral_code' => $referral_code, 'orders_year' => (int) ($live['orders_year'] ?? 0))) : array(); } else { $list = (array) get_option('atcwc_inf_codes', array()); } foreach ($list as $c) { if (strtolower((string) ($c['referral_code'] ?? '')) !== strtolower((string) $referral_code)) { continue; } $row = self::coupon_by_code((string) $c['code']); if (!$row || 'publish' !== $row['post_status']) { return null; } $coupon = new WC_Coupon((int) $row['ID']); $expires = $coupon->get_date_expires(); return array( 'code' => (string) $c['code'], 'percent' => 'percent' === $coupon->get_discount_type(), 'amount' => (float) $coupon->get_amount(), 'orders' => (int) ($c['orders_year'] ?? 0), 'expires' => $expires ? $expires->getTimestamp() : null, ); } return null; } /* Coupon con quel codice, acceso o spento. Il confronto e' quello di MySQL, senza maiuscole, come fa WooCommerce quando il cliente lo scrive. Il cestino non conta: un coupon cestinato e' come non averlo. */ private static function coupon_by_code($code) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- serve anche il coupon in bozza, che wc_get_coupon_id_by_code() non trova. $row = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_status FROM {$wpdb->posts} WHERE post_type = 'shop_coupon' AND post_title = %s AND post_status IN ('publish', 'draft', 'pending', 'private', 'future') ORDER BY post_status = 'publish' DESC, ID DESC LIMIT 1", $code ), ARRAY_A ); return $row ? $row : null; } private static function set_coupon_active($id, $active) { wp_update_post(array('ID' => (int) $id, 'post_status' => $active ? 'publish' : 'draft')); } /* Con cosa il coupon si puo' usare insieme: gli sconti COIN e gli altri coupon del negozio. `combinable` e' la forma della piattaforma 0.74.0 (una scelta sola, valeva per tutto). */ private static function combine_flags(array $rules) { $all = !empty($rules['combinable']); return array( 'coin' => isset($rules['combinable_coin']) ? (bool) $rules['combinable_coin'] : $all, 'other' => isset($rules['combinable_other']) ? (bool) $rules['combinable_other'] : $all, ); } /** * Il coupon si puo' usare insieme a quelli gia' nel carrello? (0.21.0) * * WooCommerce conosce solo "uso individuale": o il coupon sta da solo, o * si somma a tutto. Il negoziante sceglie invece due cose distinte per i * coupon degli influencer creati da noi: se accettano accanto uno sconto * COIN e se accettano un altro coupon del negozio. Qui si rifiuta il * coupon arrivato DOPO, con il motivo: quello gia' nel carrello resta. * Vale solo per il carrello del cliente, non per gli ordini modificati * in wp-admin. * * @param bool $valid Esito finora. * @param WC_Coupon $coupon Coupon che si sta controllando. * @param WC_Discounts $discounts Contesto del controllo. * @throws Exception Con il messaggio per il cliente. */ public static function check_combination($valid, $coupon, $discounts = null) { if (!$valid || !($coupon instanceof WC_Coupon)) { return $valid; } $object = is_object($discounts) && method_exists($discounts, 'get_object') ? $discounts->get_object() : null; if (!($object instanceof WC_Cart)) { return $valid; } $flags = array(); foreach ((array) get_option('atcwc_inf_codes', array()) as $c) { if (isset($c['combine']) && is_array($c['combine'])) { $flags[strtolower((string) $c['code'])] = $c['combine']; } } if (!$flags) { return $valid; } $new = strtolower((string) $coupon->get_code()); $applied = array_map('strtolower', array_map('strval', $object->get_applied_coupons())); $pos = array_search($new, $applied, true); // Conta solo chi e' arrivato prima: cosi' al ricontrollo del carrello // non saltano tutti e due. $before = false === $pos ? $applied : array_slice($applied, 0, (int) $pos); foreach ($before as $old) { foreach (array(array($new, $old), array($old, $new)) as $pair) { if (!isset($flags[$pair[0]])) { continue; } $kind = 0 === strpos($pair[1], 'coin-') ? 'coin' : 'other'; if (empty($flags[$pair[0]][$kind])) { /* translators: %s: discount code already in the cart */ throw new Exception(esc_html(sprintf(__('This coupon cannot be used together with %s.', 'affiliatetracker-connector'), strtoupper($old)))); } } } return $valid; } private static function rules_fingerprint(array $rules) { ksort($rules); return md5((string) wp_json_encode($rules)); } /* Regole scelte dal negoziante in piattaforma, sul coupon. Chiavi assenti = le regole fisse di sempre. */ private static function apply_rules(WC_Coupon $coupon, array $rules) { $min = isset($rules['min_amount']) ? (float) $rules['min_amount'] : 0; $limit = isset($rules['usage_limit']) ? (int) $rules['usage_limit'] : 0; $per = isset($rules['usage_per_customer']) ? (int) $rules['usage_per_customer'] : 0; $expires = isset($rules['expires_on']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) $rules['expires_on']) ? (string) $rules['expires_on'] : null; // Il coupon non sconta i prodotti in offerta. $coupon->set_exclude_sale_items(!empty($rules['exclude_discounted'])); $coupon->set_minimum_amount($min > 0 ? wc_format_decimal($min) : ''); // Valido fino alla fine del giorno indicato (ora del sito). $coupon->set_date_expires($expires ? $expires . ' 23:59:59' : null); // WooCommerce conta gli utilizzi a parte: qui va il tetto, 0 = nessuno. $coupon->set_usage_limit(max(0, $limit)); $coupon->set_usage_limit_per_user(max(0, $per)); // "Uso individuale" (da solo, con nessun altro coupon) solo se il // negoziante non lo vuole abbinare a niente. Se sceglie una sola // delle due (sconti COIN, altri coupon) lo decide check_combination. $combine = self::combine_flags($rules); $coupon->set_individual_use(!$combine['coin'] && !$combine['other']); // Vale solo se il negozio ha un metodo di spedizione gratuita che // richiede un coupon. $coupon->set_free_shipping(!empty($rules['free_shipping'])); } private static function create_coupon($code, $type, $value, array $rules = array()) { $coupon = new WC_Coupon(); $coupon->set_code($code); /* translators: %s: discount code */ $coupon->set_description(sprintf(__('Influencer code %s', 'affiliatetracker-connector'), $code)); $coupon->set_discount_type('percentage' === $type ? 'percent' : 'fixed_cart'); $coupon->set_amount('percentage' === $type ? min(100, (float) $value) : (float) $value); self::apply_rules($coupon, $rules); $coupon->set_status('publish'); return (int) $coupon->save(); } private static function discount_label($row) { if (!$row) { return null; } $coupon = new WC_Coupon((int) $row['ID']); $amount = (float) $coupon->get_amount(); if ($amount <= 0) { return null; } if ('percent' === $coupon->get_discount_type()) { return rtrim(rtrim(number_format($amount, 2, ',', ''), '0'), ',') . '%'; } return number_format($amount, 2, ',', '.') . ' ' . get_woocommerce_currency(); } /* Ordini fatti con il codice dalla data richiesta, a lotti da 100, poi `done`. Se un lotto non passa ci si ferma: al prossimo giro la piattaforma richiede il recupero e si ricomincia (i doppioni li scarta). */ private static function send_recovery($api, $code, $since) { global $wpdb; $from = strtotime($since); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- i coupon dell'ordine stanno solo qui, sia con HPOS sia senza. $ids = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT order_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_item_type = 'coupon' AND order_item_name = %s ORDER BY order_id", $code ) ); $batch = array(); $orders = array(); $sent = 0; foreach ((array) $ids as $oid) { $order = wc_get_order((int) $oid); if (!$order instanceof WC_Order || in_array($order->get_status(), array('trash', 'checkout-draft'), true)) { continue; } $created = $order->get_date_created(); if (!$created || $created->getTimestamp() < $from) { continue; } $payload = Atcwc_Orders::payload($order, $order->get_meta('_atcwc_ref'), $order->get_meta('_atcwc_camp')); $payload['date'] = $created->date('c'); $batch[] = $payload; $orders[] = $order; if (100 === count($batch)) { $r = $api->codes_recovery($code, $batch, false); if (empty($r['ok'])) { return $sent; } self::mark_recovered($orders, $batch); $sent += count($batch); $batch = array(); $orders = array(); } } $r = $api->codes_recovery($code, $batch, true); if (empty($r['ok'])) { return $sent; } self::mark_recovered($orders, $batch); return $sent + count($batch); } /* Un ordine recuperato ora la piattaforma lo conosce: da qui in poi i cambi di stato (annullo, rimborso) devono arrivarle come per gli ordini tracciati, altrimenti la commissione recuperata resterebbe approvata anche dopo un rimborso. */ private static function mark_recovered(array $orders, array $payloads) { foreach ($orders as $i => $order) { if ($order->get_meta('_atcwc_sent')) { continue; } $order->update_meta_data('_atcwc_tracked', '1'); $order->update_meta_data('_atcwc_sent', '1'); $order->update_meta_data('_atcwc_state', $payloads[$i]['state']); $order->save(); } } }