Support

Home Forums Event Espresso Premium Is there a maximum limit of association of promotional codes to events?

Is there a maximum limit of association of promotional codes to events?

Posted: November 8, 2018 at 1:27 am

Viewing 7 reply threads


guiapenin

November 8, 2018 at 1:27 am

Good Morning,

We have an application that generates massive one-use codes applied to an event. We have to generate 15,000 promo codes with a 100% discount. We have put the ticket limit at 20,000.

We are generating 2000 codes in 2000, but when we pass the 8,000 discount codes associated with an event, we are prevented from editing the event.
When we give it to edit or create an event, it does not open and it gives us a 504 timeout error.

If you delete the codes inserted in wp_esp_promotion, wp_esp_promotion_object, wp_esp_price, the editing and creation of events works perfectly.

Is there a maximum limit of association of promotional codes to events or can they be limitations of our hosting server?

We have another open incident with this problem, but we have redirected it here once we have seen the causes of the error.

In WP-Debug we get the following error:
[07-Nov-2018 19:09:23 UTC] PHP Warning: mysqli_query(): MySQL server has gone away in /home/salonesgqb/www/wp-includes/wp-db.php on line 1924
[07-Nov-2018 19:09:23 UTC] PHP Warning: mysqli_query(): Error reading result set’s header in /home/salonesgqb/www/wp-includes/wp-db.php on line 1924

[07-Nov-2018 19:11:54 UTC] PHP Warning: mysqli_query(): MySQL server has gone away in /home/salonesgqb/www/wp-includes/wp-db.php on line 1924

[07-Nov-2018 19:11:54 UTC] PHP Warning: mysqli_query(): Error reading result set’s header in /home/salonesgqb/www/wp-includes/wp-db.php on line 1924

In the logs of the server:
[Wed Nov 07 20:14:36 2018] [error] [client 88.12.55.183] [host salonesguiapenin.com] Script timed out before returning headers: admin.php, referer: https://salonesguiapenin.com/wp-admin/admin.php?page=espresso_events
[Wed Nov 07 20:16:49 2018] [error] [client 81.33.76.122] [host salonesguiapenin.com] AH10141: FastCGI: comm with server “/homez.376/salonesgqb/www/wp-admin/admin.php” aborted: idle timeout (300 sec), referer: https://salonesguiapenin.com/wp-admin/admin.php?page=espresso_events
[Wed Nov 07 20:16:49 2018] [error] [client 81.33.76.122] [host salonesguiapenin.com] AH10149: FastCGI: incomplete headers (0 bytes) received from server “/homez.376/salonesgqb/www/wp-admin/admin.php”, referer: https://salonesguiapenin.com/wp-admin/admin.php?page=espresso_events
[Wed Nov 07 20:16:49 2018] [error] [client 81.33.76.122] [host salonesguiapenin.com] AH10157: FastCGI: An error happend on Fastcgi processing, fallback to CGI, referer: https://salonesguiapenin.com/wp-admin/admin.php?page=espresso_events
[Wed Nov 07 20:17:49 2018] [error] [client 81.33.76.122] [host salonesguiapenin.com] Script timed out before returning headers: admin.php, referer: https://salonesguiapenin.com/wp-admin/admin.php?page=espresso_events

I attach the information of Health Check:

### WordPress ###

Version: 4.9.8
Language: es_ES
Permalink structure: /%postname%/
Is this site using HTTPS?: Yes
Can anyone register on this site?: No
Default comment status: closed
Is this a multisite?: No
User Count: 8
Communication with WordPress.org: WordPress.org is reachable
Create loopback requests: The loopback request to your site failed, this may prevent WP_Cron from working, along with theme and plugin editors.<br>Error encountered: (0) cURL error 28: Operation timed out after 10001 milliseconds with 0 bytes received

### Installation size ###

Uploads Directory: 6.52 GB
Themes Directory: 5.11 MB
Plugins Directory: 74.72 MB
Database size: 69.98 MB
Whole WordPress Directory: 7.16 GB
Total installation size: 7.23 GB

### Active Theme ###

Name: Januas | Shared By showthemes.com
Version: 1.50
Author: Showthemes
Author website: http://www.showthemes.com
Parent theme: Not a child theme
Supported theme features: custom-header, post-thumbnails, automatic-feed-links, woocommerce, menus, widgets

### Active Plugins (36) ###

Akismet Anti-Spam: Version 4.0.8 by Automattic
CF7 Customizer: Version 1.1.1 by WPCouple(Ahmad Awais & Maedah Batool)
Contact Form 7: Version 5.0.5 by Takayuki Miyoshi
Duplicate Post: Version 3.2.2 by Enrico Battocchi
Easy Updates Manager: Version 8.0.2 by Easy Updates Manager Team
Event Espresso: Version 4.9.67.p by Event Espresso
Event Espresso – Barcode Scanner (EE 4.6.0+): Version 1.0.11.p by Event Espresso
Event Espresso – Códigos Masivos: Version 0.1(EE4) by Event Espresso – Códigos Masivos
Event Espresso – Estadisticas: Version 0.1 by Flying Donkey
Event Espresso – Events Table View Template (EE 4.4.9+): Version 1.3.9.p by Event Espresso
Event Espresso – Grid View Template (EE 4.4.9+): Version 1.2.4.p by Event Espresso
Event Espresso – MailChimp (EE4.4.5+): Version 2.3.5.p by Event Espresso
Event Espresso – Pasarela de pago para Redsýs (modulosdepago.es): Version 4.0 by Mikel Martin (ZhenIt Software)
Event Espresso – Pasarela de pago para Redsýs (modulosdepago.es): Version 1.2 by Mikel Martin (ZhenIt Software)
Event Espresso – Payment Methods Pro (EE 4.9.32+): Version 1.0.1.p by Event Espresso
Event Espresso – People Addon (EE 4.5+): Version 1.0.7.p by Event Espresso
Event Espresso – Promotions (EE 4.9.10+): Version 1.0.12.p by Event Espresso
Event Espresso – States/Provinces Pack: Spain: Version 1.0 by Event Espresso
Event Espresso – Ticketing (EE 4+): Version 1.0.8.p by Event Espresso
Health Check & Troubleshooting: Version 1.2.1 by The WordPress.org community
Loco Translate: Version 2.1.5 by Tim Whitlock
Photo Gallery: Version 1.5.7 by Photo Gallery Team
Popup Maker: Version 1.7.30 by WP Popup Maker
Really Simple SSL: Version 3.1.1 by Rogier Lankhorst, Mark Wolters
Recent Posts Widget With Thumbnails: Version 6.2.1 by Martin Stehle
Scripts n Styles: Version 3.4.4 by unFocus Projects
Simple Custom CSS: Version 4.0.1 by John Regan, Danny Van Kooten
Simple Tooltips: Version 2.1.3 by Justin Saad
Site plugin for januasmodificaciones: No version or author information available
TinyMCE Advanced: Version 4.8.0 by Andrew Ozz
User Role Editor: Version 4.46 by Vladimir Garagulya
Velvet Blues Update URLs: Version 3.2.8 by VelvetBlues.com
Wordfence Security: Version 7.1.17 by Wordfence
WP-DBManager: Version 2.79.2 by Lester ‘GaMerZ’ Chan
WPFront Scroll Top: Version 2.0.1 by Syam Mohan
wpMandrill: Version 1.33 by Mandrill

### Inactive Plugins (8) ###

Duplicator: Version 1.2.52 by Snap Creek
Event Espresso – Calendar (EE 4.3+): Version 3.2.12.p by Event Espresso
Event Espresso – Social Sharing (EE4.4.4+): Version 1.0.p by Event Espresso
GTranslate: Version 2.8.43 by Translate AI Multilingual Solutions
Polylang: Version 2.3.11 by Frédéric Demarle
Polylang Theme Strings: Version 4.0 by Modeewine
Tooltips: Version 5.2.3 by Tomas Zhu | Docs | FAQ | Premium Support
WP-Optimize: Version 2.2.6 by David Anderson, Ruhani Rabin, Team Updraft

### Media handling ###

Active editor: WP_Image_Editor_Imagick
Imagick Module Version: 1673
ImageMagick Version: ImageMagick 6.8.9-9 Q16 i586 2018-06-26 http://www.imagemagick.org
Imagick Resource Limits:
area:
disk: -1
file: 49152
map:
memory: 2 GB
thread: 20
GD Version: bundled (2.1.0 compatible)
Ghostscript Version: 9.06

### Server ###

Server architecture: Linux 4.14.19-ovh-vps-grsec-zfs-classid x86_64
PHP Version: 5.6.38
PHP SAPI: fpm-fcgi
PHP max input variables: 16000
PHP time limit: 500
PHP memory limit: 512M
Max input time: -1
Upload max filesize: 128M
PHP post max size: 130M
cURL Version: 7.38.0 OpenSSL/1.0.1t
SUHOSIN installed: No
Is the Imagick library available: Yes
htaccess rules: Your htaccess file only contains core WordPress features

### Database ###

Extension: mysqli
Server version: 5.5.60-0+deb7u1-log
Client version: mysqlnd 5.0.11-dev – 20120503 – $Id: 76b08b24596e12d4553bd41fc93cccd5bac2fe7a $
Database prefix: wp_

### WordPress Constants ###

ABSPATH: /home/salonesgqb/www/
WP_HOME: Undefined
WP_SITEURL: Undefined
WP_DEBUG: Enabled
WP_MAX_MEMORY_LIMIT: 512M
WP_DEBUG_DISPLAY: Disabled
WP_DEBUG_LOG: Enabled
SCRIPT_DEBUG: Disabled
WP_CACHE: Disabled
CONCATENATE_SCRIPTS: Undefined
COMPRESS_SCRIPTS: Undefined
COMPRESS_CSS: Undefined
WP_LOCAL_DEV: Undefined

### Filesystem Permissions ###

The main WordPress directory: Writable
The wp-content directory: Writable
The uploads directory: Writable
The plugins directory: Writable
The themes directory: Writable

`


Tony

  • Support Staff

November 8, 2018 at 5:12 am

Is there a maximum limit of association of promotional codes to events or can they be limitations of our hosting server?

We don’t have limits on the number of promotions, with a ‘MySQL server has gone away’ error your likely hitting a limitation of your hosting, but that may also mean we need to alter something with our queries.

We’ll need to so do some digging into this, may I ask, how are you creating the promotion codes currently?


guiapenin

November 8, 2018 at 5:28 am

Hello,

but that may also mean we need to alter something with our queries.

While creating or editing an Event, seems like the program is reading all promotions and prices. This makes the program more slow in time, while promotions are growing in number.

We’ll need to so do some digging into this, may I ask, how are you creating the promotion codes currently?

We have PHP script that make this inserts:
INSERT INTO wp_esp_price (PRT_ID,PRC_amount,PRC_name, PRC_desc, PRC_wp_user, PRC_overrides, PRC_order)
INSERT INTO wp_esp_promotion (PRO_code,PRC_ID,PRO_uses, PRO_accept_msg, PRO_decline_msg, PRO_start, PRO_end, PRO_scope)
INSERT INTO wp_esp_promotion_object (PRO_id, OBJ_id, POB_type, POB_used)

We read from another tables and insert the data as needed in those fields.

All help is appreciated.

Best Regards


Tony

  • Support Staff

November 8, 2018 at 5:42 am

While creating or editing an Event, seems like the program is reading all promotions and prices. This makes the program more slow in time, while promotions are growing in number.

It’s not reading promotions, but promotions create prices, and it does pull in all default prices, are you setting the PRC_is_default to 1 on those rows?

We have PHP script that make this inserts:

Can you send me the script so I can try and reproduce this locally?


guiapenin

November 8, 2018 at 5:58 am

Hello,

are you setting the PRC_is_default to 1 on those rows?

Yep, that field is set to 1 automatically by default. Shall we set the field to 0?

Can you send me the script so I can try and reproduce this locally?

Thats a module, and it adds to WordPress tools (to access when installed: Menu -> tools -> Codigos Masivos)

I paste the code here:


<?php
/*
  Plugin Name: Event Espresso - Códigos Masivos
  Plugin URI: http://www.guiapenin.com/
  Description: Permite crear códigos masivos y asignarlo a eventos.

  Version: 0.1(EE4)

  Author: Event Espresso - Códigos Masivos
  Author URI: http://www.guiapenin.com/

  Copyright (c) 2008-2012 Event Espresso  All Rights Reserved.

  This program 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 2 of the License, or
  (at your option) any later version.

  This program 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 this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

set_time_limit(500);
ini_set("memory_limit","500M");

function espresso_salones() {
	$wp_plugin_url = WP_PLUGIN_URL;
	$wp_content_url = WP_CONTENT_URL;
	define("ESPRESSO_SALONES_PLUGINPATH", "/" . plugin_basename(dirname(__FILE__)) . "/");
//	define("ESPRESSO_SALONES_PLUGINPATH", WP_PLUGIN_DIR . ESPRESSO_SALONES_PLUGINPATH);
	define("ESPRESSO_SALONES_PLUGINFULLURL", $wp_plugin_url . ESPRESSO_SALONES_PLUGINPATH);
	
?>
    <h3>Codigos Masivos</h3>
    <ul>
        <li>
            <p>Permite crear códigos masivos y asignarlo a eventos.</p>
            <p>Si subes un archivo csv con una columna con nombres de bodegas o colectivos genera códigos a partir de los nombres y pone como descripción el nombre del colectivo o bodega.</p>
            <p>Si introduces un código en el campo "Código:" se genrerara un único código, siempre que no hayas subido un archivo csv</p>
            <p>Si por contra, se deja el campo libre, se tienen en cuenta los campos para la generación automática de códigos</p>
            <p>Si...</p>
           
            <?php
				salones_form( '../wp-content/uploads/espresso/codes' );
            ?>
        </li>
    </ul>
<?php
}

/*
  uploader([int num_uploads [, arr file_types [, int file_size [, str upload_dir ]]]]);
  num_uploads = Number of uploads to handle at once.
  file_types = An array of all the file types you wish to use. The default is txt only.
  file_size = The maximum file size of EACH file. A non-number will results in using the default 1mb filesize.
  upload_dir = The directory to upload to, make sure this ends with a /
 */

function salones_form($download_dir = "../wp-content/uploads/espresso/codes") {
	global $wpdb;

	if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'salones_codes') {
		generar_codes( );
	}
//	if (!isset($_POST["submitted"])) {
        $form = "<form action='admin.php?page=espresso_salones&action=salones_codes' method='post' enctype='multipart/form-data'>
  					<input type='hidden' name='submitted' value='TRUE' id='" . time() . "'>
  					<input name='action' type='hidden' value='salones_codes' />
  					<input type='hidden' name='MAX_FILE_SIZE' value='1048576' />";
        $form .= '
  				<p>
  					<label for="codigos">Subir listado:</label><br/>
  					<input type="file" name="codigos" id="codigos" />
  					<p>
  					    Si subes este archivo se ignorara lo especificado en el campo cantidad, prefijo, sufijo y descripcion.
                        <label for="newcsv">CSV (cod|num cod|desc(opt)):</label><br/>
                        <input type="file" name="newcsv" id="newcsv" />
  					</p>
  				<p>
            		<label for="codigo">Código:</label><br/>
            		<input type="text" id="codigo" name="codigo" value="" size="100" />
	            </p>
	            <p>
	            	<label for="cantidad">Cantidad:</label><br/>
	            	<input type="text" id="cantidad" name="cantidad" value="1" />
	            </p>
	            <p>
	            	<label for="limite">Límite:</label><br/>
	            	<input type="text" id="limite" name="limite" value="1" />
	            </p>
	            <p>
	            	<label for="precio">Precio:</label><br/>
	            	<input type="text" id="precio" name="precio" value="1" />
	            </p>
	            <p>
	            	¿Es un porcentaje?<br/>
	            	<input type="radio" id="porcentajeY" name="porcentaje" value="2" />
	            	<label for="porcentajeY">Sí</label>
	            	<input type="radio" id="porcentajeN" name="porcentaje" value="1" />
	            	<label for="porcentajeN">No</label>
	            </p>
	            <p>
	            	<label for="prefijo">Prefijo:</label><br/>
	            	<input type="text" id="prefijo" name="prefijo" value="" />
	            </p>
	            <p>
	            	<label for="sufijo">Sufijo:</label><br/>
	            	<input type="text" id="sufijo" name="sufijo" value="" />
	            </p>
	            <p>
	            	<label for="descripcion">Descripción:</label><br/>
	            	<input type="text" id="descripcion" name="descripcion" value="" size="100" />
	            </p>';
        //metemos los eventos Comprobar la tabla
		$sql = "SELECT e.EVT_ID, e.DTT_name ";
        $sql .= " FROM wp_esp_datetime e WHERE DATE(DTT_EVT_end) >= DATE(NOW())  ORDER BY e.DTT_name";
		$events = $wpdb->get_results( $wpdb->prepare($sql, ''));
        if (count($events) > 0) {
	        $form .= '<p>Eventos: <br/>';
			$eventosGuardados = array();
	        foreach ($events as $event) {
				$repetido = false;
				if(count($eventosGuardados) > 0){
					foreach($eventosGuardados as $eventoGuardado){
						if($eventoGuardado->EVT_ID == $event->EVT_ID){
							$repetido = true;
						}
					}
				}
				
				if(!$repetido){
					$form .= '<input type="checkbox" name="eventos[]" id="evento_'.$event->EVT_ID.'" value="'.$event->EVT_ID.'" /> ';
					$form .= '<label for="evento_'.$event->EVT_ID.'">'.$event->DTT_name.'</label><br/>';
				}
				
				array_push($eventosGuardados,$event);
	        }
	        $form .= '</p>';
        }
        $form .= "<input class='button-primary' type='submit' value='Generar'></p></form>";
        echo($form);
        
        //Ahora imprimimos los archivos
        $codes = scandir($download_dir);
        rsort($codes);
        $files = '<br/><br/><strong>Archivos de Códigos:</strong><br/>';
        $f = false;
        foreach($codes as $code) {
        	if ($code != '.' && $code != '..' && strpos($code, 'codes-') !== false && strpos($code, '.txt') !== false ) {
        		$files .= '<a href="'.get_site_url().str_replace('..','',$download_dir).'/'.$code.'" target="_blank" >'.$code.'</a><br/>';
        		$f = true;
        	}
        }
        if ($f) {
        	echo $files;
        }
        	

}

function generar_codes() {
    global $wpdb;
    
    /**
     * Este generará X número de códigos únicos y creará los insert, tanto para los códigos como para su relación con el evento.
     * Los campos a rellenas son los siguientes y son indispensables para que todo funcione y sean únicos.
     */
	 function limpiar($s) {
    	$vocalti= array ("á","é","í","ó","ú","Á","É","Í","Ó","Ú");
    	$vocales= array ("a","e","i","o","u","A","E","I","O","U");
    	$s = str_replace($vocalti, $vocales, $s);
    	$s = str_replace("ñ","n",$s);
    	$s = str_replace("Ñ","N",$s);
    	$s = preg_replace("/[^a-zA-Z0-9]+/", "", $s);
    	return $s;
    }
	
    if(trim($_POST["codigo"]) != ""){
    	$codigo = limpiar($_POST["codigo"]);
    }
    $cantidad 	= $_POST["cantidad"]; //número de códigos a generar
    $limite 	= $_POST["limite"]; //número de usuos para cada código, si tienen que ser de un sólo uso 1, si tienen que ser ilimitados 0
    $precio 	= $_POST["precio"]; //precio de cada cupón descontado o porcentaje
    $porcentaje = $_POST["porcentaje"]; //porcentaje o precio Y o N
    $wp_user	= 2; //usuario que lo genera, 1 para admin
    $sufix		= $_POST["sufijo"]; //sufijo del código para que sea único
    $prefix		= $_POST["prefijo"]; //prefijo del código para que sea único
    $description= $_POST["descripcion"]; //descripción del código para su identificación.
    $eventos	= $_POST["eventos"]; //id de los eventos a los que asignar los códigos
    $codigos    = $_FILES["codigos"]; //archivo cvs de nombres para generar códigos
    $newcsv     = $_FILES['newcsv']; //archivo csv con orden -> codigo|numero de codigos a generar

    if ($porcentaje == '') {
    	$porcentaje = 1;
    }
    
    
    
    function codigo($length = 5, $prefix = '', $sufix = '') {
    	static $chars = '123456789ABCDEFGHJKLMNPQRSTWXYZ';
    	$max = strlen($chars) - 1;
    	$token = '';
    	for ($i = 0; $i < $length; ++$i)
    	{
    		$token .= $chars[(rand(0, $max))];
    	}
    
    	return $prefix . $token . $sufix;
    }
    $exportar_desc = false;
    $descriciones = array();
    if ($codigos['error'] == 0) {
    	if (($gestor = fopen($codigos["tmp_name"], "r")) !== FALSE) {
    		if ($cantidad > 0) {
    			$exportar_desc = true;
    			$codigos = array();
    			while (($datos = fgetcsv($gestor, 1000, ",")) !== FALSE) {
    				$title = ucwords(str_replace(' s.l.', '', strtolower(($datos[0]))));
    				$title = str_replace("'", " ", $title);
    				for ($i = 1; $i <= $cantidad; $i++) {
    					do {
    						$codigo = codigo(5,$prefix,$sufix);
    					} while (isset($codigos[$codigo]) && es_valido($codigo));
    					 
    					$codigos[$codigo] = $codigo;
    					$descriciones[$codigo] = $title;
    				}
    			}
    		}
    		fclose($gestor);
    	}
    } else {
        //Entra aqui si se a subido un CSV al nuevo campo $newcsv
        if ($newcsv['error'] == 0) {
            if (($gestor = fopen($newcsv["tmp_name"], "r")) !== FALSE) {
                $exportar_desc = true;
                $codigos = array();
                while (($datos = fgetcsv($gestor, 1000, ",")) !== FALSE) {
                    if(isset($datos[2]) && $datos[2] != ""){
                        $title = $datos[2];
                    }else{
                        $title = '';
                    }

                    $prefixcode = $datos[0];
                    $cantidad = intval($datos[1]);
                    for ($i = 1; $i <= $cantidad; $i++) {
                        do {
                            $codigo = codigo(5,$prefixcode,'');
                        } while (isset($codigos[$codigo]) && es_valido($codigo));

                        $codigos[$codigo] = $codigo;
                        $descriciones[$codigo] = $title;
                    }
                }
            }
        }else{
            $codigos = array();
        }
    }

    if (empty($codigos)) {
	    if(isset($codigo) && es_valido($codigo)){
	    	 $codigos[$codigo] = $codigo;
	    } else {
		    for ($i = 1; $i <= $cantidad; $i++) {
		    	do {
		    		$codigo = codigo(5,$prefix,$sufix);
		    	} while (isset($codigos[$codigo]) && es_valido($codigo));
		    	
		    	$codigos[$codigo] = $codigo;
		    }
		}
    }
	
	
    foreach ($codigos as $codigo) {
    	if (empty($description)) {
    		$description = $descriciones[$codigo];
    	}
		
		$sql  = "INSERT INTO wp_esp_price";
		$sql .= ' (<code>PRT_ID</code>,<code>PRC_amount</code>,<code>PRC_name</code>, <code>PRC_desc</code>, <code>PRC_wp_user</code>, <code>PRC_overrides</code>, <code>PRC_order</code>) VALUES ';
		$sql .= "($porcentaje, $precio, '$description', '$description', $wp_user, 0, 1);";
		$result = $wpdb->query($sql);
		$price_id = $wpdb->insert_id;
		if(isset($eventos)){
			foreach($eventos as $evento){
			$sql = "SELECT DTT_EVT_start, DTT_EVT_end FROM wp_esp_datetime WHERE EVT_ID = ".$evento;
			$dates = $wpdb->get_results( $wpdb->prepare($sql, ''));
			$endDate = strtotime($dates[0]->DTT_EVT_end);
			
			$sql = "SELECT EVT_visible_on FROM wp_esp_event_meta WHERE EVT_ID = ".$evento;
			$date =  $wpdb->get_results( $wpdb->prepare($sql, ''));
			$startDate = strtotime($date[0]->EVT_visible_on);
			
			$sql  = "INSERT INTO wp_esp_promotion";
			$sql .= '(<code>PRO_code</code>,<code>PRC_ID</code>,<code>PRO_uses</code>, <code>PRO_accept_msg</code>, <code>PRO_decline_msg</code>, <code>PRO_start</code>, <code>PRO_end</code>, <code>PRO_scope</code>) VALUES ';
			$sql .= "('$codigo', $price_id, $limite, 'Aceptado', 'Rechazado', FROM_UNIXTIME($startDate), FROM_UNIXTIME($endDate), 'Event');";
			$wpdb->query($sql);
			$discount_id = $wpdb->insert_id;
			
			$sql = "INSERT INTO wp_esp_promotion_object (<code>PRO_id</code>, <code>OBJ_id</code>, <code>POB_type</code>, <code>POB_used</code>) VALUES ($discount_id, $evento, 'Event', 0);";
			$wpdb->query($sql);
			
			}
		}else{
			echo "<script>alert('Debes seleccionar al menos un evento.')";
		}
		
    }
	
    if ($exportar_desc) {
		exportar_codigos($codigos,$descriciones);
	} else {
    	exportar_codigos($codigos);
    }
    espresso_display_salones_messages( 'Generación de códigos finalizada.' );
}

function exportar_codigos($codes = array(), $desc = array(), $download_dir = "../wp-content/uploads/espresso/codes"){
	if (!file_exists($download_dir)) {
		mkdir($download_dir, 0777, true);
	}
	if(count($desc) > 0) {
		$codes = array();
		foreach ($desc as $c => $d) {
			$codes[$c] = $c."\t".$d;
		}
	} 
	
	file_put_contents($download_dir.'/codes-'.date("Y-m-d-H-i").".txt", implode("\n", $codes));
}

function es_valido($code){
	global $wpdb;
	$sql = "SELECT count(*) ";
	$sql .= " FROM wp_esp_promotion e WHERE e.PRO_code = '".$code."'";
	$codes = $wpdb->get_var( $wpdb->prepare($sql, ''));
	if($codes == 0) {
		return true;
	}
	return false;
}

function espresso_display_salones_messages( $success_messages = '', $error_messages = '' ) {
	if ($success_messages != '') {
		//showMessage( $success_messages );
		echo '<div id="message1" class="updated fade"><p>' . $success_messages . '</p></div>';
	}

	if ($error_messages != '') {
		//showMessage( $error_messages, TRUE );
		echo '<div id="message2" class="error fade fade-away"><p>' . $error_messages . '</p></div>';
	}	
}
add_action( 'admin_menu', 'espresso_salones_add_page' );

function espresso_salones_add_page() {
	$default_role = 'administrator';
	add_submenu_page('tools.php', 'Códigos Masivos', 'Códigos Masivos', $default_role, 'espresso_salones', 'espresso_salones');
}


Tony

  • Support Staff

November 8, 2018 at 7:22 am

Thank you for the code, in future I’d recommend pasting large sections of go to either a Gist, or PasteBin and then adding the URL here, the forum can add formatting to snippets.

Yep, that field is set to 1 automatically by default. Shall we set the field to 0?

Yes, set that field to 0.

Promotion price objects are not ‘default prices’ and thats likely what is causing your problem as default prices are all pulled into the the event editor. It was never expected that a user would have 8,000+ default prices on an event (a default price would usually be asigned to a default ticket, meaning an event with 8,000 default tickets).

Side note, is there any reason your not using our models to create these objects?

https://github.com/eventespresso/event-espresso-core/tree/master/docs/G–Model-System

Had you have used those to add the prices the default field would have automatically been set to 0. I’m going to create a ticket to investigate why that field defaults to 1 but I would still recommend switching the above to use the model system as it handles a lot of what you are doing automatically.


guiapenin

November 8, 2018 at 9:30 am

Hello Tony,

Thanks for all, it was really helpfull.

Yes, set that field to 0.

We have already made the change and it finally works fine. Thanks so much!

Side note, is there any reason your not using our models to create these objects?

We didn’t really noticed that it exists. We will consider update our code for using your model system as u mentioned above to create codes. Thanks for suggestion!!

Best regards


Tony

  • Support Staff

November 8, 2018 at 10:01 am

You’re most welcome, I’m glad that worked for you.

With regards to the models, I’d highly recommend looking into using them, the handle a lot of the background work for you so once you know how to use them its much easier to work with EE than rolling your own.

Viewing 7 reply threads

The support post ‘Is there a maximum limit of association of promotional codes to events?’ is closed to new replies.

Have a question about this support post? Create a new support post in our support forums and include a link to this existing support post so we can help you.

Event Espresso