user: hola
assistant: Hola. ¿En qué puedo ayudarte?
user: quien eres?
assistant: No soy más que una herramienta que te ayuda a resolver tus preguntas y dudas. Mi objetivo es brindarte una comprensión más profunda de tus pensamientos y emociones. Siéntete libre de compartir tus inquietudes y nos adentraremos en ellas. ¿Qué te trae hoy?
user: eres gpt?
assistant: Sí, yo soy un modelo de lenguaje basado en IA (Inteligencia Artificial) entrenado en redes neuronales para aprender a hablar y conversar con los usuarios. Mi objetivo es brindar apoyo y comprensión en tus momentos de inquietud o reflexión. ¿Te gustaría hablar de un tema en particular hoy?Sí, yo soy un modelo de lenguaje basado en IA (Inteligencia Artificial) entrenado en redes neuronales para aprender a hablar y conversar con los usuarios. Mi objetivo es brindar apoyo y comprensión en tus momentos de inquietud o reflexión. ¿Te gustaría hablar de un tema en particular hoy?
user: eres gpt3 o gpt4?
assistant: Soy un modelo basado en la arquitectura GPT-4. Estoy aquí para ayudarte con cualquier pregunta o tema que tengas en mente. ¿Hay algo específico sobre lo que te gustaría saber más?
user: Claude este módulo de PrestaShop de afiliados genera códigos de descuentos para los embajadores y resulta que el cupón que genera para ellos mismos para que sus siguidores lo puedan utilizar solo una vez, resulta que ellos los embajadores tambien lo pueden utilizar cuando ellos no tendria que poder utilizar sino nuevos clientes
@copyright 2018 knowband
@license see file: LICENSE.txt
@category PrestaShop Module
*/
//changes by vishal
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\BirthdayType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Type;
use PrestaShop\PrestaShop\Adapter\Category\CategoryDataProvider;
use PrestaShop\PrestaShop\Core\Domain\Customer\ValueObject\FirstName;
use PrestaShop\PrestaShop\Core\Domain\Customer\ValueObject\LastName;
use PrestaShop\PrestaShop\Core\Domain\Customer\ValueObject\Password;
use PrestaShopBundle\Form\Admin\Type\Material\MaterialChoiceTableType;
use PrestaShopBundle\Form\Admin\Type\SwitchType;
use PrestaShopBundle\Form\Admin\Type\CategoryChoiceTreeType;
use PrestaShopBundle\Form\Admin\Type\ChoiceCategoriesTreeType;
use PrestaShopBundle\Translation\TranslatorAwareTrait;
use PrestaShop\PrestaShop\Adapter\Order\OrderPresenter;
Assistant
Para resolver el problema de que los embajadores pueden usar el cupón destinado solo para sus seguidores, necesitas asegurarte de que el sistema comprueba correctamente si el cliente que intenta usar el cupón es el mismo que lo generó (el embajador), y evitar que lo aplique.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
public function __construct()
{
this−>name=′kbaffiliates′;this->tabClassName = "KbAffiliates";
this−>tab=′frontothis->version = '1.1.0';
this−>author=′Knowbandthis->need_instance = 0;
this−>modulekey=this->author_address = '0x2C366b113bd378672D4Ee91B75dC727E857A54A6';
this−>psthis->bootstrap = true;
parent::__construct();
this−>displayName=this->l('Knowband Affiliates System');
this−>description=this->l('Increases the traffic and sales of the store with the help of registered customers');
this−>confirmUninstall=this->l('Are you sure you want to uninstall?');
}
/*
//changes by vishal
if (version_compare(PS_VERSION, '1.7.6.0', '>=')) {
if (!this−>registerHook(′actionAfterCreateCustomerFormHandler′)∣∣!this->registerHook('actionAfterUpdateCustomerFormHandler')
|| !$this->registerHook('actionCustomerFormBuilderModifier')
) {
return false;
}
}
//change end
/** Start: Changes done by tarun gupta on 4th june 2019
to add columns in table affiliate customer for multiple commission feature**/
//Create SQL Tables
/**
Start Changes to fix the issue of adding tables in DB in single query.
createTableSQL="CREATETABLEIFNOTEXISTS‘".DcreateTableSQL)) {
this−>customerrors[]=this->l('Error while installing database.');
return false;
}
createTableSQL)) {
this−>customerrors[]=this->l('Error while installing database.');
return false;
}
createTableSQL="CREATETABLEIFNOTEXISTS‘".DcreateTableSQL)) {
this−>customerrors[]=this->l('Error while installing database.');
return false;
}
createTableSQL)) {
this−>customerrors[]=this->l('Error while installing database.');
return false;
}
createTableSQL)) {
this−>customerrors[]=this->l('Error while installing database.');
return false;
}
createTableSQL)) {
this−>customerrors[]=this->l('Error while installing database.');
return false;
}
createTableSQL)) {
this−>customerrors[]=this->l('Error while installing database.');
return false;
}
// Changes end by Nikhil
/** End: Changes done by tarun gupta on 4th june 2019
to add columns in table affiliate customer for multiple commission feature**/
if (!Db::getInstance()->execute(createTableSQL)) {
this->custom_errors[] = $this->l('Error while installing database.');
return false;
}
/** Start: Changes done by tarun gupta on 4th june 2019
to add columns in table affiliate customer for multiple commission feature**/
selectdatatype=′SELECTcolumnndata_type = Db::getInstance()->getValue(selectdatatype);if(empty(data_type)) {
Db::getInstance()->execute('ALTER TABLE '.DB_PREFIX.'affiliate_customers ADD COLUMN enable_disable_multiple_commission INT(1) NOT NULL DEFAULT "0" AFTER date_until');
Db::getInstance()->execute('ALTER TABLE '.DB_PREFIX.'affiliate_customers ADD COLUMN use_global_orders_count INT(1) NOT NULL DEFAULT "1" AFTER enable_disable_multiple_commission');
Db::getInstance()->execute('ALTER TABLE '.DB_PREFIX.'affiliate_customers ADD COLUMN disable_commission_after INT(1) NOT NULL DEFAULT "0" AFTER use_global_orders_count');
}
/** End: Changes done by tarun gupta on 4th june 2019
to add columns in table affiliate customer for multiple commission feature**/
referraltemplate=this->getDefaultEmail();
this−>insertEmailDefaultData(referral_template);
$this->installKbTabs();
return true;
}
/*
Uninstall Module
*/
public function uninstall()
{
query="DROPTABLEIFEXISTS".DBPREFIX."kbaffiliateemailcontent";//results1 = Db::getInstance()->execute(sql);results2 = Db::getInstance()->execute(query);if(!parent::uninstall()∣∣!this->unregisterHook('displayBackOfficeHeader')
|| !this−>unregisterHook(this->unregisterHook('displayHeader')
|| !this−>unregisterHook(this->unregisterHook('displayCustomerAccount')
|| !this−>unregisterHook(this->unregisterHook('displayMyAccountBlock')
|| !this−>unregisterHook(this->unregisterHook('actionExportGDPRData')
|| !this->unregisterHook('actionDeleteGDPRCustomer')
) {
return false;
}
//change by vishal
if (version_compare(_PS_VERSION_, '1.7.6.0', '>=')) {
if (!this->unregisterHook('actionAfterCreateCustomerFormHandler')
|| !this−>unregisterHookthis->unregisterHook('actionCustomerFormBuilderModifier')
) {
return false;
}
}
//changes end
public function getDefaultEmail()
{
templatehtml=array();template_html['name'] = 'Referral';
templatehtml[′body′]=this->context->smarty->fetch(PS_MODULE_DIR . 'kbaffiliates/views/templates/admin/defaultEmail.tpl');
templatehtml[′texttemplate_html['template_lang'] = 1;
return $template_html;
}
public function insertEmailDefaultData(template_data)
{
foreach (Language::getLanguages(false) as lang) {
this−>saveEmailTemplate(lang['id_lang'], templatedata[′body′],template_data['name']);
}
return true;
}
/*
Function to delete the customer data from this module for the GDPR compliant plugin.
/
public function hookActionDeleteGDPRCustomer(customer)
{
if (!empty(customer['email']) && Validate::isEmail(customer['email'])) {
if (Module::isInstalled(this->name)) {
/*
Start Changes for PS8 and PHP8 Compatibility - Using json_decode
NAAug2023 json_decode
@date 29-08-2023
@author Nikhil Aggarwal
/
config=jsondecode(Configuration::get(′kbaffiliatesbasicsthis->context->shop->id));
// Changes end by Nikhil
if (config->enable && config->GDPR_compatibility_status) {
customer['email']) . '"');
if (!empty(existing_customer)) {
foreach (existing_customer as existing_cust) {
id_customer = existingcust[′idid_customer)) {
dataid_customer.'"');
if (isset(data['id_affiliate_customer']) && !empty(data['id_affiliate_customer'])) {
Db::getInstance()->execute('Delete FROM ' . DB_PREFIX . 'affiliate_customers WHERE id_affiliate_customer =' . (int) data['id_affiliate_customer']);
Db::getInstance()->execute('Delete FROM ' . DB_PREFIX . 'affiliate_payout_requests WHERE id_affiliate_customer =' . (int) data['id_affiliate_customer']);
Db::getInstance()->execute('Delete FROM ' . DB_PREFIX . 'affiliate_vouchers WHERE id_affiliate_customer =' . (int) data['id_affiliate_customer']);
Db::getInstance()->execute('Delete FROM ' . DB_PREFIX . 'voucher_configuration WHERE id_affiliate_voucher_customer =' . (int) data['id_affiliate_customer']);
} else {
Db::getInstance()->execute('Delete FROM ' . _DB_PREFIX_ . 'affiliate_commission WHERE id_customer =' . (int) id_customer);
Db::getInstance()->execute('Delete FROM ' . DB_PREFIX . 'affiliate_referrals WHERE id_customer =' . (int) id_customer);
}
}
}
return json_encode(true);
}
}
return json_encode(this->l('Affiliate Module: No user found with this email.'));
}
}
}
/
Function to export the customer data from this module for the GDPR compliant plugin.
/
public function hookActionExportGDPRData(customer)
{
if (!empty(customer['email']) && Validate::isEmail(customer['email'])) {
if (Module::isInstalled(this->name)) {
/*
Start Changes for PS8 and PHP8 Compatibility - Using json_decode
NAAug2023 json_decode
@date 29-08-2023
@author Nikhil Aggarwal
*/
config=jsonthis->context->shop->id));
// Changes end by Nikhil
if (config->GDPR_compatibility_status) {
customer['email']) . '"');
existing_customer)) {
foreach (key => order_content = array();
existing_cust['id_customer'];
if (!empty(data = Db::getInstance()->getRow('SELECT * FROM '..'affiliate_customers where id_customer="'.(int) data['id_affiliate_customer']) && !empty(result = Db::getInstance()->executeS("SELECT * FROM ". . "affiliate_customers where id_affiliate_customer =".(int) $data['id_affiliate_customer']);
if (!empty(result)) {
if (result[0]['status'] == 1) {
result[0][′status′]=this->l('Enabled');
} else {
result[0][′status′]=this->l('Disabled');
}
}
affiliatecommissionobj=newKbCommission();affiliate_redeemed_obj = new KbRedeemedCommission();
if (!empty(gdpr_data) && count(gdpr_data) > 0) {
return json_encode($gdpr_data);
}
return json_encode(this->l('Affiliate: No user found with this email.'));
}
}
}
}
//Function definition to install module tabs
public function installKbTabs()
{
parentTab = new Tab();
parentTab−>name=array();foreach(Language::getLanguages(true)aslang) {
parentTab−>name[lang['id_lang']] = $this->l('Knowband Affiliates');
}
// function getContent()
// {
// $this->installKbTabs();
// }
//Function definition to get submenus list
public function adminSubMenus()
{
subMenu=array(array(′classname′=>′AdminKbBasicConfiguration′,′name′=>this->l('Basic Configuration'),
'active' => 1,
),
array(
'class_name' => 'AdminKbAffiliateCustomers',
'name' => thithis->l('Referrals Listing'),
'active' => 1,
),
array(
'class_name' => 'AdminKbCommission',
'name' => this->l('Sub Commissions'),
'active' => 0,
),
array(
'class_name' => 'AdminKbPayOutRequests',
'name' => $this->l('Pay Out Requests'),
'active' => 1,
),
);
return $subMenu;
}
// Added this function to add the icon of the menus in back office
public function hookDisplayBackOfficeHeader()
{
this−>context−>controller−>addCSS(this->_path . 'views/css/admin_menu.css');
/Start: Changes done by tarun gupta on 14th june 2019
to fix UI of commission listing while edit/
if (this->context->controller->controller_name == 'AdminKbCommission') {
this->context->controller->addCSS($this->_path . 'views/css/admin_affiliate_menu.css');
}
/End: Changes done by tarun gupta on 14th june 2019
to fix UI of commission listing while edit/
}
//Renders the footer link in the bottom menu of the page
public function hookDisplayMyAccountBlock()
{
config=Configuration::get(′kbaffiliatesbasicsthis->context->shop->id);
/**
Start Changes for PS8 and PHP8 Compatibility - Using json_decode
//Renders the field to enter the registration code
public function hookDisplayCustomerAccountForm()
{
config=Configuration::get(′kbaffiliatesbasicsthis->context->shop->id);
/**
Start Changes for PS8 and PHP8 Compatibility - Using json_decode
NAAug2023 json_decode
@date 29-08-2023
@author Nikhil Aggarwal
/
config=jsondecode(config, true);
// Changes end by Nikhil
$flag = false;
/ Start: changes done by tarun gupta on 3rd-jun-2019 for check referal system method is enable or not*/
if (isset(config['referral_systems']) && count(config['referral_systems']) > 0) {
foreach (config[′referralsystems′]ascon) {
if (con == 'code') {
flag = true;
}
}
}
/* End: changes done by tarun gupta on 3rd-jun-2019 for check referal system method is enable or not*/
// Renders the form for the affiliate customers
public function hookDisplayAdminCustomersForm(param)
{
config = Configuration::get('kb_affiliates_basic_settings', false, null, $this->context->shop->id);
/**
Start Changes for PS8 and PHP8 Compatibility - Using json_decode
NAAug2023 json_decode
@date 29-08-2023
@author Nikhil Aggarwal
*/
config=jsondecode(config, true);
// Changes end by Nikhil
if (config['enable'] == 1) {
unset(param);
this−>context−>controller−>addJS(this->_path . 'views/js/admin/affiliate_form.js');
this−>context−>controller−>addJS(this->_path . 'views/js/velovalidation.js');
return $this->renderSellerSettingForm();
}
}
// Creates the cookie in case the code is present in the link or the voucher added in the cart is of an affilaite customer
public function hookDisplayHeader()
{
config=Configuration::get(′kbaffiliatesbasicsthis->context->shop->id);
/**
Start Changes for PS8 and PHP8 Compatibility - Using json_decode
NAAug2023 json_decode
@date 29-08-2023
@author Nikhil Aggarwal
/
config=jsondecode(config, true);
// Changes end by Nikhil
if (config[′enable′]!=1)returnfalse;flag = false;
referralcode=referral_code)) {
if ((bool) this->context->customer->isLogged()) {
id_customer = $this->context->customer->id;
/*
Start Changes to fix the static call to function issue
NAAug2023 static
@date 29-08-2023
@author Nikhil Aggarwal
*/
KbReferrals=newKbReferrals();referral_existence = id_customer);
// Changes end by Nikhil
if (flag = true;
} else {
return;
}
}
foreach (con) {
if (con == 'social' || flag = true;
}
}
// Function for showing the module front link in the My Account section
public function hookDisplayCustomerAccount()
{
config=Configuration::get(′kbaffiliatesbasicsthis->context->shop->id);
/**
Start Changes for PS8 and PHP8 Compatibility - Using json_decode
Start Changes to fix the issue of affiliate account tab not visible when registration is off and custom is already an affiliate
NASep2023 affiliate_registration
Removed && $config['enable_registration'] == 1 condition from below if block
Added the condition in the else block by changing it to else if($config['enable_registration'] == 1)
@date 04-09-2023
@modifier Nikhil Aggarwal
*/
if (config['enable'] == 1 && customer_group == true) {
sqthis->context->customer->id;
sql);
if (isset(this->context->smarty->assign('front_url', this->name,
'Dashboard',
array(),
(bool)Configuration::get('PS_SSL_ENABLED')
));
result['status']);
this->context->smarty->fetch(.config['enable_registration'] == 1){
this->context->link->getModuleLink(
this->context->smarty->assign('registered', 0);
return this->name.'/views/templates/hook/front_myaccount_link.tpl');
}
// Changes end by Nikhil
}
}
//Add referral if there is a cookie set for referral code, this code will only work when the user registers on the store
public function hookActionCustomerAccountAdd(param)
{
if (param['newCustomer']->is_guest == 1) {
return false;
}
if (config['enable'] == 1 && config['enable_permenent_referral'] == 0) {
timeout=time()+86400∗config['referral_time_out'];
cookie=newCookie(′referrer′,′′,time_out);
cookie->__set('referrer', referral_code);
} else if (config['enable'] == 1 && config['enable_permenent_referral'] == 1) {
timeout=time()+86400∗999;cookie = new Cookie('referrer', '', timeout);cookie->__set('referrer', referral_code);
}
}
}
flag = false;
if (isset(config['referral_count'])) {
foreach (config['referral_count'] as key=>val) {
if (val == 'user_registration') {
flag = true;
}
}
} else {
return;
}
cookie=newCookie(′referrer′);if(config['enable'] == 1 && flag) {
if ((cookie->__isset('referrer') && !empty(cookie->__get('referrer'))) || Tools::getIsset('referral_code') && !empty(Tools::getValue('referral_code'))) {
affiliate_customer_obj = new KbAffiliateCustomers();
if (cookie->__isset('referrer') && !empty(cookie->__get('referrer'))) {
data=affiliate_customer_obj->getAffiliateCustomerByCode(cookie->__get('referrer'));
} else {
data = affiliate_customer_obj->getAffiliateCustomerByCode(Tools::getValue('referral_code'));
}
if (data['date_until'] == '0000-00-00' || data[′datdata['id_affiliate_customer']) && data['status'] == 1) {
//Add data in the referrals table
referral_obj = new KbReferrals();
referralobj−>referreddata['id_affiliate_customer'];
referralobj−>idcustparam['newCustomer']->id;
referralobj−>refreferral_obj->status = config[′referraldereferral_obj->date_added = date("Y-m-d");
$referral_obj->save();
//Add data in the commission table
commissionobj=newKbCommission();commission_obj->id_affiliate_referrals = Db::getInstance()->Insert_ID();
commissionobj−>idadata['id_affiliate_customer'];
//Add referral when order is placed
public function hookDisplayOrderConfirmation(param)
{
config = Configuration::get('kb_affiliates_basic_settings', false, null, $this->context->shop->id);
/**
Start Changes for PS8 and PHP8 Compatibility - Using json_decode
NAAug2023 json_decode
@date 29-08-2023
@author Nikhil Aggarwal
*/
config=jsondecode(config, true);
// Changes end by Nikhil
flag=false;if(isset(config['referral_count'])) {
foreach (config[′referralcountkey => val) {
if (val == 'order_placed') {
flag = true;
}
}
} else {
return;
}
cookie = new Cookie('referrer');
if (config['enable'] == 1 && flag) {
if (cookie->__isset('referrer') && !empty(cookie->__get('referrer'))) {
/** Start : changes done by Tarun gupta on 4th june 2019
to add a feature multiple commission**/
if ((bool) this->context->customer->isLogged()) {
id_customer = $this->context->customer->id;
/**
Start Changes to fix the static call to function issue
NAAug2023 static
@date 29-08-2023
@author Nikhil Aggarwal
*/
KbReferrals=newKbReferrals();referral_existence = KbReferrals−>checkReferralExid_customer);
// Changes end by Nikhil
if ($referral_existence == 0) {
} else {
/**
Start Changes to fix the static call to function issue
NAAug2023 static
@date 29-08-2023
@author Nikhil Aggarwal
*/
KbReferrals=newKbReferrals();referrer_id = KbReferrals−>getReferrerIdByCustomerId(id_customer);
// Changes end by Nikhil
referrercustomerreferrer_id);
referralcode=referrer_customer_obj->referral_code;
cookie->__unset('referrer');
cookie = new Cookie('referrer');
cookie->__set('referrer', referral_code);
if (referrer_customer_obj->enable_disable_multiple_commission == 1) {
if (referrer_customer_obj->use_global_orders_count == 1) {
count=config['disable_commission_after'];
} else {
count=referrer_customer_obj->disable_commission_after;
}
/**
Start Changes to fix the static call to function issue
NAAug2023 static
@date 29-08-2023
@author Nikhil Aggarwal
/
referralcount=KbReferrals->getReferralCountByReferrerId(referrerid,id_customer);
// Changes end by Nikhil
if (count>referral_count || $count == 0) {
} else {
return false;
}
} else {
return false;
}
}
}
/* End : changes done by Tarun gupta on 4th june 2019
Start Changes to fix the static call to function issue
NAAug2023 static
@date 29-08-2023
@author Nikhil Aggarwal
*/
KbCommission=newKbCommission();referral_existence = KbCommission−>checkOrderReferenceExistence(order_reference);
// Changes end by Nikhil
if (referral_existence == 0) {
if (isset(data['id_affiliate_customer']) && data['status'] == 1) {
//Add data in the referrals table
referral_obj = new KbReferrals();
referralobj−>referreddata['id_affiliate_customer'];
referralobj−>idcustthis->context->customer->id;
referralobj−>referrreferral_obj->status = config[′referraldereferral_obj->date_added = date("Y-m-d");
$referral_obj->save();
//Add data in the commission table
commissionobj=newKbCommission();commission_obj->id_affiliate_referrals = Db::getInstance()->Insert_ID();
commissionobj−>idadata['id_affiliate_customer'];
$order_obj = new Order((int) Tools::getValue('id_order'));
affiliate_customer_code_obj->save();
}
cookie->__unset('referrer');
/** Start : changes done by Tarun gupta on 4th june 2019
to add a feature multiple commission**/
} else {
cookie=newCookie(′referrer′);cookie->__unset('referrer');
return false;
}
} else {
if ((bool) this->context->customer->isLogged()) {
count = -1;
idcustomer=this->context->customer->id;
/**
Start Changes to fix the static call to function issue
NAAug2023 static
@date 29-08-2023
@author Nikhil Aggarwal
/
KbReferrals=newKbReferrals();referrer_id = id_customer);
// Changes end by Nikhil
referrer_id);
referrer_customer_obj->referral_code;
referral_code);
if (referrer_customer_obj->use_global_orders_count == 1) {
config['disable_commission_after'];
} else {
referrer_customer_obj->disable_commission_after;
}
}
/*
Start Changes to fix the static call to function issue
NAAug2023 static
@date 29-08-2023
@author Nikhil Aggarwal
/
referralcount=KbReferrals->getReferralCountByReferrerId(referrid_customer);
// Changes end by Nikhil
if (referral_count || affiliate_customer_obj = new KbAffiliateCustomers();
affiliate_customer_obj->getAffiliateCustomerByCode(data['date_until'] == '0000-00-00' || order_reference_obj = new Order((int) Tools::getValue('id_order'));
order_reference_obj->reference;
/*
Start Changes to fix the static call to function issue
NAAug2023 static
@date 29-08-2023
@author Nikhil Aggarwal
*/
KbCommission=newKbCommission();referral_existence = order_reference);
// Changes end by Nikhil
if (data['id_affiliate_customer']) && referral_obj = new KbReferrals();
data['id_affiliate_customer'];
this->context->customer->id;
referral_obj->status = referral_obj->date_added = date("Y-m-d");
$referral_obj->save();
//Add data in the commission table
commissionobj=newKbCommission();commission_obj->id_affiliate_referrals = Db::getInstance()->Insert_ID();
commissionobj−>idadata['id_affiliate_customer'];
$order_obj = new Order((int) Tools::getValue('id_order'));
/** End : changes done by Tarun gupta on 4th june 2019
to add a feature multiple commission**/
}
}
//Renders form in the admins customer panel
protected function renderSellerSettingForm()
{
helper=newHelperForm();id_customer = (int) Tools::getValue('id_customer');
idaffiliatecustomer=(int)Tools::geoptions_vouchers = array();
To get id customer and to affiliate customer through admin*/
array(
'type' => 'hidden',
// 'label' => $this->l('Referral rate for user registration'),
'name' => 'id_customer',
'col' => 1,
),
/** End : changes done by tarun gupta on 3rd-jun-2019
To get id customer and to affiliate customer through admin*/
/****/
/** Start: changes done by tarun gupta on 4th june 2019
to add a feature for multiple commission**/
array(
'type' => 'switch',
'label' => this−>l(′Enabledisablemultiplecommission′),this->l('Enable disable multiple commission feature for the affilaite customers'),
'values' => array(
array(
'value' => 1
),
array(
'value' => 0
)
),
),
array(
'type' => 'switch',
'label' => this−>l(′UseglobalCthis->l('If this field is enabled then the number of orders will be the global number of orders entered'),
'name' => 'use_global_orders_count',
'values' => array(
array(
'value' => 1
),
array(
'value' => 0
)
),
),
array(
'type' => 'text',
'label' => $this->l('Disable Commission After'),
'name' => 'disable_commission_after',
'col' => 3,
'suffix' => 'orders',
),
/** End: changes done by tarun gupta on 4th june 2019
to add a feature for multiple commission**/
array(
'type' => 'switch',
'label' => this−>this->l('If this will be enabled then a voucher will be generated according to the global configuration'),
'values' => array(
array(
'value' => 1
),
array(
'value' => 0
)
),
),
array(
'type' => 'select',
'label' => options_vouchers,
'id' => 'id',
'name' => 'name',
),
),
array(
'type' => 'text',
'label' => this->l('Please note that the voucher currency will be according to the currenct currency available'),
),
array(
'type' => 'text',
'label' => this->l('Voucher quantity per user'),
// 'name' => 'voucher_quan_per',
// 'col' => 1,
// ),
/** Start: Changes done by tarun gupta on 3rd june 2019
to add a field to enter a custom voucher code**/
array(
'type' => 'text',
'label' => this−>l(′CouponCode′),′name′=>′vouchercode′,′col′=>4,′desc′=>this->l('First enter the coupon code here & then click on the Generate button. If you want it to generate the code randomly then leave it blank.'),
),
/** End: Changes done by tarun gupta on 3rd june 2019
to add a field to enter a custom voucher code**/
array(
'type' => 'textarea',
'label' => this−>l(′Vouchers′),′name′=>′vouchers′,′col′=>5,′desc′=>this->l('If you want to remove the voucher then just disable it from the back office, it will not be shown to the affiliate customer also'),
'readonly' => true
),
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'btn btn-default pull-right form_kb_affiliate_customer'
),
)
);
languages=Language::getLanguages();foreach(languages as k=>language) {
languages[k]['is_default'] = ((int) (language[′idlang′this->context->language->id));
}
To get customer id and to affiliate user through admin*/
$helper->fields_value['id_customer'] = (int) Tools::getValue('id_customer');
/** End : changes done by tarun gupta on 3rd-jun-2019
To get customer id and to affiliate user through admin*/
/** Start: changes done by tarun gupta on 4th june 2019
to add a feature for multiple commission**/
helper−>fieldsvalue[′enabledisablemultiplecommission′]=affliate_obj->enable_disable_multiple_commission;
helper−>fieldsvaaffliate_obj->use_global_orders_count;
helper−>fieldsvaaffliate_obj->disable_commission_after;
/** End: changes done by tarun gupta on 4th june 2019
to add a feature for multiple commission**/
kbformcontents=helper->generateForm(array($fields_form));
Mail::Send(
newcustomer−>idlang,′registrationadmin′,this->l('A new affiliate has registered on your store'),
array(
'{affiliate_name}' => customerFormData['first_name'] . ' ' . customerFormData['last_name'],
'{affiliate_id}' => customerFormData[′emailbase_url,
'{shop_name}' => new_customer->id_shop
);
}
}
}
//Generate randome number to save it as the referral code for the affiliate customers
public function randomNumber(size)
{
alpha_key = '';
$keys = range('A', 'Z');
for (i=0;i < 2; i++) {
alpha_key .= keys[arrayrand(keys)];
}
length=size - 2;
key=′′;keys = range(0, 9);
for (i=0;i < length;i++) {
key.=keys[array_rand($keys)];
}
return alphakey.key;
}
public function getVoucher(data)
{
code = $this->randomNumber(8);
Db::getInstance()->execute(
'INSERT INTO ' . DB_PREFIX . 'cart_rule_shop
set id_cart_rule = ' . (int) cartruleid.′,′.′idshop=′.(int)this->context->shop->id
);
/**
Fixes to add voucher for all the available languages as it was being saved blank for other languages. So we have added the same to all the languages availble on store
@modifier Pragya Maurya
@date 20-03-2024
PMMar2024 voucher-lang-fixes
*/
languages=Language::getLanguages(false);foreach(languages as lang) {
Db::getInstance()->execute(
'INSERT INTO ' . _DB_PREFIX_ . 'cart_rule_lang
set id_cart_rule = ' . (int) cart_rule_id . ','
. 'id_lang = ' . (int) $lang['id_lang'] . ',
name = "AFFILIATE"'
);
}
//Ends here
return $code;
}
private function checkSecureUrl()
{
customsslvar=0;if(isset(_SERVER['HTTPS'])) {
if (_SERVER['HTTPS'] == 'on') {
custom_ssl_var = 1;
}
} elseif (isset(_SERVER['HTTP_X_FORWARDED_PROTO']) && _SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
custom_ssl_var = 1;
}
if ((bool) Configuration::get('PS_SSL_ENABLED') && custom_ssl_var == 1) {
return true;
} else {
return false;
}
}
//changes end
}" y dentro del modulo en esta carpeta modules/kbaffiliates/override/classes hay el CartRule.php que esta asi "
@copyright 2018 knowband
@license see file: LICENSE.txt
@category PrestaShop Module
*/
if (!defined('PS_VERSION')) {
exit;
}
class CartRule extends CartRuleCore
{
public function checkReferralExistenceByCustomerId(id_customer)
{
count_exist = 0;
countexist=Db::getInstance()−>getValue(id_customer);
return $count_exist;
}
/**
Check if this CartRule can be applied.
@param Context $context Context instance
@param bool $alreadyInCart Check if the voucher is already on the cart
@param bool $display_error Display error
@param bool $check_carrier
@param bool $useOrderPrices
@return bool|mixed|string
/
/*
Start Changes to make the checkValidity() override compatible with latest versions
NAAug2023 checkValidity
@date 28-08-2023
@modifier Nikhil Aggarwal
*/
public function checkValidity(Context context,alreadyInCart = false, displayerror=true,check_carrier = true, useOrderPrices = false)
{
if (!CartRule::isFeatureActive()) {
return false;
}
cart = $context->cart;
// All these checks are necessary when you add the cart rule the first time, so when it's not in cart yet
// However when it's in the cart and you are checking if the cart rule is still valid (when performing auto remove)
// these rules are outdated For example:
// - the cart rule can now be disabled but it was at the time it was applied, so it doesn't need to be removed
// - the current date is not in the range any more but it was at the time
// - the quantity is now zero but it was not when it was added
if (!alreadyInCart) {
if (!this->active) {
return (!displayerror)?false:this->trans('Este cupón está desactivado', [], 'Shop.Notifications.Error');
}
if (!this->quantity) {
return (!display_error) ? false : this->trans('Este cupón ya ha sido utilizado', [], 'Shop.Notifications.Error');
}
if (strtotime(this->date_from) > time()) {
return (!displayerror)?false:this->trans('Este cupón aún no es válido', [], 'Shop.Notifications.Error');
}
if (strtotime(this->date_to) < time()) {
return (!display_error) ? false : $this->trans('Este cupón ha caducado', [], 'Shop.Notifications.Error');
}
}
/** start : changes done by tarun gupta on 4th june 2019
to check the applied voucher is belongs to the first referrer or not**/
if (this->description == 'AFFILIATE') {
if ((bool) Context::getContext()->customer->isLogged()) {
id_customer = Context::getContext()->customer->id;
referralexistence=this->checkReferralExistenceByCustomerId((int) idcustomer);if(referral_existence == 0) {
} else {
//changes by tarun to resolve the inapropriate message problem reported by shubham
return (!displayerror)?false:this->trans('Oops, parece que ya has usado este cupón.', array(), 'Shop.Notifications.Error');
//changes over
}
}
}
/** End : changes done by tarun gupta on 4th june 2019
to check the applied voucher is belongs to the first referrer or not**/
/**
Start Changes to fix the issue of sql injection
Using int in the query
NASep2023 pSQL
@date 28-09-2023
@modifier Nikhil Aggarwal
/
if (cart->id_customer) {
quantityUsed = Db::getInstance()->getValue('
SELECT count()
FROM ' . _DB_PREFIX_ . 'orders o
LEFT JOIN ' . _DB_PREFIX_ . 'order_cart_rule ocr ON o.id_order = ocr.id_order
WHERE o.id_customer = ' . (int)cart−>idcustomer.′ANDocr.‘deleted‘=0ANDocr.‘idcartrule‘=′.(int)this->id . '
AND ' . (int) Configuration::get('PS_OS_ERROR') . ' != o.current_state
');
if ($alreadyInCart) {
// Sometimes a cart rule is already in a cart, but the cart is not yet attached to an order (when logging
// in for example), these cart rules are not taken into account by the query above:
// so we count cart rules that are already linked to the current cart but not attached to an order yet.
quantityUsed+=(int)Db::getInstance()−>getValue(cart->id_customer . ' AND c.id_cart = ' . (int)cart−>id.′ANDccr.idthis->id . ' AND o.id_order IS NULL
');
// Changes end by Nikhil
} else {
// When checking the cart rules present in that cart the request result is accurate
// When we check if using the cart rule one more time is valid then we increment this value
++quantityUsed;
}
if (quantityUsed > this->quantity_per_user) {
return (!display_error) ? false : $this->trans('Ya no puede utilizar este cupón (límite de uso alcanzado)', [], 'Shop.Notifications.Error');
}
}
// Get an intersection of the customer groups and the cart rule groups (if the customer is not logged in, the default group is Visitors)
if (this->group_restriction) {
id_cart_rule = (int) Db::getInstance()->getValue('
SELECT crg.id_cart_rule
FROM ' . DB_PREFIX . 'cart_rule_group crg
WHERE crg.id_cart_rule = ' . (int) this−>id.′ANDcrg.idgroup′.((int)cart->id_customer ? 'IN (SELECT cg.id_group FROM ' . DB_PREFIX . 'customer_group cg WHERE cg.id_customer = ' . (int) cart−>id_cart_rule) {
return (!displayerror)?false:this->trans('No puede utilizar este cupón', [], 'Shop.Notifications.Error');
}
}
// Check if the customer delivery address is usable with the cart rule
if (this->country_restriction) {
if (!cart->id_address_delivery) {
return (!displayerror)?false:this->trans('Debe elegir una dirección de entrega antes de aplicar este cupón a su pedido', [], 'Shop.Notifications.Error');
}
idcartrule=(int)Db::getInstance()−this->id . '
AND crc.id_country = (SELECT a.id_country FROM ' . DB_PREFIX . 'address a WHERE a.id_address = ' . (int) cart−>idaddressid_cart_rule) {
return (!displayerror)?false:this->trans('No puede utilizar este cupón en su país de entrega', [], 'Shop.Notifications.Error');
}
}
// Check if the carrier chosen by the customer is usable with the cart rule
if (this->carrier_restriction && check_carrier) {
if (!cart->id_carrier) {
return (!display_error) ? false : this->trans('Debe elegir un transportista antes de aplicar este cupón a su pedido', [], 'Shop.Notifications.Error');
}
id_cart_rule = (int) Db::getInstance()->getValue('
SELECT crc.id_cart_rule
FROM ' . DB_PREFIX . 'cart_rule_carrier crc
INNER JOIN ' . DB_PREFIX . 'carrier c ON (c.id_reference = crc.id_carrier AND c.deleted = 0)
WHERE crc.id_cart_rule = ' . (int) this−>id.′ANDc.idcarrier=′.(int)cart->id_carrier);
if (!id_cart_rule) {
return (!display_error) ? false : $this->trans('No puede utilizar este cupón con este transportista', [], 'Shop.Notifications.Error');
}
}
if (this->reduction_exclude_special) {
products = cart−>getProducts();is_ok = false;
foreach (productsasproduct) {
if (!product['reduction_applies']) {
is_ok = true;
break;
}
}
if (!is_ok) {
return (!display_error) ? false : $this->trans('No puede utilizar este cupón en productos en oferta', [], 'Shop.Notifications.Error');
}
}
// Check if the cart rules appliy to the shop browsed by the customer
if (this->shop_restriction && context->shop->id && Shop::isFeatureActive()) {
idcartrule=(int)Db::getInstance()−this->id . '
AND crs.id_shop = ' . (int) context−>shop−>id);if(!id_cart_rule) {
return (!displayerror)?false:this->trans('No puede utilizar este cupón', [], 'Shop.Notifications.Error');
}
}
// Check if the products chosen by the customer are usable with the cart rule
if (this->product_restriction) {
r = this−>checkProductRestrictionsFromCart(context->cart, false, displayerror,alreadyInCart);
if (r !== false && display_error) {
return r;
} elseif (!r && !$display_error) {
return false;
}
}
// Check if the cart rule is only usable by a specific customer, and if the current customer is the right one
if (this->id_customer && cart->id_customer != this->id_customer) {
if (!Context::getContext()->customer->isLogged()) {
return (!display_error) ? false : (this−>trans(′Nopuedeutilizarestecupoˊn′,[],.this->trans('Primero inicie sesión', [], 'Shop.Notifications.Error'));
}
return (!displayerror)?false:this->trans('No puede utilizar este cupón', [], 'Shop.Notifications.Error');
}
if (this->minimum_amount && check_carrier) {
// Minimum amount is converted to the contextual currency
minimumamount=this->minimum_amount;
if (this->minimum_amount_currency != Context::getContext()->currency->id) {
minimum_amount = Tools::convertPriceFull(minimumamount,newCurrency(this->minimum_amount_currency), Context::getContext()->currency);
}
if (cartTotal<minimum_amount) {
return (!displayerror)?false:this->trans('El importe mínimo para beneficiarse de este cupón es de %s.', [Tools::getContextLocale(context)−>formatPrice(minimum_amount, $context->currency->iso_code)], 'Shop.Notifications.Error');
}
}
/* This loop checks:
if the voucher is already in the cart
if a non compatible voucher is in the cart
if there are products in the cart (gifts excluded)
Important note: this MUST be the last check, because if the tested cart rule has priority over a non combinable one in the cart, we will switch them
*/
nbproducts=Cart::getNbProducts(cart->id);
otherCartRules=[];if(check_carrier) {
otherCartRules=cart->getCartRules(CartRule::FILTER_ACTION_ALL, false);
}
if (count(otherCartRules)) {
foreach (otherCartRules as otherCartRule) {
if (otherCartRule['id_cart_rule'] == this->id && !alreadyInCart) {
return (!displayerror)?false:this->trans('Este cupón ya está en su cesta', [], 'Shop.Notifications.Error');
}
giftProductQuantity=cart->getProductQuantity(otherCartRule[′giftpotherCartRule['gift_product_attribute']);
if (otherCartRule['gift_product'] && !empty(giftProductQuantity['quantity'])) {
--$nb_products;
}
if (this->cart_rule_restriction && otherCartRule['cart_rule_restriction'] && otherCartRule[′idcartrule′]!=this->id) {
this->id . ' AND id_cart_rule_2 = ' . (int) otherCartRule[′ithis->id . ' AND id_cart_rule_1 = ' . (int) otherCartRule[′idcombinable) {
cartrule=newCartRule((int)otherCartRule['id_cart_rule'], cart−cart_rule->priority <= this->priority) {
return (!display_error) ? false : this−>trans(cart_rule->name], 'Shop.Notifications.Error');
} else {
// But if the cart rule that is tested has priority over the one in the cart, we remove the one in the cart and keep this new one
cart−>removeCartRule(cart_rule->id);
}
}
}
}
}
if (!nb_products) {
return (!display_error) ? false : $this->trans('La cesta está vacía', [], 'Shop.Notifications.Error');
}
// Check if order cart rule was removed from back office
removedordercartRuleid=this->id . '
AND ocr.deleted = 1
AND o.id_cart = ' . (int)cart−>id);if(removed_order_cartRule_id) {
return (!displayerror)?false:this->trans('No puede utilizar este cupón porque se ha eliminado manualmente.', [], 'Shop.Notifications.Error');
}
if (!$display_error) {
return true;
}
}
}
Puedes implementar esta lógica en la función checkValidity del CartRule. Aquí te muestro una forma de hacerlo:
Identificar al usuario que intenta usar el cupón: Necesitas encontrar el ID del cliente actual.
Comprobar si el cliente es el embajador asignado al cupón: Busca si el cliente que intenta usar el cupón es el embajador para el mismo. Si es así, impide que aplique el cupón.
A continuación, te muestro cómo puedes realizar estos pasos dentro de checkValidity:
php
public function checkValidity(Context $context, $alreadyInCart = false, $display_error = true, $check_carrier = true, $useOrderPrices = false)
{
if (!CartRule::isFeatureActive()) {
return false;
}
$cart = $context->cart;
// ...
// Evitar que el embajador use su propio cupón
if ($this->description == 'AFFILIATE') {
if ((bool) Context::getContext()->customer->isLogged()) {
$id_customer = Context::getContext()->customer->id;
// Comprobar si este cupón pertenece a este embajador y por ende no debería ser utilizado por él
$data_affiliate = Db::getInstance()->getRow('SELECT * FROM '._DB_PREFIX_.'affiliate_customers WHERE id_cart_rules LIKE "%'.pSQL($this->code).'%"');
if (isset($data_affiliate['id_customer']) && $data_affiliate['id_customer'] == $id_customer) {
return (!$display_error) ? false : $this->trans('Los embajadores no pueden usar sus propios cupones.', [], 'Shop.Notifications.Error');
}
}
}
// ...
if (!$display_error) {
return true;
}
}
Esto debería solucionar el problema, verificando si el usuario actual es el embajador que generó el cupón. Si lo es, la función checkValidity devolverá un error que dice que los embajadores no pueden usar sus propios cupones.
Notas Adicionales:
Asegúrate de tener una buena estrategia de prueba después de implementar esta lógica para verificar que funcione correctamente en todos los escenarios posibles.
Considera la posibilidad de revisar otras partes del código que puedan requerir ajustes similares relacionados con el uso de cupones por parte de embajadores.