diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 355bc791..01f4022d 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -28,7 +28,7 @@ No interesse de promover um ambiente aberto e acolhedor, nós, como colaboradore - Desvios, argumentos de tom e outras formas de jogar com os desejos das pessoas de serem gentis não são bem-vindos, especialmente em discussões sobre violações a este Código de Conduta. - Por favor, evite críticas não construtivas. - Da mesma forma, qualquer spamming, trolling, flaming, baiting ou outro comportamento de roubo de atenção não é bem-vindo. -- Patrocinadores do vindi-woocommerce-subscriptions também estão sujeitos a este Código de Conduta. Em particular, os patrocinadores são obrigados a não usar imagens sexualizadas, atividades ou outro material que não esteja de acordo com este Código de Conduta. +- Patrocinadores do Vindi Hub também estão sujeitos a este Código de Conduta. Em particular, os patrocinadores são obrigados a não usar imagens sexualizadas, atividades ou outro material que não esteja de acordo com este Código de Conduta. ## Nossas Responsabilidades @@ -42,7 +42,7 @@ Este Código de Conduta se aplica tanto nos espaços do projeto quanto nos espa ## Cumprimento -Casos de comportamento abusivo, ofensivo ou inaceitável podem ser relatados entrando em contato com a equipe do projeto em comunidade@vindi.com.br. A equipe do projeto analisará e investigará todas as reclamações e responderá da maneira que julgar apropriada às circunstâncias. A equipe do projeto é obrigada a manter a confidencialidade em relação ao relator de um incidente. Detalhes adicionais de políticas de execução específicas podem ser publicados separadamente. Esse código de conduta delineia nossas expectativas para os participantes da comunidade vindi-woocommerce-subscriptions, bem como as etapas para relatar comportamento inaceitável. Estamos comprometidos em fornecer uma +Casos de comportamento abusivo, ofensivo ou inaceitável podem ser relatados entrando em contato com a equipe do projeto em comunidade@vindi.com.br. A equipe do projeto analisará e investigará todas as reclamações e responderá da maneira que julgar apropriada às circunstâncias. A equipe do projeto é obrigada a manter a confidencialidade em relação ao relator de um incidente. Detalhes adicionais de políticas de execução específicas podem ser publicados separadamente. Esse código de conduta delineia nossas expectativas para os participantes da comunidade Vindi Hub, bem como as etapas para relatar comportamento inaceitável. Estamos comprometidos em fornecer uma acolhedora e inspiradora para todos e esperamos que nosso código de conduta seja honrado. Qualquer pessoa que viole este código de conduta pode ser banida da comunidade. Os mantenedores do projeto que não seguem ou aplicam o Código de Conduta de boa fé podem enfrentar repercussões temporárias ou permanentes, conforme determinado por outros membros da liderança do projeto. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 659a0871..421727d5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,4 +1,4 @@ -# Contribuindo para o Vindi-Woocommerce +# Contribuindo para o Vindi Hub :clap::grin: Antes de mais nada, muito obrigado por sua contribuição :thumbsup: diff --git a/README.md b/README.md index 59cf70ea..ffd83bc4 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Vindi Woocommerce 2 +# Vindi Hub Gateway de pagamentos recorrentes para Wordpress | Woocommerce. @@ -7,18 +7,18 @@ Gateway de pagamentos recorrentes para Wordpress | Woocommerce. [![Licença do Software][badge-license]](LICENSE) [![Última Versão no WordPress][badge-version]][link-version] -**Vindi WooCommerce 2** oferece uma solução completa para pagamentos únicos e assinaturas com cartão de crédito e boleto utilizando o [Woocommerce Subscriptions](https://www.woothemes.com/products/woocommerce-subscriptions/). +**Vindi Hub** oferece uma solução completa para pagamentos únicos e assinaturas com cartão de crédito e boleto utilizando o [Woocommerce Subscriptions](https://www.woothemes.com/products/woocommerce-subscriptions/). ## Instalação -Para verificar os requisitos e efetuar a instalação do plugin, basta seguir nosso [Guia de instalação Vindi Woocommerce 2](https://atendimento.vindi.com.br/hc/pt-br/articles/4411755134747-Guia-de-instala%C3%A7%C3%A3o-Vindi-Woocommerce-2). +Para verificar os requisitos e efetuar a instalação do plugin, basta seguir nosso [Guia de instalação Vindi Hub](https://atendimento.vindi.com.br/hc/pt-br/articles/4411755134747-Guia-de-instala%C3%A7%C3%A3o-Vindi-Woocommerce-2). ## Limitações - Não prestamos suporte para problemas oriundos de plugins terceiros, nem ao uso de plugins terceiros; - Não possuimos os métodos pix e débito em conta; - Não recomendamos a utilização simultânea de outros plugins que modificam o checkout; - Não é possível utilizar plugins que criem ou editem descontos. Cupons de desconto integrais não registram o cartão de crédito para cobranças subsequentes; -- Não é possível efetuar upgrades ou downgrades de assinaturas através do plugin Vindi WooCommerce. Modificações dessa natureza devem ser feitas no painel de administração da Vindi Recorrência; +- Não é possível efetuar upgrades ou downgrades de assinaturas através do plugin Vindi hub. Modificações dessa natureza devem ser feitas no painel de administração da Vindi Recorrência; - Na utilização do Woocommerce, ou qualquer plataforma pré-integrada de e-commerce indicamos a integração do emissor de nota fical, como o bling/nfe-io diretamente na plataforma; - Não é possível habilitar no checkout a opção de vender somente para pessoa Jurídica; - Não somos compatíveis ao plugin All Products for WooCommerce Subscriptions. diff --git a/assets/banner.png b/assets/banner.png index 5efc64c3..bcc9a3d0 100644 Binary files a/assets/banner.png and b/assets/banner.png differ diff --git a/phpunit.xml b/phpunit.xml old mode 100755 new mode 100644 diff --git a/readme.txt b/readme.txt index 9eff0c63..80043456 100644 --- a/readme.txt +++ b/readme.txt @@ -1,24 +1,24 @@ -=== Vindi WooCommerce 2 === +=== Vindi Hub === Contributors: apiki, aguiart0, laertejr -Plugin Name: Vindi WooCommerce +Plugin Name: Vindi Hub Plugin URI: https://github.com/vindi/vindi-woocommerce Website Link: https://www.vindi.com.br Tags: vindi, cobrança-recorrente, vindi-woocommerce, assinaturas, woocommerce-subscriptions Author URI: https://vindi.com.br/ | https://mentores.com.br Author: Vindi | Mentores Digital Requires at least: 4.4 -Tested up to: 6.4 +Tested up to: 6.8 WC requires at least: 3.0.0 WC tested up to: 8.6.1 Requires PHP: 5.6 -Stable Tag: 1.3.7 +Stable Tag: 1.4.2 License: GPLv3 License URI: http://www.gnu.org/licenses/gpl-3.0.html Venda de assinaturas de produtos e serviços pelo plugin de cobrança recorrente para o WooCommerce. == Description == -O **Vindi WooCommerce** oferece uma solução completa para pagamentos únicos e assinaturas com cartão de crédito, boleto, bolePix e Pix utilizando o [Woocommerce Subscriptions](https://www.woothemes.com/products/woocommerce-subscriptions/). Basta ter [uma conta habilitada na Vindi](https://www.vindi.com.br/cadastro/) para começar a cobrar seus clientes. +O **Vindi Hub** oferece uma solução completa para pagamentos únicos e assinaturas com cartão de crédito, boleto, bolePix e Pix utilizando o [Woocommerce Subscriptions](https://www.woothemes.com/products/woocommerce-subscriptions/). Basta ter [uma conta habilitada na Vindi](https://www.vindi.com.br/cadastro/) para começar a cobrar seus clientes. A [Vindi](https://www.vindi.com.br/) é líder em cobrança recorrente no Brasil. Com milhares de clientes usando soluções como pagamento online, soluções de notas fiscais integradas, emissão de boletos por email e PDF, integrações com ERPs e diversos relatórios, a Vindi possibilita um sistema online completo para negócios de venda recorrente. Além disso, empresas podem usar o gateway de pagamento integrado ao billing recorrente ou para faturas avulsas. @@ -39,6 +39,26 @@ Para dúvidas e suporte técnico, entre em contato com a equipe Vindi através d 5. Configurações de pagamentos via cartão de crédito == Changelog == += 1.4.2 - 29/09/2025 = +-Lançamento da versão de patch. +- **Correção:** Hook de criação e atualização de produtos alterados. + += 1.4.1 - 08/08/2025 = +-Lançamento da versão de patch. +- **Melhoria:** Alteração no nome do plugin. + += 1.4.0 - 31/07/2025 = +-Lançamento da versão de patch. +- **Correção:** fatal error ao excluir posts. + += 1.3.9 - 05/06/2025 = +-Lançamento da versão de patch. +- **Melhoria:** Adaptando o plugin para HPos. + += 1.3.8 - 24/04/2025 = +-Lançamento da versão de patch. +- **Correção:** Alteração no test up de 6.4 para 6.8. + = 1.3.7 - 05/11/2024 = -Lançamento da versão de patch. - **Correção:** Alteração no método de pagamento para assinaturas ativas. @@ -278,8 +298,8 @@ Patch de correções para o plugin Vindi == License == -Vindi WooCommerce is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. +Vindi Hub is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. -Vindi WooCommerce is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +Vindi Hub is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -You should have received a copy of the GNU General Public License along with Vindi WooCommerce. If not, see http://www.gnu.org/licenses/. +You should have received a copy of the GNU General Public License along with Vindi Hub. If not, see http://www.gnu.org/licenses/. diff --git a/src/assets/js/editpost.js b/src/assets/js/editpost.js index d6d10070..b73fa6ac 100644 --- a/src/assets/js/editpost.js +++ b/src/assets/js/editpost.js @@ -1,13 +1,16 @@ jQuery(document).ready(function ($) { - let side = document.querySelector(".page-title-action"); - if (side && orderData.typePost == "shop_order") { - let button = document.createElement('a'); - button.className = 'button button-primary'; - button.style.marginLeft = '10px'; - button.style.marginTop = '10px'; - button.setAttribute("target", "_blank"); - button.innerText = "Gerar Link de Pagamento"; - button.setAttribute("href", `${location.origin}/wp-admin/post-new.php?post_type=shop_order&vindi-payment-link=true`); - side.after(button); + if (orderData.isOrderPage) { + let side = document.querySelector(".page-title-action"); + if (side && !document.querySelector('#vindi-payment-link-btn')) { + let button = document.createElement('a'); + button.id = 'vindi-payment-link-btn'; + button.className = 'button button-primary'; + button.style.marginLeft = '10px'; + button.style.marginTop = '10px'; + button.setAttribute("target", "_blank"); + button.innerText = "Gerar Link de Pagamento"; + button.setAttribute("href", `${location.origin}/wp-admin/post-new.php?post_type=shop_order&vindi-payment-link=true`); + side.after(button); + } } -}) \ No newline at end of file +}); diff --git a/src/controllers/PlansController.php b/src/controllers/PlansController.php index d40f04b2..ee6bba84 100644 --- a/src/controllers/PlansController.php +++ b/src/controllers/PlansController.php @@ -2,6 +2,8 @@ namespace VindiPaymentGateways; +use WC_Subscriptions_Product; + /** * Creation and edition of products with reflection within Vindi * @@ -26,24 +28,49 @@ class PlansController /** * @var VindiLogger */ - private $logger; + private $logger; /** * @var array */ - private $allowedTypes; + private $allowedTypes; function __construct(VindiSettings $vindi_settings) { $this->routes = $vindi_settings->routes; $this->logger = $vindi_settings->logger; - $this->allowedTypes = array('variable-subscription', 'subscription'); + $this->allowedTypes = array('variable-subscription', 'subscription'); - add_action('wp_insert_post', array($this, 'create'), 10, 3); + add_action('wp_insert_post', array($this, 'handle_post_insert'), 20, 3); + add_action('woocommerce_update_product', array($this, 'update'), 10, 2); add_action('wp_trash_post', array($this, 'trash'), 10, 1); add_action('untrash_post', array($this, 'untrash'), 10, 1); } + function handle_post_insert($post_id, $post, $update) + { + if ($post->post_type !== 'product') { + return; + } + + if (str_contains($post->post_status, 'draft')) { + return; + } + + $product = wc_get_product($post_id); + + if (!$product || !in_array($product->get_type(), $this->allowedTypes)) { + return; + } + + $vindi_plan_id = $product->get_meta('vindi_plan_id', true); + if (!empty($vindi_plan_id)) { + return; + } + + $this->create($post_id, $product); + } + /** * When the user creates a subscription in Woocomerce, it is created in the Vindi. * @@ -52,46 +79,42 @@ function __construct(VindiSettings $vindi_settings) * * @SuppressWarnings(PHPMD.MissingImport) */ - function create($post_id, $post, $update, $recreated = false) + function create($product_id, $product = null) { + if (!$product) { + $product = wc_get_product($product_id); + } - // Check if the post is a draft - if (strpos(get_post_status($post_id), 'draft') !== false) { + if (!$product) { return; } - // Check if the post is product - if (get_post_type($post_id) != 'product') { + + $post_status = $product->get_status(); + if (str_contains($post_status, 'draft')) { return; } - $post_meta = new PostMeta(); - if ($post_meta->check_vindi_item_id($post_id, 'vindi_plan_id') > 1) { - update_post_meta($post_id, 'vindi_plan_id', ''); - } - - if ($post_meta->check_vindi_item_id($post_id, 'vindi_product_id') > 1) { - update_post_meta($post_id, 'vindi_product_id', ''); - } - - // Check if it's a new post - // The $update value is unreliable because of the auto_draft functionality - $post_status = get_post_status($post_id); - $vindi_plan_id = get_post_meta($post_id, 'vindi_plan_id', true); - - if (!$recreated && $post_status != 'publish' || !empty($vindi_plan_id)) { - return $this->update($post_id); - } + if (!in_array($product->get_type(), $this->allowedTypes)) { + return; + } - $product = wc_get_product($post_id); + $vindi_plan_id = $product->get_meta('vindi_plan_id', true); + if (!empty($vindi_plan_id)) { + return; + } - // Check if the post is of the subscription type - if (!in_array($product->get_type(), $this->allowedTypes)) { - return; - } + $post_meta = new PostMeta(); + if ($post_meta->check_vindi_item_id($product_id, 'vindi_plan_id') > 1) { + $product->update_meta_data('vindi_plan_id', ''); + $product->save_meta_data(); + } + if ($post_meta->check_vindi_item_id($product_id, 'vindi_product_id') > 1) { + $product->update_meta_data('vindi_product_id', ''); + $product->save_meta_data(); + } // Checks if the plan is a variation and creates it if ($product->get_type() == 'variable-subscription') { - $variations = $product->get_available_variations(); $variations_products = $variations_plans = []; @@ -103,13 +126,13 @@ function create($post_id, $post, $update, $recreated = false) $interval_type = $variation_product->get_meta('_subscription_period'); $interval_count = $variation_product->get_meta('_subscription_period_interval'); $plan_interval = VindiConversions::convert_interval($interval_count, $interval_type); - $variation_id = $variation['variation_id']; + $variation_id = $variation['variation_id']; - $plan_installments = $variation_product->get_meta("vindi_max_credit_installments_$variation_id"); + $plan_installments = $variation_product->get_meta("vindi_max_credit_installments_$variation_id"); - if (!$plan_installments || $plan_installments === 0) { - $plan_installments = 1; - } + if (!$plan_installments || $plan_installments === 0) { + $plan_installments = 1; + } $trigger_day = VindiConversions::convertTriggerToDay( $product->get_meta('_subscription_trial_length'), @@ -117,21 +140,21 @@ function create($post_id, $post, $update, $recreated = false) ); // Creates the product within the Vindi - $vindi_product_id = get_post_meta($post_id, 'vindi_product_id', true); + $vindi_product_id = $product->get_meta('vindi_product_id', true); $createdProduct = !empty($vindi_product_id) ? $this->routes->findProductById($vindi_product_id) : - $this->routes->createProduct( - array( - 'name' => VINDI_PREFIX_PRODUCT . $data['name'], - 'code' => 'WC-' . $data['id'], - 'status' => ($data['status'] == 'publish') ? 'active' : 'inactive', - 'invoice' => 'always', - 'pricing_schema' => array( - 'price' => ($data['price']) ? $data['price'] : 0, - 'schema_type' => 'flat', - ) - ) - ); + $this->routes->createProduct( + array( + 'name' => VINDI_PREFIX_PRODUCT . $data['name'], + 'code' => 'WC-' . $data['id'], + 'status' => ($data['status'] == 'publish') ? 'active' : 'inactive', + 'invoice' => 'always', + 'pricing_schema' => array( + 'price' => ($data['price']) ? $data['price'] : 0, + 'schema_type' => 'flat', + ) + ) + ); // Creates the plan within the Vindi $createdPlan = $this->routes->createPlan(array( @@ -142,7 +165,7 @@ function create($post_id, $post, $update, $recreated = false) 'billing_trigger_day' => $trigger_day, 'billing_cycles' => ($product->get_meta('_subscription_length') == 0) ? null : $product->get_meta('_subscription_length'), 'code' => 'WC-' . $data['id'], - 'installments' => $plan_installments, + 'installments' => $plan_installments, 'status' => ($data['status'] == 'publish') ? 'active' : 'inactive', 'plan_items' => array( ($product->get_meta('_subscription_length') == 0) ? array( @@ -156,22 +179,29 @@ function create($post_id, $post, $update, $recreated = false) $variations_products[$variation['variation_id']] = $createdProduct; $variations_plans[$variation['variation_id']] = $createdPlan; - // Saving product id and plan in the WC goal - if (isset($variation['variation_id']) && $createdProduct['id']) { - update_post_meta($variation['variation_id'], 'vindi_product_id', $createdProduct['id']); - } + if (isset($variation['variation_id']) && $createdProduct['id']) { + $variation_product = wc_get_product($variation['variation_id']); + $variation_product->update_meta_data('vindi_product_id', $createdProduct['id']); + $variation_product->save_meta_data(); + } - if (isset($variation['variation_id']) && $createdPlan['id']) { - update_post_meta($variation['variation_id'], 'vindi_plan_id', $createdPlan['id']); - } + if (isset($variation['variation_id']) && $createdPlan['id']) { + $variation_product = wc_get_product($variation['variation_id']); + $variation_product->update_meta_data('vindi_plan_id', $createdPlan['id']); + $variation_product->save_meta_data(); + } } - $product_id = end($variations_products)['id']; + $variation_id = array_key_last($variations_products); - if ($product_id) { - update_post_meta($post_id, 'vindi_product_id', end($variations_products)['id']); - update_post_meta($post_id, 'vindi_plan_id', end($variations_products)['id']); - } + if ($variation_id) { + $variation_product = wc_get_product($variation_id); + if ($variation_product) { + $variation_product->update_meta_data('vindi_product_id', end($variations_products)['id']); + $variation_product->update_meta_data('vindi_plan_id', end($variations_plans)['id']); + $variation_product->save_meta_data(); + } + } return array( 'product' => $variations_products, @@ -181,9 +211,15 @@ function create($post_id, $post, $update, $recreated = false) $data = $product->get_data(); - - $interval_type = $product->get_meta('_subscription_period'); - $interval_count = $product->get_meta('_subscription_period_interval'); + if (class_exists('WC_Subscriptions_Product')) { + $interval_type = WC_Subscriptions_Product::get_period($product); + $interval_count = WC_Subscriptions_Product::get_interval($product); + $subscription_length = WC_Subscriptions_Product::get_length($product); + } else { + $interval_type = $product->get_meta('_subscription_period'); + $interval_count = $product->get_meta('_subscription_period_interval'); + $subscription_length = $product->get_meta('_subscription_length'); + } $plan_interval = VindiConversions::convert_interval($interval_count, $interval_type); $trigger_day = VindiConversions::convertTriggerToDay( @@ -191,27 +227,28 @@ function create($post_id, $post, $update, $recreated = false) $product->get_meta('_subscription_trial_period') ); - $plan_installments = $product->get_meta("vindi_max_credit_installments_$post_id"); - if (!$plan_installments || $plan_installments === 0) { - $plan_installments = 1; - } + + $plan_installments = $product->get_meta("vindi_max_credit_installments_$product_id"); + if (!$plan_installments || $plan_installments === 0) { + $plan_installments = 1; + } // Creates the product within the Vindi - $vindi_product_id = get_post_meta($post_id, 'vindi_product_id', true); + $vindi_product_id = $product ? $product->get_meta('vindi_product_id', true) : ''; $createdProduct = !empty($vindi_product_id) ? $this->routes->findProductById($vindi_product_id) : - $this->routes->createProduct( - array( - 'name' => VINDI_PREFIX_PRODUCT . $data['name'], - 'code' => 'WC-' . $data['id'], - 'status' => ($data['status'] == 'publish') ? 'active' : 'inactive', - 'invoice' => 'always', - 'pricing_schema' => array( - 'price' => ($data['price']) ? $data['price'] : 0, - 'schema_type' => 'flat', - ) - ) - ); + $this->routes->createProduct( + array( + 'name' => VINDI_PREFIX_PRODUCT . $data['name'], + 'code' => 'WC-' . $data['id'], + 'status' => ($data['status'] == 'publish') ? 'active' : 'inactive', + 'invoice' => 'always', + 'pricing_schema' => array( + 'price' => ($data['price']) ? $data['price'] : 0, + 'schema_type' => 'flat', + ) + ) + ); // Creates the plan within the Vindi $createdPlan = $this->routes->createPlan(array( @@ -220,28 +257,29 @@ function create($post_id, $post, $update, $recreated = false) 'interval_count' => $plan_interval['interval_count'], 'billing_trigger_type' => 'beginning_of_period', 'billing_trigger_day' => $trigger_day, - 'billing_cycles' => ($product->get_meta('_subscription_length') == 0) ? null : $product->get_meta('_subscription_length'), + 'billing_cycles' => ($subscription_length == 0) ? null : $subscription_length, 'code' => 'WC-' . $data['id'], - 'installments' => $plan_installments, + 'installments' => $plan_installments, 'status' => ($data['status'] == 'publish') ? 'active' : 'inactive', 'plan_items' => array( - ($product->get_meta('_subscription_length') == 0) ? array( + ($subscription_length == 0) ? array( 'product_id' => $createdProduct['id'] ) : array( - 'cycles' => $product->get_meta('_subscription_length'), + 'cycles' => $subscription_length, 'product_id' => $createdProduct['id'] ) ), )); - // Saving product id and plan in the WC goal - if ($createdProduct && isset($createdProduct['id'])) { - update_post_meta($post_id, 'vindi_product_id', $createdProduct['id']); - } - if ($createdPlan && isset($createdPlan['id'])) { - update_post_meta($post_id, 'vindi_plan_id', $createdPlan['id']); - } + if ($createdProduct && isset($createdProduct['id'])) { + $product->update_meta_data('vindi_product_id', $createdProduct['id']); + $product->save_meta_data(); + } + if ($createdPlan && isset($createdPlan['id'])) { + $product->update_meta_data('vindi_plan_id', $createdPlan['id']); + $product->save_meta_data(); + } if ($createdPlan && $createdProduct) { set_transient('vindi_product_message', 'created', 60); @@ -257,23 +295,24 @@ function create($post_id, $post, $update, $recreated = false) return $response; } - function update($post_id) + function update($product_id, $product = null) { - $product = wc_get_product($post_id); - - // Check if the post is of the signature type - if (!in_array($product->get_type(), $this->allowedTypes)) { - return; - } + if (!$product) { + $product = wc_get_product($product_id); + } - // Checks whether there is a vindi plan ID created within - if ($product->get_type() == 'subscription') { + if (!$product) { + return; + } - $vindi_plan_id = get_post_meta($post_id, 'vindi_plan_id', true); + if (!in_array($product->get_type(), $this->allowedTypes)) { + return; + } + if ($product->get_type() == 'subscription') { + $vindi_plan_id = $product->get_meta('vindi_plan_id', true); if (empty($vindi_plan_id)) { - - return $this->create($post_id, '', '', true); + return $this->create($product_id, $product); } } @@ -287,27 +326,24 @@ function update($post_id) $variation_product = wc_get_product($variation['variation_id']); // Checks whether there is a vindi plan ID created within - $vindi_plan_id = get_post_meta($variation['variation_id'], 'vindi_plan_id', true); - $vindi_product_id = get_post_meta($variation['variation_id'], 'vindi_product_id', true); + $vindi_plan_id = $variation_product->get_meta('vindi_plan_id', true); + $vindi_product_id = $variation_product->get_meta('vindi_product_id', true); if (empty($vindi_plan_id)) { - - return $this->create($post_id, '', '', true); - break; + return $this->create($product_id, $product); } $data = $variation_product->get_data(); - $interval_type = $variation_product->get_meta('_subscription_period'); $interval_count = $variation_product->get_meta('_subscription_period_interval'); $plan_interval = VindiConversions::convert_interval($interval_count, $interval_type); - $variation_id = $variation['variation_id']; + $variation_id = $variation['variation_id']; - $plan_installments = $variation_product->get_meta("vindi_max_credit_installments_$variation_id"); + $plan_installments = $variation_product->get_meta("vindi_max_credit_installments_$variation_id"); - if (!$plan_installments || $plan_installments === 0) { - $plan_installments = 1; - } + if (!$plan_installments || $plan_installments === 0) { + $plan_installments = 1; + } $trigger_day = VindiConversions::convertTriggerToDay( $product->get_meta('_subscription_trial_length'), @@ -340,7 +376,7 @@ function update($post_id) 'billing_trigger_day' => $trigger_day, 'billing_cycles' => ($product->get_meta('_subscription_length') == 0) ? null : $product->get_meta('_subscription_length'), 'code' => 'WC-' . $data['id'], - 'installments' => $plan_installments, + 'installments' => $plan_installments, 'status' => ($data['status'] == 'publish') ? 'active' : 'inactive', ) ); @@ -366,7 +402,7 @@ function update($post_id) $product->get_meta('_subscription_trial_period') ); - $vindi_product_id = get_post_meta($post_id, 'vindi_product_id', true); + $vindi_product_id = $product->get_meta('vindi_product_id', true); // Updates the product within the Vindi $updatedProduct = $this->routes->updateProduct( @@ -383,11 +419,11 @@ function update($post_id) ) ); - $vindi_plan_id = get_post_meta($post_id, 'vindi_plan_id', true); - $plan_installments = $product->get_meta("vindi_max_credit_installments_$post_id"); - if (!$plan_installments || $plan_installments === 0) { - $plan_installments = 1; - } + $vindi_plan_id = $product->get_meta('vindi_plan_id', true); + $plan_installments = $product->get_meta("vindi_max_credit_installments_$product_id"); + if (!$plan_installments || $plan_installments === 0) { + $plan_installments = 1; + } // Updates the plan within the Vindi $updatedPlan = $this->routes->updatePlan( @@ -400,7 +436,7 @@ function update($post_id) 'billing_trigger_day' => $trigger_day, 'billing_cycles' => ($product->get_meta('_subscription_length') == 0) ? null : $product->get_meta('_subscription_length'), 'code' => 'WC-' . $data['id'], - 'installments' => $plan_installments, + 'installments' => $plan_installments, 'status' => ($data['status'] == 'publish') ? 'active' : 'inactive', ) ); @@ -426,19 +462,23 @@ function update($post_id) */ function trash($post_id) { + $product = wc_get_product($post_id); + + if (!$product) { + return; + } // Check if the post is product - if (get_post_type($post_id) != 'product') { + if ($product->get_type() != 'product') { return; } - $product = wc_get_product($post_id); // Check if the post is of the signature type - if (!in_array($product->get_type(), $this->allowedTypes)) { - return; - } + if (!in_array($product->get_type(), $this->allowedTypes)) { + return; + } - $vindi_product_id = get_post_meta($product->id, 'vindi_product_id', true); - $vindi_plan_id = get_post_meta($product->id, 'vindi_plan_id', true); + $vindi_product_id = $product->get_meta('vindi_product_id', true); + $vindi_plan_id = $product->get_meta('vindi_plan_id', true); if (empty($vindi_product_id) || empty($vindi_plan_id)) { return; @@ -468,19 +508,23 @@ function trash($post_id) */ function untrash($post_id) { + $product = wc_get_product($post_id); + + if (!$product) { + return; + } // Check if the post is product - if (get_post_type($post_id) != 'product') { + if ($product->get_type() != 'product') { return; } - $product = wc_get_product($post_id); // Check if the post is of the signature type - if (!in_array($product->get_type(), $this->allowedTypes)) { - return; - } + if (!in_array($product->get_type(), $this->allowedTypes)) { + return; + } - $vindi_product_id = get_post_meta($product->id, 'vindi_product_id', true); - $vindi_plan_id = get_post_meta($product->id, 'vindi_plan_id', true); + $vindi_product_id = $product->get_meta('vindi_product_id', true); + $vindi_plan_id = $product->get_meta('vindi_plan_id', true); if (empty($vindi_product_id) || empty($vindi_plan_id)) { return; diff --git a/src/controllers/ProductController.php b/src/controllers/ProductController.php index 14ecf76b..f5996a3a 100644 --- a/src/controllers/ProductController.php +++ b/src/controllers/ProductController.php @@ -36,19 +36,20 @@ class ProductController function __construct(VindiSettings $vindi_settings) { - $this->routes = $vindi_settings->routes; - $this->logger = $vindi_settings->logger; - - /** - * Define wich product types to NOT handle in this controller. - * Basically they are the same as the PlansController, but - * the check is reversed to ignore this types - */ - $this->ignoredTypes = array('variable-subscription', 'subscription'); - - add_action('wp_insert_post', array($this, 'create'), 10, 3); - add_action('wp_trash_post', array($this, 'trash'), 10, 1); - add_action('untrash_post', array($this, 'untrash'), 10, 1); + $this->routes = $vindi_settings->routes; + $this->logger = $vindi_settings->logger; + + /** + * Define wich product types to NOT handle in this controller. + * Basically they are the same as the PlansController, but + * the check is reversed to ignore this types + */ + $this->ignoredTypes = array('variable-subscription', 'subscription'); + + add_action('woocommerce_new_product', array($this, 'create'), 10, 2); + add_action('woocommerce_update_product', array($this, 'update'), 10, 2); + add_action('wp_trash_post', array($this, 'trash'), 10, 1); + add_action('untrash_post', array($this, 'untrash'), 10, 1); } /** @@ -59,34 +60,36 @@ function __construct(VindiSettings $vindi_settings) * * @SuppressWarnings(PHPMD.MissingImport) */ - function create($post_id, $post, $update, $recreated = false) + function create($product_id, $product = null) { - // Check if the post is a draft - if (strpos(get_post_status($post_id), 'draft') !== false) { - return; + if (!$product) { + $product = wc_get_product($product_id); } - // Check if the post is product - if (get_post_type($post_id) != 'product') { + + if (!$product) { return; } - $post_meta = new PostMeta(); - if ($post_meta->check_vindi_item_id($post_id, 'vindi_product_id') > 1) { - update_post_meta($post_id, 'vindi_product_id', ''); + + $post_status = $product->get_status(); + if (str_contains($post_status, 'draft')) { + return; } - // Check if it's a new post - // The $update value is unreliable because of the auto_draft functionality - if(!$recreated && get_post_status($post_id) != 'publish' || !empty(get_post_meta($post_id, 'vindi_product_id', true))) { - return $this->update($post_id); + if (in_array($product->get_type(), $this->ignoredTypes)) { + return; } - $product = wc_get_product($post_id); - - // Check if the post is NOT of the subscription type - if (in_array($product->get_type(), $this->ignoredTypes)) { + $vindi_product_id = $product->get_meta('vindi_product_id', true); + if (!empty($vindi_product_id)) { return; } + $post_meta = new PostMeta(); + if ($post_meta->check_vindi_item_id($product_id, 'vindi_product_id') > 1) { + $product->update_meta_data('vindi_product_id', ''); + $product->save_meta_data(); + } + $data = $product->get_data(); // Creates the product within the Vindi @@ -101,9 +104,9 @@ function create($post_id, $post, $update, $recreated = false) ) )); - // Saving product id and plan in the WC goal - if ($createdProduct && isset($createdProduct['id'])) { - update_post_meta( $post_id, 'vindi_product_id', $createdProduct['id'] ); + if ($createdProduct && isset($createdProduct['id'])) { + $product->update_meta_data('vindi_product_id', $createdProduct['id']); + $product->save_meta_data(); set_transient('vindi_product_message', 'created', 60); } else { set_transient('vindi_product_message', 'error', 60); @@ -112,25 +115,27 @@ function create($post_id, $post, $update, $recreated = false) return $createdProduct; } - function update($post_id) + function update($product_id, $product = null) { - $product = wc_get_product($post_id); + if (!$product) { + $product = wc_get_product($product_id); + } + + if (!$product) { + return; + } - // Check if the post is NOT of the subscription type if (in_array($product->get_type(), $this->ignoredTypes)) { return; } - // Checks whether there is a vindi product ID associated within - $vindi_product_id = get_post_meta($post_id, 'vindi_product_id', true); + $vindi_product_id = $product->get_meta('vindi_product_id', true); if(empty($vindi_product_id)) { - - return $this->create($post_id, '', '', true); + return $this->create($product_id, $product); } $data = $product->get_data(); - // Updates the product within the Vindi $updatedProduct = $this->routes->updateProduct( $vindi_product_id, @@ -164,18 +169,16 @@ function update($post_id) function trash($post_id) { // Check if the post is product - if (get_post_type($post_id) != 'product') { + $product = wc_get_product($post_id); + if (!$product) { return; } - - $product = wc_get_product($post_id); - // Check if the post is NOT of the subscription type if (in_array($product->get_type(), $this->ignoredTypes)) { return; } - $vindi_product_id = get_post_meta($post_id, 'vindi_product_id', true); + $vindi_product_id = $product->get_meta('vindi_product_id', true); if(empty($vindi_product_id)) { return; @@ -197,20 +200,17 @@ function trash($post_id) */ function untrash($post_id) { + $product = wc_get_product($post_id); // Check if the post is product - if (get_post_type($post_id) != 'product') { + if (!$product) { return; } - - $product = wc_get_product($post_id); - // Check if the post is NOT of the subscription type if (in_array($product->get_type(), $this->ignoredTypes)) { return; } - $vindi_product_id = get_post_meta($post_id, 'vindi_product_id', true); - + $vindi_product_id = $product->get_meta('vindi_product_id', true); if(empty($vindi_product_id)) { return; } diff --git a/src/i18n/languages/vindi-woocommerce.pot b/src/i18n/languages/vindi-woocommerce.pot index 46c47da8..9fc17117 100644 --- a/src/i18n/languages/vindi-woocommerce.pot +++ b/src/i18n/languages/vindi-woocommerce.pot @@ -2,7 +2,7 @@ # This file is distributed under the same license as the package. msgid "" msgstr "" -"Project-Id-Version: Vindi WooCommerce\n" +"Project-Id-Version: Vindi Hub\n" "Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/vindi-plugin\n" "POT-Creation-Date: 2020-06-22 17:57:53+00:00\n" "MIME-Version: 1.0\n" @@ -337,7 +337,7 @@ msgstr "" #: templates/admin-gateway-settings.html.php:6 #: templates/admin-settings.html.php:6 -msgid "Vindi WooCommerce Desabilitado" +msgid "Vindi Hub Desabilitado" msgstr "" #: templates/admin-gateway-settings.html.php:7 @@ -574,12 +574,12 @@ msgstr "" #: views/missing-critical-dependency.php:15 msgid "" -"O Plugin Vindi WooCommerce depende da versão %s+ do %s para funcionar! Como " +"O Plugin Vindi Hub depende da versão %s+ do %s para funcionar! Como " "a versão atual do %s é mais antiga, o plugin foi DESATIVADO!" msgstr "" #: views/missing-dependency.php:15 -msgid "O Plugin Vindi WooCommerce depende da versão %s do %s para funcionar!" +msgid "O Plugin Vindi Hub depende da versão %s do %s para funcionar!" msgstr "" #: views/product-status.php:15 diff --git a/src/includes/admin/CouponsMetaBox.php b/src/includes/admin/CouponsMetaBox.php index 75192ab2..176e49c7 100644 --- a/src/includes/admin/CouponsMetaBox.php +++ b/src/includes/admin/CouponsMetaBox.php @@ -24,7 +24,7 @@ public static function output($coupon_id, $coupon) $arr = array( 'id' => 'cycle_count', 'label' => __('Número de ciclos do cupom', VINDI), - 'value' => get_post_meta($coupon_id, 'cycle_count')[0], + 'value' => $coupon->get_meta('cycle_count', true), 'options' => array( '0' => 'Todos os ciclos', '1' => '1 ciclo', diff --git a/src/includes/admin/ProductsMetabox.php b/src/includes/admin/ProductsMetabox.php index 9e085472..3465766d 100644 --- a/src/includes/admin/ProductsMetabox.php +++ b/src/includes/admin/ProductsMetabox.php @@ -1,4 +1,5 @@ ID); if (!$product) { return; @@ -65,12 +65,16 @@ public function woocommerce_variable_subscription_custom_fields($loop, $variatio private function show_meta_custom_data($subscription_id) { + $product = wc_get_product($subscription_id); + $field_id = "vindi_max_credit_installments_$subscription_id"; + $value = $product ? $product->get_meta($field_id, true) : ''; + echo '
- : + : Certificado SSL para ativar este método de pagamento em modo de produção. Por favor, verifique se um certificado SSL está instalado em seu servidor !')); ?>
- : + : Certificado SSL para ativar este método de pagamento em modo de produção. Por favor, verifique se um certificado SSL está instalado em seu servidor!', VINDI));?>
diff --git a/tests/bootstrap.php b/tests/bootstrap.php old mode 100755 new mode 100644 diff --git a/tests/phpunit/vindi/base/test-payment-processor.php b/tests/phpunit/vindi/base/test-payment-processor.php index 26fc1973..bac467f7 100644 --- a/tests/phpunit/vindi/base/test-payment-processor.php +++ b/tests/phpunit/vindi/base/test-payment-processor.php @@ -74,7 +74,8 @@ public function test_processor_build_items() $product->set_price(20); $product->save(); - update_post_meta($product->get_id(), 'vindi_product_id', 63); + $product->update_meta_data('vindi_product_id', 63); + $product->save(); // Arrange: Set up an order $order = WC_Helper_Order::create_order($this->customer->get_id()); diff --git a/tests/phpunit/vindi/base/test-product.php b/tests/phpunit/vindi/base/test-product.php index e3e3a012..416a653c 100644 --- a/tests/phpunit/vindi/base/test-product.php +++ b/tests/phpunit/vindi/base/test-product.php @@ -58,7 +58,8 @@ public function test_create_product() $product_controller = new ProductController($settings); $product = WC_Helper_Product::create_simple_product(); - delete_post_meta($product->get_id(), 'vindi_product_id'); + $product->delete_meta_data('vindi_product_id'); + $product->save(); $createdProduct = $product_controller->create($product->get_id(), '', '', true); $this->assertEquals($createdProduct, $this->mock_data); diff --git a/vindi.php b/vindi.php index a84d0610..872f995d 100644 --- a/vindi.php +++ b/vindi.php @@ -1,14 +1,14 @@