$items['customer-logout']) : array(); unset($items['customer-logout']); $items[self::ENDPOINT] = __('Affiliate program', 'affiliatetracker-connector'); return $items + $logout; } private static function mapping($user_id) { $ref = get_user_meta($user_id, '_atcwc_referral_code', true); return $ref ? array( 'id' => get_user_meta($user_id, '_atcwc_affiliate_id', true), 'ref' => $ref, 'type' => get_user_meta($user_id, '_atcwc_type', true), 'status' => get_user_meta($user_id, '_atcwc_status', true), ) : null; } // Per le azioni (link, conversione COIN): la copia sull'utente, aggiornata // dalla piattaforma a ogni apertura della pagina, purche' l'affiliato sia // attivo. Stato vuoto = copia salvata prima della 0.17.0. private static function active_mapping($user_id) { $map = self::mapping($user_id); return ($map && in_array($map['status'], array('approved', ''), true)) ? $map : null; } private static function store_mapping($user_id, array $aff) { update_user_meta($user_id, '_atcwc_affiliate_id', $aff['id']); update_user_meta($user_id, '_atcwc_referral_code', $aff['referral_code']); update_user_meta($user_id, '_atcwc_type', $aff['type']); update_user_meta($user_id, '_atcwc_status', $aff['status'] ?? ''); } private static function clear_mapping($user_id) { foreach (array('_atcwc_affiliate_id', '_atcwc_referral_code', '_atcwc_type', '_atcwc_status') as $k) { delete_user_meta($user_id, $k); } } /** * L'affiliato del cliente loggato secondo la piattaforma, che e' la fonte * autorevole: i dati salvati sull'utente sono solo una copia. Senza * questa lettura un influencer creato dal merchant in dashboard (mai * candidato da qui, quindi senza copia) si vedeva proporre la * candidatura, e uno rifiutato o eliminato continuava a vedere la * dashboard. Se la piattaforma non risponde si usa la copia, purche' non * sia in attesa o rifiutata: meglio una dashboard con i numeri a zero che * la candidatura a chi e' gia' affiliato. * * @return array|null mapping + 'status' + 'live' (riga della piattaforma) */ private static function resolve($user) { $local = self::mapping($user->ID); $api = atcwc_api(); $live = $api->get_affiliate_by_customer((string) $user->ID, $user->user_email); if ($live && !empty($live['referral_code'])) { self::store_mapping($user->ID, $live); $map = self::mapping($user->ID); $map['live'] = $live; return $map; } if ($api->last_failed()) { if ($local && !in_array($local['status'], array('pending', 'rejected', 'suspended'), true)) { $local['status'] = 'approved'; } return $local; } if ($local) { self::clear_mapping($user->ID); } return null; } public static function handle_post() { if (empty($_POST['atcwc_action'])) { return; } if (!isset($_POST['atcwc_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['atcwc_nonce'])), 'atcwc_account')) { wp_die(esc_html__('The link you followed has expired. Please reload the page and try again.', 'affiliatetracker-connector'), '', array('response' => 403)); } // Ogni azione riguarda solo l'account di chi la fa: basta essere un // utente registrato con la capacita' minima `read`. if (!is_user_logged_in() || !current_user_can('read')) { wp_die(esc_html__('You must be logged in to do this.', 'affiliatetracker-connector'), '', array('response' => 403)); } $user = wp_get_current_user(); $action = sanitize_key(wp_unslash($_POST['atcwc_action'])); if ('apply' === $action && !self::resolve($user)) { // Il consenso ai termini si verifica anche qui: `required` sul // checkbox e' solo un aiuto del browser. if (empty($_POST['terms'])) { wc_add_notice(__('You must accept the terms of the affiliate program.', 'affiliatetracker-connector'), 'error'); wp_safe_redirect(wc_get_account_endpoint_url(self::ENDPOINT)); exit; } $type = ('influencer' === sanitize_key(wp_unslash($_POST['type'] ?? ''))) ? 'influencer' : 'customer'; if ('customer' === $type) { $settings = atcwc_api()->settings(); if ($settings && empty($settings['enable_customer_affiliation'])) { wc_add_notice(__('Customer affiliate applications are not available at the moment.', 'affiliatetracker-connector'), 'error'); wp_safe_redirect(wc_get_account_endpoint_url(self::ENDPOINT)); exit; } } $resp = atcwc_api()->create_affiliate(array( 'type' => $type, 'email' => $user->user_email, 'display_name' => $user->display_name, 'external_customer_id' => (string) $user->ID, )); if ($resp && isset($resp['affiliate']['id'])) { self::store_mapping($user->ID, $resp['affiliate'] + array('type' => $type, 'status' => 'pending')); wc_add_notice(__('Application sent! You will receive a confirmation once it is approved.', 'affiliatetracker-connector')); } else { wc_add_notice(__('Submission failed, please try again later.', 'affiliatetracker-connector'), 'error'); } } if ('create_link' === $action) { $map = self::active_mapping($user->ID); $label = sanitize_text_field(wp_unslash($_POST['link_label'] ?? '')); if ($map && '' !== $label) { $resp = atcwc_api()->create_link($map['ref'], $label); if ($resp && isset($resp['link']['slug'])) { wc_add_notice(__('Link created!', 'affiliatetracker-connector')); } else { wc_add_notice(__('Link creation failed, please try again.', 'affiliatetracker-connector'), 'error'); } } } if ('convert' === $action) { $map = self::active_mapping($user->ID); $coins = absint(wp_unslash($_POST['coins'] ?? 0)); if ($map && $coins > 0) { $api = atcwc_api(); $req = $api->request_discount($map['ref'], $coins); if ($req && isset($req['request']['id'])) { $code = Atcwc_Orders::create_coupon( (float) $req['request']['value_eur'], $user->ID, (int) ($req['request']['expiry_days'] ?? 365), !isset($req['request']['single_use']) || $req['request']['single_use'] ); if ($code) { $api->confirm_discount($req['request']['id'], 'created', $code); /* translators: %s: discount code */ wc_add_notice(sprintf(__('Discount created! Your code: %s', 'affiliatetracker-connector'), $code)); } else { $api->confirm_discount($req['request']['id'], 'failed'); wc_add_notice(__('Error creating the discount, your COIN have been refunded.', 'affiliatetracker-connector'), 'error'); } } elseif ($req && 'insufficient_balance' === ($req['error'] ?? '')) { wc_add_notice(__('Insufficient COIN balance.', 'affiliatetracker-connector'), 'error'); } elseif ($req && 'below_min_convert' === ($req['error'] ?? '')) { /* translators: %d: minimum COIN balance */ wc_add_notice(sprintf(__('You need at least %d COIN to generate a discount.', 'affiliatetracker-connector'), (int) $req['min']), 'error'); } else { wc_add_notice(__('Conversion failed, please try again later.', 'affiliatetracker-connector'), 'error'); } } } if ('payout' === $action) { self::handle_payout($user); } wp_safe_redirect(wc_get_account_endpoint_url(self::ENDPOINT)); exit; } /** * Dati per il bonifico (piattaforma 0.73.10+). Solo influencer: gli * affiliati clienti sono pagati in COIN. Il controllo dell'IBAN (formato, * lunghezza per paese, cifra di controllo) lo fa la piattaforma, che e' * anche quella che li usa: qui si ripulisce l'input e si traducono gli * errori. */ private static function handle_payout($user) { // phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce verificato in handle_post() prima di arrivare qui. $map = self::active_mapping($user->ID); if (!$map || 'influencer' !== $map['type'] || empty($map['id'])) { return; } $remove = !empty($_POST['atcwc_payout_remove']); $iban = $remove ? '' : sanitize_text_field(wp_unslash($_POST['payout_iban'] ?? '')); $holder = $remove ? '' : sanitize_text_field(wp_unslash($_POST['payout_holder'] ?? '')); // phpcs:enable WordPress.Security.NonceVerification.Missing // Un IBAN vuoto per la piattaforma vuol dire "cancella": dal modulo di // modifica e' quasi sempre una dimenticanza, quindi si cancella solo // col pulsante apposta. if (!$remove && '' === trim($iban)) { wc_add_notice(__('Enter the IBAN of the account where you want to receive payments.', 'affiliatetracker-connector'), 'error'); return; } $resp = atcwc_api()->update_payout_details($map['id'], $iban, $holder); $error = is_array($resp) ? ($resp['error'] ?? '') : ''; if ($resp && !empty($resp['ok'])) { wc_add_notice($remove ? __('Payment details removed.', 'affiliatetracker-connector') : __('Payment details saved.', 'affiliatetracker-connector')); } elseif ('invalid_iban' === $error) { wc_add_notice(__('The IBAN is not valid. Check it and try again.', 'affiliatetracker-connector'), 'error'); } elseif ('holder_required' === $error) { wc_add_notice(__('Enter the name of the account holder.', 'affiliatetracker-connector'), 'error'); } else { wc_add_notice(__('Saving failed, please try again later.', 'affiliatetracker-connector'), 'error'); } } /** Solo paese e ultime quattro cifre, come nella dashboard: IT•• •••• 3456. */ private static function mask_iban($iban) { $iban = strtoupper(preg_replace('/[\s-]+/', '', (string) $iban)); return substr($iban, 0, 2) . '•• •••• ' . substr($iban, -4); } /** * Riquadro "Dati per il pagamento" dell'influencer: intestatario e IBAN * mascherato se ci sono, e il modulo per inserirli o cambiarli. L'IBAN * intero non torna mai nella pagina: si riscrive da capo. */ private static function render_payout($api, array $map) { $aff = $api->get_affiliate($map['id']); ?>
' . esc_html__('Payment details are temporarily unavailable, please try again shortly.', 'affiliatetracker-connector') . ''; return; } $iban = (string) ($aff['payout_iban'] ?? ''); $holder = (string) ($aff['payout_holder'] ?? ''); ?>
| # | __('Approved', 'affiliatetracker-connector'), 'pending' => __('Pending', 'affiliatetracker-connector'), 'cancelled' => __('Cancelled', 'affiliatetracker-connector'))[$c['status']] ?? $c['status']); ?> | ||