Mathieu Moulin 3 years ago
parent
commit
05742310cf

+ 10 - 4
src/bootstrap.inc.php

@@ -16,15 +16,21 @@ require_once CLASS_PATH.'/db/mysqli.php';
 require_once CLASS_PATH.'/logger/base.php';
 
 $db = new \db\mysqli(DB_HOST, DB_USER, DB_PASS, DB_BASE);
-//$dbp = new mysqli(DB_USER, DB_PASS, DB_BASE);
-//$dbd = new mysqli(DB_USER, DB_PASS, DB_BASE);
 //echo 'db : '; var_dump($db);
 $db->set_charset('utf8mb4');
 
 $logger = new \logger\base();
 
-define('DEBUG_SQL', true);
-define('DEBUG_SYNCHRO', true);
+define('DEBUG_ALL', true);
+//define('DEBUG_SQL', true);
+//define('DEBUG_SYNCHRO', true);
+//define('DEBUG_WS', true);
+if (!defined('DEBUG_SQL'))
+	define('DEBUG_SQL', DEBUG_ALL);
+if (!defined('DEBUG_SYNCHRO'))
+	define('DEBUG_SYNCHRO', DEBUG_ALL);
+if (!defined('DEBUG_WS'))
+	define('DEBUG_WS', DEBUG_ALL);
 
 ini_set("xdebug.var_display_max_children", '-1');
 ini_set("xdebug.var_display_max_data", '-1');

+ 111 - 0
src/class/controller/model.php

@@ -0,0 +1,111 @@
+<?php
+
+namespace Controller;
+
+require_once 'base.php';
+require_once CLASS_PATH.'/table/p_table.php';
+require_once CLASS_PATH.'/table/d_table.php';
+
+class Model extends Base {
+
+protected $actions = [
+	'index' => [
+		'label'=>'Accueil',
+		'viewmodel'=>'model/index',
+	],
+	'p_table' => [
+		'label'=>'Tables Prestashop associées',
+		'viewmodel'=>'model/table_list',
+	],
+	'p_field' => [
+		'label'=>'Gestion des champs des tables Prestashop',
+		'param'=>['table'],
+		'viewmodel'=>'model/field_list',
+	],
+	'd_table' => [
+		'label'=>'Tables Dolibarr associées',
+		'viewmodel'=>'model/table_list',
+	],
+	'd_field' => [
+		'label'=>'Gestion des champs des tables Dolibarr',
+		'param'=>['table'],
+		'viewmodel'=>'model/field_list',
+	],
+];
+
+protected $viewmodel_name = 'table/index';
+
+/**
+ * Liste des tables
+ */
+public function index_action()
+{
+	static::__log(__METHOD__);
+}
+
+/**
+ * Liste des tables
+ */
+public function p_table_action()
+{
+	static::__log(__METHOD__);
+	$db = static::$__db;
+	
+	$this->data['_prefix'] = $_prefix;
+	
+	$classname = '\\Table\\'.$_prefix.'Table';
+	$this->data['t_list'] = $classname::_list();
+	$this->data['t_fields'] = $classname::_fields();
+}
+
+/**
+ * Liste des tables
+ */
+public function d_table_action()
+{
+	static::__log(__METHOD__);
+	
+	return $this->list_action('p_');
+}
+
+/**
+ * Liste des tables
+ */
+public function p_field_action()
+{
+	static::__log(__METHOD__);
+	
+	return $this->list_action('d_');
+}
+
+/**
+ * Détails d'une table
+ */
+public function d_field_action()
+{
+	static::__log(__METHOD__);
+	
+	$table_name = $_GET['table'];
+	
+	$classname = '\\Table\\'.$_prefix.'Table';
+	$field_classname = '\\Table\\'.$_prefix.'Field';
+	$table = $classname::_get_by_name($table_name);
+	//var_dump($table);
+	
+	// Indéxation champs manquant
+	if (isset($_GET['index'])) {
+		$table->fields_index();
+	}
+	
+	$this->data['_prefix'] = $_prefix;
+	$this->data['table'] = $table;
+	
+	// Obsolète ..? Accessible depuis $table
+	$this->data['t_fields'] = $classname::_fields();
+	$this->data['f_fields'] = $field_classname::_fields();
+	$this->data['c_fields'] = $field_classname::_c_fields();
+}
+
+}
+
+Table::__init();

+ 85 - 37
src/class/controller/synchro.php

@@ -232,11 +232,11 @@ public function create_action()
 	static::__log(__METHOD__);
 	static::__gettopostall();
 	
-	if (empty($_POST['order']))
-		die('order manquant');
-	$order = $_POST['order'];
+	if (empty($_POST['sens']))
+		die('sens manquant');
+	$sens = $_POST['sens'];
 	
-	$type = ($order=='pd') ?'p' :'d';
+	$type = ($sens=='pd') ?'p' :'d';
 	if (empty($_POST['otype']))
 		die('otype manquant');
 	$otype = $_POST['otype'];
@@ -259,34 +259,50 @@ public function create_action()
 	$this->create_exec($type, $otype, $oid, $ref, $data);
 }
 
+/**
+ * Vérifie si un objet est dans une association
+ * rtuorne un tableau avec entre autres :
+ * response : true si oui, false sinon
+ * reason : raison/pourquoi cette réponse
+ * o : objet trouvé
+ */
 public function oexists_exec($type, $otype, $oid, $ref=null)
 {
 	static::__log(__METHOD__);
+	//die('test mathou');
 	
-	// Check Mapping
-	if (!($map = $this->model::_mapbyotype($type, $otype))) {
+	// Check Mapping not exists
+	// ATTENTION! On se connait pas le mapping a priori...
+	// @todo mapping à récupérer SI l'objet est mappé au modèle.
+	if (!($map = $this->model::_mapbyobject($type, $otype, $oid))) {
+		//var_dump($map); die();
 		return ['response'=>false, 'reason'=>'map_none', 'reason_label'=>'Aucun mapping...'];
 	}
 	//var_dump($map); //die();
 	
-	// Check ID
-	if ($o = $this->model::_getbyoid($map['id'], $type, $otype, $oid)) {
-		return ['response'=>false, 'reason'=>'id_already', 'map'=>$map, 'o'=>$o, 'reason_label'=>'Objet déjà Mappé...'];
+	// Check OID not Exists
+	$tableclass = '\\Table\\'.$type.'_Table';
+	$t = $tableclass::_get($otype);
+	//var_dump($t); //die();
+	if (empty($r = $t->get($oid))) {
+		//var_dump($r); die();
+		return ['response'=>false, 'reason'=>'oid_incorrect', 'map'=>$map];
 	}
 	
-	$table = '\\Table\\'.$type.'_Table';
-	$t = $table::_get($otype);
-	//var_dump($t); die();
-	$r = $t->get($oid);
-	//var_dump($r); //die();
+	// Check OID already mapped
+	//var_dump($map['id'].", $type, $otype, $oid");
+	if ($id = $this->model::_getidbyoid($map['id'], $type, $otype, $oid)) {
+		//var_dump($id); die();
+		return ['response'=>false, 'reason'=>'id_already', 'map'=>$map, 't'=>$t, 'r'=>$r, 'id'=>$id, 'reason_label'=>'Objet déjà Mappé...'];
+	}
 	
-	// Check ref
-	$ref = !empty($t->f_ref) ?$r[$t->f_ref] :NULL;
-	if ($ref && ($o = $this->model::_getbyref($ref))) {
-		return ['r'=>false, 'reason'=>'ref_already', 'reason_label'=>'Ref existante...', 'map'=>$map, 'o'=>$o, 't'=>$t, 'r'=>$r];
+	// Check ref already mapped with another OID
+	$ref = !empty($t->f_ref) && !empty($r) ?$r[$t->f_ref] :NULL;
+	if ($ref && ($id = $this->model::_getidbyref($ref))) {
+		return ['r'=>false, 'reason'=>'ref_already', 'map'=>$map, 't'=>$t, 'r'=>$r, 'id'=>$id, 'reason_label'=>'Ref existante...'];
 	}
 	
-	return ['response'=>true, 'o'=>$o, 't'=>$t, 'r'=>$r];
+	return ['response'=>true, 'reason'=>'ok_to_create', 'map'=>$map, 't'=>$t, 'r'=>$r];
 }
 
 /**
@@ -296,29 +312,47 @@ public function create_exec($type, $otype, $oid, $ref=null, $data=null)
 {
 	static::__log(__METHOD__);
 	
+	$orig = $type;
+	$dest = ($type=='p') ?'d' :'p';
 	$sens = ($type=='p') ?'pd' :'dp';
+	
+	$model = $this->model;
 	$table = '\\Table\\'.$type.'_Table';
+	
 	$t = $table::_get($otype);
 	//var_dump($t); die();
-	$r = $t->get($oid);
-	//var_dump($r); //die();
 	
-	$map = $this->model::_mapbyotype($type, $otype);
+	$r = $model::_ws_oexists($type, $otype, $oid);
+	if (empty($r) || empty($r['return'])) {
+		var_dump($r); die('COUILLE oid inexistant sur serveur distant!');
+	}
+	//var_dump($r); die();
+	// Ancienne version local...
+	//if (!($r = $t->get($oid)))
+	//	die('COUILLE oid');
+	//var_dump($r); //die();
 	
+	$map = $model::_mapbyobject($type, $otype, $oid);
+	//var_dump($type); var_dump($otype); var_dump($map); var_dump($r); die();
 	// Check label
-	$label = !empty($t->f_label) ?$r[$t->f_label] :NULL;
+	$label = (!empty($t->f_label) && isset($r[$t->f_label])) ?$r[$t->f_label] :NULL;
 	// @todo : Conflit de ref => envoi email pour validation
 	// @todo : Conflit d'id idem ! faut pas associer 40 fois un objet, sinon ça va faire des synchro de merde...
 	// Lien de confirmation ou de reverse (remet les valeurs d'avant en cas de modif de ref)
 	//var_dump($ref); var_dump($label); //die();
 	
+	if ($ref && ($oid2=$model::_ws_oexists_ref($type, $otype, $ref)))
+		die('COUILLE objet avec ref '.$ref.' existe déjà de l\'autre côté avec oid '.$oid2);
+	
 	// Add object model
-	$id = $this->model::_add($map['id'], $ref, $label);
+	$id = $model::_add($map['id'], $ref, $label);
 	//var_dump($id); 
 	// Link object to table data
-	$this->model::_t_assoc($type, $id, $t->id, $oid);
+	$model::_t_assoc($type, $id, $t->id, $oid);
 	
 	// Sync object
+	$this->sync_exec($sens, $id);
+	// Sync ini object
 	$this->sync_init_exec($sens, $id);
 }
 
@@ -329,7 +363,7 @@ public function create_exec($type, $otype, $oid, $ref=null, $data=null)
  * Ensuite on pourra les synchroniser
  * Ordre d'association : dp = Doli => Presta
  */
-public function assoc_action($order='dp')
+public function assoc_action($sens='dp')
 {
 	static::__log(__METHOD__);
 	static::__gettopostall();
@@ -339,10 +373,10 @@ public function assoc_action($order='dp')
 			if (empty($_POST['s']))
 				echo "Argument manquant : Tableau d'association vide";
 			foreach($_POST['s'] as $r)
-				$this->assoc_exec($order, $r);
+				$this->assoc_exec($sens, $r);
 		}
 		elseif (is_string($_POST['s'])) {
-			$this->assoc_exec($order, $_POST['s']);
+			$this->assoc_exec($sens, $_POST['s']);
 		}
 		else {
             echo "Argument manquant : Tableau/Chaine d'association";
@@ -350,10 +384,10 @@ public function assoc_action($order='dp')
 	}
 	
 	if (!isset($_GET['ajax']))
-		$this->assoc_display($order);
+		$this->assoc_display($sens);
 }
 
-protected function assoc_exec($order='dp', $r)
+protected function assoc_exec($sens='dp', $r)
 {
 	// @todo overload
 }
@@ -362,7 +396,7 @@ protected function assoc_exec($order='dp', $r)
  * Liste des objets associés ou à associer
  * Ordre d'association : dp = Doli => Presta
  */
-protected function assoc_display($order='dp')
+protected function assoc_display($sens='dp')
 {
 	// @todo overload
 }
@@ -472,11 +506,11 @@ public function osync_action()
 	static::__log(__METHOD__);
 	static::__gettopostall();
 	
-	if (empty($_POST['order']))
-		die('order manquant');
-	$order = $_POST['order'];
+	if (empty($_POST['sens']))
+		die('sens manquant');
+	$sens = $_POST['sens'];
 	
-	$type = ($order=='pd') ?'p' :'d';
+	$type = ($sens=='pd') ?'p' :'d';
 	if (empty($_POST['otype']))
 		die('otype manquant');
 	$otype = $_POST['otype'];
@@ -492,11 +526,18 @@ public function osync_action()
 	// Ceci doit pouvoir être forcé.
 	
 	$res = $this->oexists_exec($type, $otype, $oid, $ref);
-	//var_dump($res); die();
+	if (DEBUG_SYNCHRO) {
+		var_dump("$type, $otype, $oid, $ref");
+		var_dump($res);
+		//die();
+	}
+	// Erreur
 	if (!is_array($res) || !array_key_exists('response', $res))
 		die('couille');
+	// Déjà => Update
 	elseif (!$res['response'] && $res['reason']=='id_already')
-		$this->sync_exec($order, $res['o']);
+		$this->sync_exec($sens, $res['id']);
+	// Pas => Create
 	else
 		$this->create_exec($type, $otype, $oid, $ref, $data);
 }
@@ -520,4 +561,11 @@ public function model_add($map_id, $ref=null, $label=null)
 	return $this->model::_add($map_id, $ref, $label);
 }
 
+/**
+ * Mapping
+ */
+public function map_action()
+{
+}
+
 }

+ 362 - 101
src/class/model/base.php

@@ -49,6 +49,9 @@ protected static $_maps = [];
 protected static $_map_val = [];
 protected static $_map_fct = [];
 
+protected static $_p_map_pk = [];
+protected static $_d_map_pk = [];
+
 protected static function __init_params()
 {
 	if (empty(static::$_name))
@@ -72,6 +75,8 @@ protected static function __init_params()
 	$sql = 'SELECT *
 		FROM `_map`
 		WHERE `model_id`='.static::$_id;
+	if (DEBUG_SQL)
+		var_dump($sql);
 	$q = $db->query($sql);
 	$maps_ids = [];
 	static::$_maps = [];
@@ -82,12 +87,15 @@ protected static function __init_params()
 		);
 		$maps_ids[] = $row['id'];
 	}
+	//var_dump(static::$_maps);
 	
 	// Tables PRESTA
 	
 	$sql = 'SELECT *
 		FROM `_map_p_tables`
 		WHERE `map_id` IN ('.implode(', ', $maps_ids).')';
+	if (DEBUG_SQL)
+		var_dump($sql);
 	$q = $db->query($sql);
 	//var_dump($q); die();
 	while($row=$q->fetch_assoc()) {
@@ -109,6 +117,8 @@ protected static function __init_params()
 	$sql = 'SELECT *
 		FROM `_map_d_tables`
 		WHERE `map_id` IN ('.implode(', ', $maps_ids).')';
+	if (DEBUG_SQL)
+		var_dump($sql);
 	$q = $db->query($sql);
 	//var_dump($q); die();
 	while($row=$q->fetch_assoc()) {
@@ -242,12 +252,18 @@ public static function _maps()
 	return static::$_maps;
 }
 
+public static function _mapbyobject($type, $otype, $oid=null)
+{
+	return static::_mapbyotype($type, $otype);
+}
 public static function _mapbyotype($type, $otype)
 {
+	//var_dump(static::$_maps); die();
 	foreach(static::$_maps as $map_id=>$map) {
 		//var_dump($map);
-		if ($map[$type.'t_main']==$otype)
+		if ($map[$type.'t_main']==$otype) {
 			return $map;
+		}
 	}
 }
 
@@ -278,51 +294,55 @@ public static function _schema_check($update=false)
 		foreach(static::${'_'.$type.'t'} as $tablename=>$table) {
 			$classname = 'Table\\'.$type.'_field';
 			$schema_web = static::_ws_action($type, 'schema_fields', ['tablename'=>$tablename]);
-			$schema = $classname::_c_data_get($tablename);
-			$diff = static::_data_diff_rows($schema, $schema_web);
-			//echo '<p>'.$tablename.'</p>'; var_dump($diff); var_dump($schema_web);
-			
-			if (!empty($diff)) {
-				$tdiff[] = 'Champs sur '.$type.'.'.$tablename;
-				//var_dump($diff);
-				foreach($diff as $fieldname=>$field) {
-					if (!empty($field)) {
-						//var_dump($field);
-						if ($update) {
-							// Insert
-							if (empty($field[0]))
-								$classname::_c_insert($tablename, $field[1]);
-							// Delete
-							elseif (empty($field[1]))
-								$classname::_c_delete($tablename, $field[0]);
-							// Update
-							else
-								$classname::_c_update($tablename, $field[1]);
+			if (!is_null($schema_web)) {
+				$schema = $classname::_c_data_get($tablename);
+				$diff = static::_data_diff_rows($schema, $schema_web);
+				//echo '<p>'.$tablename.'</p>'; var_dump($diff); var_dump($schema_web);
+				
+				if (!empty($diff)) {
+					$tdiff[] = 'Champs sur '.$type.'.'.$tablename;
+					//var_dump($diff);
+					foreach($diff as $fieldname=>$field) {
+						if (!empty($field)) {
+							//var_dump($field);
+							if ($update) {
+								// Insert
+								if (empty($field[0]))
+									$classname::_c_insert($tablename, $field[1]);
+								// Delete
+								elseif (empty($field[1]))
+									$classname::_c_delete($tablename, $field[0]);
+								// Update
+								else
+									$classname::_c_update($tablename, $field[1]);
+							}
 						}
 					}
 				}
 			}
 			
 			$index_web = static::_ws_action($type, 'schema_index', ['tablename'=>$tablename]);
-			$index = $classname::_i_data_get($tablename);
-			$diff = static::_data_diff_rows($index, $index_web);
-			//echo '<p>'.$tablename.'</p>'; var_dump($diff); //var_dump($index_web);
-			if (!empty($diff)) {
-				$tdiff[] = 'Index sur '.$type.'.'.$tablename;
-				//var_dump($diff);
-				foreach($diff as $fieldname=>$field) {
-					if (!empty($field)) {
-						//var_dump($field);
-						if ($update) {
-							// Insert
-							if (empty($field[0]))
-								$classname::_i_insert($tablename, $field[1]);
-							// Delete
-							elseif (empty($field[1]))
-								$classname::_i_delete($tablename, $field[0]);
-							// Update
-							else
-								$classname::_i_update($tablename, $field[1]);
+			if (!is_null($index_web)) {
+				$index = $classname::_i_data_get($tablename);
+				$diff = static::_data_diff_rows($index, $index_web);
+				//echo '<p>'.$tablename.'</p>'; var_dump($diff); //var_dump($index_web);
+				if (!empty($diff)) {
+					$tdiff[] = 'Index sur '.$type.'.'.$tablename;
+					//var_dump($diff);
+					foreach($diff as $fieldname=>$field) {
+						if (!empty($field)) {
+							//var_dump($field);
+							if ($update) {
+								// Insert
+								if (empty($field[0]))
+									$classname::_i_insert($tablename, $field[1]);
+								// Delete
+								elseif (empty($field[1]))
+									$classname::_i_delete($tablename, $field[0]);
+								// Update
+								else
+									$classname::_i_update($tablename, $field[1]);
+							}
 						}
 					}
 				}
@@ -484,6 +504,8 @@ public static function _d_list($params=null)
 	$db = static::$__db;
 	
 	$sql = static::_d_list_sql($params);
+	if (DEBUG_SQL)
+		var_dump($sql);
 		
 	$l = [];
 	$q = $db->query($sql);
@@ -574,25 +596,60 @@ public static function _getbyref($ref)
 	
 	return $o;
 }
-public static function _getbyoid($map_id, $type, $otype, $oid)
+public static function _getidbyref($ref)
 {
 	static::__log(__METHOD__);
 	$db = static::$__db;
 	
-	$sql = 'SELECT ot.id
-		FROM _objects_'.$type.' ot
-		INNER JOIN _objects o ON o.id=ot.id
+	$sql = 'SELECT o.id
+		FROM _objects o
+		WHERE o.ref="'.$ref.'"';
+	if (DEBUG_SQL)
+		var_dump($sql);
+	if (!($q = $db->query($sql))) {
+		var_dump('COUILLE OID');
+		return;
+	}
+	
+	if (list($id)=$q->fetch_row())
+		return $id;
+}
+public static function _getidbyoid($map_id, $type, $otype, $oid)
+{
+	static::__log(__METHOD__);
+	$db = static::$__db;
+	
+	$sql = 'SELECT o.id
+		FROM _objects o
+		INNER JOIN _objects_'.$type.' ot ON ot.id=o.id
 		INNER JOIN _'.$type.'_tables t ON t.id=ot.tid
-		WHERE o.map_id='.$map_id.'
-			AND ot.oid='.$oid.'
+		WHERE ot.oid='.$oid.'
 			AND t.ref="'.$otype.'"';
+		// @todo verif que map_id est bien inutile dans tous les cas de figure!
+		// AND o.map_id='.$map_id.'
 	if (DEBUG_SQL)
 		var_dump($sql);
-	$q = $db->query($sql);
+	if (!($q = $db->query($sql))) {
+		var_dump('COUILLE OID');
+		return;
+	}
 	
 	if (list($id)=$q->fetch_row())
 		return $id;
 }
+public static function _existsbyoid($map_id, $type, $otype, $oid)
+{
+	return is_numeric(static::_getidbyoid($map_id, $type, $otype, $oid));
+}
+public static function _getbyoid($map_id, $type, $otype, $oid)
+{
+	$id = static::_getidbyoid($map_id, $type, $otype, $oid);
+	if (DEBUG_SQL)
+		var_dump($id);
+	if ($id)
+		return static::_get($id);
+	//var_dump($o); die();
+}
 
 /**
  * Récupère Un objet
@@ -657,6 +714,7 @@ public static function _get_all_d(&$o)
 	
 	$o[$type.'_tree'] = static::_get_data_tree($map_id, $type, $t_main, $oid);
 	$o[$type.'_tree_web'] = static::_ws_model($type, $map_id, $oid);
+	//var_dump($o[$type.'_tree_web']); die();
 }
 /**
  * ATTENTION! : params doit être construit en amont
@@ -702,7 +760,7 @@ public static function _get_data_tree_sub($map, $type, $data, $row)
 {
 	$data['row'] = $row;
 	// récursion enfants
-	if (!empty($map['children'])) foreach($map['children'] as $tname=>$t) {
+	if (!is_null($row) && !empty($map['children'])) foreach($map['children'] as $tname=>$t) {
 		//$table = static::${'_'.$type.'t'}[$tname];
 		//echo '<p>'.$tname.'</p>'; var_dump($t);// die();
 		$params = [
@@ -745,9 +803,19 @@ public static function _ws_model($type, $map_id, $id)
 	//var_dump(static::$_maps[$map_id]);
 	return static::_ws_action($type, 'get', ['id'=>$id, 'map'=>static::$_maps[$map_id]]);
 }
-public static function _ws_sql($type, $sql)
+public static function _ws_oexists($type, $tablename, $oid)
 {
-	return static::_ws_action($type, 'sql', ['sql'=>$sql]);
+	//var_dump(static::$_maps[$map_id]);
+	return static::_ws_action($type, 'exists', ['tablename'=>$tablename, 'id'=>$oid]);
+}
+public static function _ws_oexists_ref($type, $tablename, $ref)
+{
+	//var_dump(static::$_maps[$map_id]);
+	return static::_ws_action($type, 'exists_ref', ['tablename'=>$tablename, 'ref'=>$ref]);
+}
+public static function _ws_sql($type, $sql_type, $sql)
+{
+	return static::_ws_action($type, 'sql', ['type'=>$sql_type, 'sql'=>$sql]);
 }
 /**
  * Webservice action
@@ -762,6 +830,9 @@ public static function _ws_action($type, $action, $params=null)
 public static function _ws_url($type, $url, $post=null)
 {
 	$url = static::${'__'.$type.'_params'}['ws_url'].$url;
+	if (DEBUG_SYNCHRO || DEBUG_WS) {
+		var_dump($url);
+	}
 	
 	$timeout = 30;
 	$ch = curl_init($url); // initialize curl with given url
@@ -775,9 +846,8 @@ public static function _ws_url($type, $url, $post=null)
 		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
 	}
 	$raw_data = @curl_exec($ch);
-	//var_dump($raw_data);
 	$data = json_decode($raw_data, true);
-	//echo $url; var_dump($data);
+	//var_dump($url); var_dump($post); var_dump($raw_data); var_dump($data);
 	return $data;
 }
 
@@ -786,42 +856,65 @@ public static function _ws_url($type, $url, $post=null)
 
 /**
  * Requête SQL depuis Tree sur un set de données avec un mapping donné
- * Fonctionne bien pour une synchronisation, moins bien pour un mapping, mais on va s'arranger!
+ * @todo Fonctionne bien pour une synchronisation, moins bien pour un mapping, mais on va s'arranger!
+ * 
+ * @param $map Mapping concerné
+ * @param $type p/d
+ * @param $tree Data locale
+ * @param $tree_web Data prod distante
+ * @param $tree_new Data nouvelle (à mettre à jour vers distant)
  */
 public static function _sql_update($map, $type, $tree, $tree_web, $tree_new=null)
 {
 	$db = static::$__db;
+	//trigger_error('mm');
 	
+	// On synchronise le distant par màj
 	if (isset($tree_new)) {
 		$tree_orig = $tree_new;
 		$tree_dest = $tree_web;
 		$dest = 'ws';
 	}
+	// On synchronise le local avec le distant
 	else {
 		$tree_orig = $tree_web;
 		$tree_dest = $tree;
 		$dest = 'local';
 	}
 	
-	//var_dump($map); die();
 	$tablename = $map['name'];
-	if (DEBUG_SYNCHRO) {
+	if (DEBUG_SYNCHRO || DEBUG_SQL) {
 		echo '<p>_sql_update : '.$tablename.'</p>';
+		var_dump($map);
+		var_dump($tree_orig);
+		var_dump($tree_dest);
+		var_dump($dest);
+		//die();
 	}
 	$table = static::${"_".$type."t"}[$tablename];
 	
 	if (empty($tree_dest['row'])) {
 		// Création depuis distant
 		if (!empty($tree_orig['row'])) {
-			$sql = $table->data_insert_sql($tree_orig['row']);
+			$sql = $table->data_insert_sql($tree_orig['row'], $tree_orig['params']);
+			if (DEBUG_SQL)
+				var_dump($sql);
 			if ($dest=='local') {
 				$q = $db->query($sql);
-				var_dump($q);
-				$r = ['response'=>true, 'id'=>$db->insert_id];
+				//var_dump($q);
+				$id = $db->insert_id;
+				$sql_notif = 'INSERT INTO _'.$type.'_log (ts, tid, oid, rev, action, fields, details) VALUES (NOW(), '.$map['tid'].', '.$id.', 0, "c", "'.addslashes(json_encode(array_keys($tree_orig['row']))).'", "'.addslashes(json_encode($tree_orig['row'])).'")';
+				if (DEBUG_SQL)
+					var_dump($sql_notif);
+				$q = $db->query($sql_notif);
+				$r = ['response'=>!empty($id), 'id'=>$id];
+				if (DEBUG_SYNCHRO || DEBUG_SQL)
+					var_dump($r);
 			}
 			elseif ($dest=='ws') {
-				$r = static::_ws_sql($type, $sql);
-				var_dump($r);
+				$r = static::_ws_sql($type, 'c', $sql);
+				if (DEBUG_SYNCHRO || DEBUG_SQL)
+					var_dump($r);
 			}
 		}
 	}
@@ -830,12 +923,23 @@ public static function _sql_update($map, $type, $tree, $tree_web, $tree_new=null
 		// Suppression du local
 		if (!empty($tree_dest['row'])) {
 			$sql = $table->data_delete_sql($tree_dest['params']);
+			if (DEBUG_SQL)
+				var_dump($sql);
 			if ($dest=='local') {
 				$q = $db->query($sql);
-				$r = ['response'=>true];
+				$affected_rows = $db->affected_rows;
+				$sql_notif = 'INSERT INTO _'.$type.'_log (ts, tid, oid, rev, action) VALUES (NOW(), '.$map['tid'].', '.$tree_dest['params'].', 0, "d")';
+				if (DEBUG_SQL)
+					var_dump($sql_notif);
+				$q = $db->query($sql_notif);
+				$r = ['response'=>$affected_rows>0];
+				if (DEBUG_SYNCHRO || DEBUG_SQL)
+					var_dump($r);
 			}
 			elseif ($dest=='ws') {
-				$r = static::_ws_sql($type, $sql);
+				$r = static::_ws_sql($type, 'd', $sql);
+				if (DEBUG_SYNCHRO || DEBUG_SQL)
+					var_dump($r);
 			}
 		}
 	}
@@ -845,34 +949,65 @@ public static function _sql_update($map, $type, $tree, $tree_web, $tree_new=null
 		//var_dump($diff);
 		if (!empty($diff)) {
 			$sql = $table->data_update_sql($diff, $tree_orig['params']);
+			if (DEBUG_SQL)
+				var_dump($sql);
 			if ($dest=='local') {
 				$q = $db->query($sql);
-				$r = ['response'=>true];
+				$affected_rows = $db->affected_rows;
+				if (is_numeric($tree_orig['params'])) {
+					$sql_notif = 'INSERT INTO _'.$type.'_log (ts, tid, oid, rev, action, fields, details) VALUES (NOW(), '.$map['tid'].', '.$tree_orig['params'].', 0, "u", "'.addslashes(json_encode(array_keys($diff))).'", "'.addslashes(json_encode($diff)).'")';
+					$q = $db->query($sql_notif);
+					if (DEBUG_SQL)
+						var_dump($sql_notif);
+				}
+				$r = ['response'=>$affected_rows>0];
 			}
 			elseif ($dest=='ws') {
-				$r = static::_ws_sql($type, $sql);
+				$r = static::_ws_sql($type, 'u', $sql);
+				if (DEBUG_SYNCHRO || DEBUG_SQL)
+					var_dump($r);
 			}
 		}
 	}
 	
-	// BIM
-	if (!empty($sql)) {
-		if (DEBUG_SQL)
-			var_dump($sql);
-	}
-	
 	// On va potentiellement utiliser par la suite des id sur les objets nouvellement créés !
 	
 	//var_dump($map['children']); die();
 	if (isset($map['children'])) foreach($map['children'] as $tablename=>$tmap) {
-		//echo '<p>'.$tablename.'</p>'; //var_dump($tree['children'][$tablename]); die();
-		static::_sql_update(
-			$tmap,
-			$type,
-			isset($tree['children'][$tablename]) ?$tree['children'][$tablename] :null,
-			isset($tree_web['children'][$tablename]) ?$tree_web['children'][$tablename] :null,
-			isset($tree_new['children'][$tablename]) ?$tree_new['children'][$tablename] :null
-		);
+		if (DEBUG_SYNCHRO) {
+			echo '<p>'.$tablename.'</p>';
+			//var_dump($tree['children'][$tablename]);
+			var_dump($tmap);
+			//die();
+		}
+		// Row simple
+		if ($tmap['join_type']=='row') {
+			static::_sql_update(
+				$tmap,
+				$type,
+				isset($tree['children'][$tablename]) ?$tree['children'][$tablename] :null,
+				isset($tree_web['children'][$tablename]) ?$tree_web['children'][$tablename] :null,
+				isset($tree_new['children'][$tablename]) ?$tree_new['children'][$tablename] :null
+			);
+		}
+		// Liste
+		else {//if ($tmap['join_type']=='list') {
+			// @todo key mapping des listes... chaud patate!
+			//foreach($row as $key=>$row)
+			if (empty($tree_new)) {
+				if (!empty($tree_web['children'][$tablename])) {
+					foreach($tree_web['children'][$tablename] as $key=>$row) {
+						static::_sql_update(
+							$tmap,
+							$type,
+							isset($tree['children'][$tablename][$key]) ?$tree['children'][$tablename][$key] :null,
+							$row,
+							null
+						);
+					}
+				}
+			}
+		}
 	}
 	
 	return isset($r) ?$r :null;
@@ -967,7 +1102,9 @@ public static function _pd_update(&$o, &$update) //, $diff
 	$type = 'd';
 	
 	$r = static::_sql_update($map[$type.'t'][$map[$type.'t_main']], $type, $o[$type.'_tree'], $o[$type.'_tree_web'], $update['tree']);
-	var_dump($r);
+	if (DEBUG_SQL || DEBUG_SYNCHRO) {
+		var_dump($r);
+	}
 	
 	return $r;
 }
@@ -983,12 +1120,14 @@ public static function _dp_update(&$o, &$update) //, $diff
 	$type = 'p';
 	
 	$r = static::_sql_update($map[$type.'t'][$map[$type.'t_main']], $type, $o[$type.'_tree'], $o[$type.'_tree_web'], $update['tree']);
-	var_dump($r);
+	if (DEBUG_SYNCHRO || DEBUG_SQL)
+		var_dump($r);
 	
 	return $r;
 	
 	$sqls = static::_diff_sql($o['map_id'], 'p', $diff);
-	var_dump($sqls);
+	if (DEBUG_SYNCHRO || DEBUG_SQL)
+		var_dump($sqls);
 	return $sqls;
 }
 
@@ -1030,7 +1169,8 @@ public static function _sync($sens, $id)
 	if (!empty($r['id']))
 		static::_t_assoc($dest, $id, $update['tid'], $r['id']);
 	
-	var_dump($r);
+	if (DEBUG_SYNCHRO || DEBUG_SQL)
+		var_dump($r);
 	
 	// Synchronisation destination après miseà jour
 	$fct = '_'.$dest.'_update';
@@ -1073,6 +1213,21 @@ public static function _map_val_set($type)
 	];
 }
 
+public static function _map_fk($type, $modelname, $map_id, $tablename, $oid)
+{
+	$orig = $type;
+	$dest = $orig=='p' ?'d' :'p';
+	require_once MODEL_PATH.'/'.$modelname.'.php';
+	$classname = '\\Model\\'.$modelname;
+	$o = $classname::_getbyoid($map_id, $orig, $tablename, $oid);
+	if (DEBUG_SYNCHRO) {
+		var_dump("$classname::_getbyoid($map_id, '$orig', $tablename, $oid)");
+		var_dump($o);
+	}
+	if (!empty($o[$dest]['oid']))
+		return $o[$dest]['oid'];
+}
+
 // @todo mettre ailleurs, c'est un helper bien plus général
 public static function _array_merge_recursive(&$map, $tmap)
 {
@@ -1138,6 +1293,12 @@ protected static $_tmap = [
 				'product_lang' => [
 					'name' => 'product_lang',
 				],
+				// Association fournisseur/produit avec prix fournisseur
+				'product_supplier' => [
+					'name' => 'product_supplier',
+					'map_main' => 'product_fournisseur_price',
+					'map_type' => 'list', // mapping list=>list
+				],
 			],
 		],
 	],
@@ -1163,6 +1324,13 @@ protected static $_tmap = [
 			// Quelles infos à utiliser ?
 			'map_main' => 'supplier', // main/main en fait
 			'map_join' => ['supplier_lang', 'supplier_shop'],
+			'children' => [
+				// Adresse client
+				'socpeople' => [
+					'name' => 'socpeople',
+					'map_main' => 'address',
+				],
+			],
 		],
 		'pt' => [
 			'name' => 'supplier',
@@ -1179,6 +1347,12 @@ protected static $_tmap = [
 				'supplier_lang' => [
 					'name' => 'supplier_lang',
 				],
+				// Adresses
+				'address' => [
+					'name' => 'address',
+					'map_type' => 'list', // mapping list=>list
+					'map_main' => 'socpeople',
+				],
 			],
 		],
 	],
@@ -1205,11 +1379,42 @@ protected static $_tmap = [
 				// Adresse client
 				'address' => [
 					'name' => 'address',
+					'map_type' => 'list', // mapping list=>list
 					'map_main' => 'socpeople',
 				],
 			],
 		],
 	],
+	8 => [ // Commande / Order
+		'dt' => [
+			'name' => 'commande',
+			// Quelles infos à utiliser ?
+			'map_main' => 'orders', // main/main en fait
+			'children' => [
+				// Adresse client
+				'commandedet' => [
+					'name' => 'commandedet',
+					'map_type' => 'list', // mapping list=>list
+					'map_main' => 'order_detail',
+				],
+			],
+		],
+		'pt' => [
+			'name' => 'orders',
+			// Quelles infos à utiliser ?
+			'map_main' => 'commande', // main/main en fait
+			//'map_join' => ['supplier_lang', 'supplier_shop'],
+			// Construction des champs enfant
+			'children' => [
+				// Adresse client
+				'order_detail' => [
+					'name' => 'order_detail',
+					'map_type' => 'list', // mapping list=>list
+					'map_main' => 'commandedet',
+				],
+			],
+		],
+	],
 ];
 
 /**
@@ -1322,7 +1527,7 @@ public static function _map_data_tree($sens, $map_dest, $tree_dest, $tree_orig,
 	
 	$tablename = $map_dest['name'];
 	
-	//var_dump($tree_orig); die();
+	//var_dump($tablename); var_dump($tree_orig); die();
 	
 	// Construction/Récupération données de base
 	$datainit = [
@@ -1332,6 +1537,12 @@ public static function _map_data_tree($sens, $map_dest, $tree_dest, $tree_orig,
 		'children' => [],
 	];
 	
+	if (DEBUG_SYNCHRO) {
+		echo '<p>Données sources (data_from) '.$tablename.' :</p>';
+		var_dump($map_dest);
+		//die();
+	}
+	
 	// Une ligne de donnée
 	if ($map_dest['join_type']=='row') {
 		// construction/augmentation $data_from
@@ -1344,7 +1555,10 @@ public static function _map_data_tree($sens, $map_dest, $tree_dest, $tree_orig,
 				$data_from[$tablename_new] = $tree_orig['children'][$tablename_new]['row'];
 		}
 		if (DEBUG_SYNCHRO) {
-			echo '<p>Données sources (data_from) '.$tablename.' :</p>'; var_dump($data_from); var_dump($tree_orig); //die();
+			echo '<p>ROW:Données sources (data_from) '.$tablename.' :</p>';
+			var_dump($data_from);
+			var_dump($tree_orig);
+			//die();
 		}
 		
 		//echo '<p>'.$tablename.'</p>';
@@ -1360,13 +1574,26 @@ public static function _map_data_tree($sens, $map_dest, $tree_dest, $tree_orig,
 		// construction/augmentation $data_from
 		foreach($tree_orig as $key=>$tree_data) {
 			$data_from_sub = array_merge($data_from, [$map_dest['map_main'] => $tree_data['row']]);
+			// Sous-tables de la table de liaison
+			// @todo
 			if (false && !empty($map_dest['map_join'])) foreach($map_dest['map_join'] as $tablename_new) {
 				if (isset($tree_orig['children'][$tablename_new]))
 					$data_from_sub[$tablename_new] = $tree_orig['children'][$tablename_new]['row'];
 			}
+			
 			$row = static::_map_table_row($sens, $tablename, $map_dest, $tree_dest, $data_from_sub);
+			if (DEBUG_SYNCHRO) {
+				echo '<p>LIST:Données sources (data_from) '.$tablename.' :</p>';
+				var_dump($key);
+				var_dump($data_from);
+				var_dump($data_from_sub);
+				var_dump($tree_data);
+				var_dump($row);
+				//die();
+			}
+			//$row = [];
 			
-			//@todo : map key
+			//@todo : map key selon row ? chaud patate...
 			$key_mapped = $key;
 			//$rows = static::${'_'.$type.'t'}[$tablename]->select($params);
 			$datas[$key_mapped] = static::_map_data_tree_sub($sens, $map_dest, $tree_dest, $tree_data, $data_from_sub, $datainit, $row);
@@ -1377,6 +1604,14 @@ public static function _map_data_tree($sens, $map_dest, $tree_dest, $tree_orig,
 /**
  * Sous-requête
  * Juste histoire de factoriser et simplifier le code
+ * 
+ * @param $sens
+ * @param $map_dest mapping de l'objet à construire
+ * @param $tree_dest arbre de donnée final/destination à titre de repère/comparaison
+ * @param $tree_orig arbre de donnée source/origine
+ * @param $data_from tableau de données source/origine
+ * @param $data donnée qu'on va modifier/construire et renvoyer
+ * @param $row ligne de donnée de l'objet en cours
  */
 public static function _map_data_tree_sub($sens, $map_dest, $tree_dest, $tree_orig, $data_from, &$data, $row)
 {
@@ -1385,19 +1620,20 @@ public static function _map_data_tree_sub($sens, $map_dest, $tree_dest, $tree_or
 	
 	$data['row'] = $row;
 	// récursion enfants
-	if (!empty($map_dest['children'])) foreach($map_dest['children'] as $tablename=>$map_dest_child) {
-		if (DEBUG_SYNCHRO) {
-			var_dump($map_dest); echo '<p>'.$tablename.'</p>'; var_dump($map_dest_child); //die();
-		}
+	if (!is_null($row) && !empty($map_dest['children'])) foreach($map_dest['children'] as $tablename=>$map_dest_child) {
 		$vname = $map_dest_child['join']['from_fieldname'];
-		//var_dump($map_dest_child['join']['fieldname']); var_dump($vname); die();
 		
-		//echo '<p>tree dest '.$tablename.'</p>'; var_dump($tree_dest['children'][$tablename]); //die();
 		$tree_dest_child = isset($tree_dest['children'][$tablename]) ?$tree_dest['children'][$tablename] :[];
-		//var_dump($tree_dest_child); die();
 		
 		if (DEBUG_SYNCHRO) {
-			var_dump($tree_dest);
+			var_dump($map_dest);
+			echo '<p>'.$tablename.'</p>';
+			var_dump($map_dest_child);
+			var_dump($map_dest_child['join']['fieldname']);
+			var_dump($vname);
+			echo '<p>tree dest '.$tablename.'</p>';
+			var_dump($tree_dest_child);
+			//die();
 		}
 		// Passage/Mapping de paramètre pour la mise à jour
 		// Identique à l'objet existant
@@ -1431,7 +1667,10 @@ public static function _map_data_tree_sub($sens, $map_dest, $tree_dest, $tree_or
 			$tree_orig_child = $tree_orig;
 		}
 		else {//if ($map_dest_child['join_type']=='list') {
-			//var_dump($tree_orig['children'][$map_dest_child['map_main']]); var_dump($map_dest_child['map_main']); die();
+			if (DEBUG_SYNCHRO) {
+				var_dump(isset($map_dest_child['map_main']));
+				//die();
+			}
 			if (!isset($map_dest_child['map_main']))
 				continue;
 			//var_dump($tree_orig['children']);
@@ -1452,15 +1691,28 @@ public static function _map_data_tree_sub($sens, $map_dest, $tree_dest, $tree_or
  * - valeur par défaut
  * - récupération/modification d'une valeur
  * - récupération/mappage d'une clé à partir de la table de mappage de clés
+ *
+ * @param $sens
+ * @param $tablename
+ * @param $map_dest Mapping que l'on construit
+ * @param $tree_dest Arbre de donnée actuel sur lequel on peut se baser/comparer
+ * @param $data_from Données source permettant de construre la donnée à retourner
  */
 public static function _map_table_row($sens, $tablename, $map_dest, $tree_dest, $data_from)
 {
 	$type = $dest = ($sens=='pd') ?'d' :'p';
 	$orig = ($sens=='pd') ?'p' :'d';
 	$table = static::${'_'.$dest.'t'}[$tablename];
-	//var_dump($tree_dest); die();
-	//var_dump($map_dest); die();
+	//var_dump($tree_dest); var_dump($map_dest); die();
 	$u = [];
+	if (DEBUG_SYNCHRO) {
+		echo '<p>map table row :</p>';
+		var_dump($tablename);
+		var_dump($map_dest);
+		var_dump($tree_dest);
+		var_dump($data_from);
+		//var_dump($table);
+	}
 	//var_dump($p_diff); die();
 	//var_dump($p_data[$tablename]);
 	//var_dump($d_data); die();
@@ -1468,11 +1720,15 @@ public static function _map_table_row($sens, $tablename, $map_dest, $tree_dest,
 	// Bouclage sur les champs présent dans la tables du modèle
 	foreach($table->map_fields($map_dest['map_id']) as $fieldname=>$field) {
 		
-		//var_dump($field); die();
+		if (DEBUG_SYNCHRO) {
+			echo '<p>map_fieldname ('.$tablename.'.'.$fieldname.')</p>';
+			var_dump($field);
+			//die();
+		}
 		// Si mapping update
 		if (!empty($field['update_fct'])) {
 			if (DEBUG_SYNCHRO) {
-				echo '<p>map_fieldname ('.$tablename.'.'.$fieldname.') : '.$field['update_fct'].'</p>';
+				echo '<p>field:update_fct : '.$field['update_fct'].'</p>';
 				//var_dump($fieldname);
 			}
 			
@@ -1494,7 +1750,7 @@ public static function _map_table_row($sens, $tablename, $map_dest, $tree_dest,
 				}
 			}
 			// Fonctions paramétrées
-			if ($map_tablename=='fct') {
+			elseif ($map_tablename=='fct') {
 				if (isset(static::$_map_fct[$dest][$map_fieldname])) {
 					$fct = '_'.$dest.'_map_'.$map_fieldname;
 					//$u[1][$fieldname] = static::$fct($data_from);
@@ -1506,6 +1762,11 @@ public static function _map_table_row($sens, $tablename, $map_dest, $tree_dest,
 			// et utiliser le mapping associé, qui n'est pas collé à la définition du champ
 			elseif($map_tablename=='fk') {
 				// Foreign key
+				if (isset(static::$_map_fk[$map_fieldname])) {
+					$fct = '_'.$dest.'_map_fk';
+					//$u[1][$fieldname] = static::$fct($data_from);
+					$u[$fieldname] = static::$fct($map_fieldname, $data_from, $tree_dest);
+				}
 				
 			}
 			elseif(isset(static::${'_'.$orig.'t_alias'}[$map_tablename])) {
@@ -1555,7 +1816,7 @@ public static function _map_table_row($sens, $tablename, $map_dest, $tree_dest,
 	if (false && empty($d_data)) {
 		// Gestion dépendance des données si on créé toute la chaine...
 		// Par ex, pour un produit décliné, on devrai créer dans l'ordre et utiliser par la suite :
-		// - iproduct => id_product
+		// - product => id_product
 		// - product_shop <= id_product
 		// - product_lang <= id_product
 		// - product_attribute <= id_product => id_product_attribute
@@ -1569,7 +1830,7 @@ public static function _map_table_row($sens, $tablename, $map_dest, $tree_dest,
 			$u['keys'][$fieldname] = $a_data[$tablename][$fieldname];
 		}
 	}
-	
+		
 	return $u;
 }
 

+ 1 - 1
src/class/orm/base.php

@@ -10,7 +10,7 @@ class Base
 protected static $__db;
 protected static $__logger;
 
-public function __init()
+public static function __init()
 {
 	if (!isset(static::$__logger))
 		static::__setlogger($GLOBALS['logger']);

+ 3 - 0
src/class/table/d_field.php

@@ -14,9 +14,12 @@ protected static $_prefix = 'd_';
 protected static $_db_prefix = 'llx_';
 
 protected static $_cache = [];
+protected static $_table_cache = [];
 protected static $_c_cache = [];
 protected static $_i_cache = [];
 protected static $_map_cache = [];
+protected static $_ref_cache = [];
+protected static $_alias_cache = [];
 
 }
 

+ 3 - 0
src/class/table/d_table.php

@@ -9,6 +9,9 @@ class D_Table extends Table
 {
 
 protected static $_cache = [];
+protected static $_row_cache = [];
+protected static $_ref_cache = [];
+protected static $_alias_cache = [];
 
 /* ORM\Base */
 protected static $_db_table = '_d_tables';

+ 97 - 32
src/class/table/field.php

@@ -10,9 +10,12 @@ class Field extends \ORM\Base {
 protected static $_prefix;
 protected static $_db_prefix;
 protected static $_cache = [];
+protected static $_table_cache = [];
 protected static $_c_cache = [];
 protected static $_i_cache = [];
 protected static $_map_cache = [];
+protected static $_ref_cache = [];
+protected static $_alias_cache = [];
 
 /*
  * Champs d'une table
@@ -143,6 +146,51 @@ protected static $_c_fields = [
 	],
 ];
 
+public static function __init()
+{
+	parent::__init();
+	
+	static::_cache_all();
+}
+
+public static function _cache_all($force=false)
+{
+	if (!empty(static::$_ref_cache) && !$force)
+		return;
+	
+	// Rows
+	$sql = 'SELECT *
+		FROM _'.static::$_prefix.'fields';
+	if (DEBUG_SQL)
+		var_dump($sql);
+	$q = static::$__db->query($sql);
+	//var_dump($q); die();
+	while($row = $q->fetch_assoc()) {
+		$o = new static($row['id'], $row);
+		static::$_cache[$row['id']] = $o;
+		static::$_table_cache[$row['table_id']][$row['name']] = $o;
+	}
+	
+	// Ref/alias, etc.
+	$sql = 'SELECT f.id, t.ref, t.alias, f.name
+		FROM _'.static::$_prefix.'fields f
+		INNER JOIN _'.static::$_prefix.'tables t ON t.id=f.table_id';
+	if (DEBUG_SQL)
+		var_dump($sql);
+	$q = static::$__db->query($sql);
+	//var_dump($q); die();
+	while($row = $q->fetch_assoc()) {
+		static::$_ref_cache[$row['ref']][$row['name']] = $row['id'];
+		static::$_alias_cache[$row['alias']][$row['name']] = $row['id'];
+	}
+}
+
+public static function _ref_to_id($tablename, $fieldname)
+{
+	if (isset(static::$_ref_cache[$tablename][$fieldname]))
+		return static::$_ref_cache[$tablename][$fieldname];
+}
+
 public static function _c_fields()
 {
 	return static::$_c_fields;
@@ -164,7 +212,8 @@ public static function _c_data_get($table_name)
 	
 	// Table informations
 	$sql = 'SHOW FULL COLUMNS FROM '.static::$_db_prefix.$table_name;
-	//echo $sql; die();
+	if (DEBUG_SQL)
+		var_dump($sql);
 	$q = $db->query($sql);
 	$f = [];
 	while($r=$q->fetch_assoc())
@@ -184,7 +233,8 @@ public static function _i_data_get($table_name)
 	
 	// Table informations
 	$sql = 'SHOW INDEX FROM '.static::$_db_prefix.$table_name;
-	//echo $sql; die();
+	if (DEBUG_SQL)
+		var_dump($sql);
 	$q = $db->query($sql);
 	$f = [];
 	while($r=$q->fetch_assoc()) {
@@ -203,7 +253,8 @@ public static function _c_insert($table_name, $row)
 	$options = explode(',', $row['Extra']);
 	$sql = 'ALTER TABLE `'.static::$_db_prefix.$table_name.'`
 		ADD `'.$row['Field'].'` '.$row['Type'].($row['Collation'] ?' CHARACTER SET utf8mb4'.' COLLATE '.$row['Collation'] :'').($row['Null'] ?' NULL' :' NOT NULL').' DEFAULT '.(is_null($row['Default']) ?'NULL' :'"'.$row['Default'].'"').' '.(in_array('auto_increment', $options) ?' AUTO_INCREMENT' :'').(in_array('unsigned', $options) ?' UNSIGNED' :'').';';
-	echo '<p>'.$sql.'</p>'; //return;
+	if (DEBUG_SQL)
+		var_dump($sql);
 	return static::$__db->query($sql);
 }
 /**
@@ -214,7 +265,8 @@ public static function _c_update($table_name, $row)
 	$options = explode(',', $row['Extra']);
 	$sql = 'ALTER TABLE `'.static::$_db_prefix.$table_name.'`
 		CHANGE `'.$row['Field'].'` `'.$row['Field'].'` '.$row['Type'].($row['Collation'] ?' CHARACTER SET utf8mb4'.' COLLATE '.$row['Collation'] :'').($row['Null']=='YES' ?' NULL' :' NOT NULL').' DEFAULT '.(is_null($row['Default']) ?'NULL' :'"'.$row['Default'].'"').' '.(in_array('auto_increment', $options) ?' AUTO_INCREMENT' :'').(in_array('unsigned', $options) ?' UNSIGNED' :'').';';
-	echo '<p>'.$sql.'</p>'; //return;
+	if (DEBUG_SQL)
+		var_dump($sql);
 	return static::$__db->query($sql);
 }
 /**
@@ -224,7 +276,8 @@ public static function _c_delete($table_name, $row)
 {
 	$sql = 'ALTER TABLE `'.static::$_db_prefix.$table_name.'`
 		DROP column `'.$row['Field'].'`;';
-	echo '<p>'.$sql.'</p>'; //return;
+	if (DEBUG_SQL)
+		var_dump($sql);
 	return static::$__db->query($sql);
 }
 
@@ -238,7 +291,8 @@ public static function _i_insert($table_name, $row)
 	//$options = explode(',', $row['Extra']);
 	$sql = 'ALTER TABLE `'.static::$_db_prefix.$table_name.'`
 		ADD INDEX `'.$row['Key_name'].'` (`'.$row['Column_name'].'`);';
-	//echo '<p>'.$sql.'</p>'; //return;
+	if (DEBUG_SQL)
+		var_dump($sql);
 	$q = static::$__db->query($sql);
 	//var_dump($q);
 	return $q;
@@ -253,7 +307,8 @@ public static function _i_update($table_name, $row)
 	//$options = explode(',', $row['Extra']);
 	$sql = 'ALTER TABLE `'.static::$_db_prefix.$table_name.'`
 		CHANGE INDEX `'.$row['Key_name'].'` (`'.$row['Column_name'].'`);';
-	//echo '<p>'.$sql.'</p>'; //return;
+	if (DEBUG_SQL)
+		var_dump($sql);
 	$q = static::$__db->query($sql);
 	//var_dump($q);
 	return $q;
@@ -268,7 +323,8 @@ public static function _i_delete($table_name, $row)
 	//$options = explode(',', $row['Extra']);
 	$sql = 'ALTER TABLE `'.static::$_db_prefix.$table_name.'`
 		DROP INDEX `'.$row['Key_name'].'`';
-	//echo '<p>'.$sql.'</p>'; //return;
+	if (DEBUG_SQL)
+		var_dump($sql);
 	$q = static::$__db->query($sql);
 	//var_dump($q);
 	return $q;
@@ -280,22 +336,8 @@ public static function _i_delete($table_name, $row)
 public static function _select_by_table($id)
 {
 	static::__log(__METHOD__);
-	$db = static::$__db;
 	
-	$fields = [];
-	// Actual Fields information
-	$sql = 'SELECT *
-		FROM `'.static::$_db_table.'`
-		WHERE `table_id`="'.$id.'"';
-	//echo $sql; die();
-	$q = $db->query($sql);
-	while($r=$q->fetch_assoc()) {
-		$o = new static($r['id'], $r);
-		$fields[$r['name']] = $o;
-	}
-	//var_dump($fields);
-	
-	return $fields;
+	return static::$_table_cache[$id];
 }
 
 // Object
@@ -303,14 +345,36 @@ public static function _select_by_table($id)
 public function map_data_get($map_id)
 {
 	if (!isset(static::$_map_cache[$this->id])) {
-		static::$_map_cache[$this->id] = [];
-		$sql = 'SELECT *
-			FROM _map_'.static::$_prefix.'fields';
-		$q = static::$__db->query($sql);
-		//var_dump($sql); var_dump($q);
-		while($row = $q->fetch_assoc())
-			static::$_map_cache[$row['field_id']][$row['map_id']] = $row;
-		//var_dump($map); die();
+		// On en a déjà => pas requête
+		if (!empty(static::$_map_cache)) {
+			static::$_map_cache[$this->id] = [];
+		}
+		
+		else {
+			static::$_map_cache[$this->id] = [];
+			$sql = 'SELECT *
+				FROM _map_'.static::$_prefix.'fields';
+			if (DEBUG_SQL)
+				var_dump($sql);
+			$q = static::$__db->query($sql);
+			//var_dump($q);
+			while($row = $q->fetch_assoc()) {
+				if (false && !empty($row['field_id'])) {
+					static::$_map_cache[$row['field_id']][$row['map_id']] = $row;
+				}
+				elseif(!empty($row['field'])) {
+					list($tablealias, $fieldname) = explode('.', $row['field']);
+					$field_id = static::$_alias_cache[$tablealias][$fieldname];
+					static::$_map_cache[$field_id][$row['map_id']] = $row;
+					//var_dump($tablename); var_dump($fieldname);
+				}
+				else {
+					var_dump('COUILLE ASSOC CHAMP MAP');
+					continue;
+				}
+			}
+			//var_dump($map); die();
+		}
 	}
 	
 	if (isset(static::$_map_cache[$this->id][$map_id]))
@@ -321,4 +385,5 @@ public function map_data_get($map_id)
 
 }
 
-Field::__init();
+//Field::__init();
+

+ 4 - 1
src/class/table/p_field.php

@@ -9,14 +9,17 @@ class P_Field extends Field {
 /* ORM\Base */
 protected static $_db_table = '_p_fields';
 /* Table\Field */
-protected static $_prefix = '_p';
+protected static $_prefix = 'p_';
 /* Associated database name */
 protected static $_db_prefix = 'ps_';
 
 protected static $_cache = [];
+protected static $_table_cache = [];
 protected static $_c_cache = [];
 protected static $_i_cache = [];
 protected static $_map_cache = [];
+protected static $_ref_cache = [];
+protected static $_alias_cache = [];
 
 }
 

+ 3 - 0
src/class/table/p_table.php

@@ -9,6 +9,9 @@ class P_Table extends Table
 {
 
 protected static $_cache = [];
+protected static $_row_cache = [];
+protected static $_ref_cache = [];
+protected static $_alias_cache = [];
 
 /* ORM\Base */
 protected static $_db_table = '_p_tables';

+ 69 - 11
src/class/table/table.php

@@ -29,6 +29,10 @@ protected static $_fields = [
 		'label'=>'Label',
 		'label',
 	],
+	'alias' => [
+		'label'=>'Alias',
+		'unique',
+	],
 	'details' => [
 		'label'=>'Details',
 	],
@@ -67,6 +71,48 @@ protected static $_fields = [
 	],
 ];
 
+protected static $_row_cache = [];
+protected static $_ref_cache = [];
+protected static $_alias_cache = [];
+
+public static function __init()
+{
+	parent::__init();
+	static::_cache_all();
+}
+
+public static function _cache_all($force=false)
+{
+	if (!empty(static::$_alias_cache) && !$force)
+		return;
+	
+	// On met tout en cache direct !
+	$sql = 'SELECT *
+		FROM _'.static::$_prefix.'tables';
+	if (DEBUG_SQL)
+		var_dump($sql);
+	//echo $sql;
+	$q = static::$__db->query($sql);
+	//var_dump($q); die();
+	while($row = $q->fetch_assoc()) {
+		static::$_alias_cache[$row['alias']] = $row['id'];
+		static::$_ref_cache[$row['ref']] = $row['id'];
+		static::$_row_cache[$row['id']] = $row;
+	}
+}
+
+public static function _ref_to_id($tablename)
+{
+	if (isset(static::$_ref_cache[$tablename]))
+		return static::$_ref_cache[$tablename];
+}
+
+public static function _alias_to_id($tablename)
+{
+	if (isset(static::$_alias_cache[$tablename]))
+		return static::$_alias_cache[$tablename];
+}
+
 public static function _get_by_id($id)
 {
 	static::__log(__METHOD__);
@@ -221,6 +267,7 @@ public function fields_index()
 		
 		//$key = $row['Key']; //Inutile
 		//$comment = $row['Comment']; //Inutile
+		//var_dump($ref);
 		
 		$type_e = explode(' ', $row['Type']);
 		if (isset($type_e[1])) {
@@ -256,7 +303,7 @@ public function fields_index()
 		
 		// Champs à size
 		if (in_array($type, ['int', 'string', 'float']))
-			$size = $matches[3];
+			$size = isset($matches[3])?$matches[3] :($type=='double' ?'16,4' :NULL);
 		else
 			$size = NULL;
 		
@@ -309,6 +356,8 @@ public function get($params)
 	$db = static::$__db;
 	
 	$sql = $this->select_sql($params);
+	if (DEBUG_SQL)
+		var_dump($sql);
 	
 	$q = $db->query($sql);
 	if ($row = $q->fetch_assoc())
@@ -320,7 +369,8 @@ public function select($params)
 	$db = static::$__db;
 	
 	$sql = $this->select_sql($params);
-	echo '<p>'.$sql.'</p>';
+	if (DEBUG_SQL)
+		var_dump($sql);
 	$q = $db->query($sql);
 	$r = [];
 	$keys = $this->ident_fields();
@@ -354,27 +404,33 @@ public function select_sql($params)
 		WHERE ';
 	
 	$sql .= $this->sql_params($params);
-	//echo $sql;
+	if (DEBUG_SQL)
+		var_dump($sql);
 	return $sql;
 }
 
-public function data_insert($data)
+public function data_insert($data, $params=[])
 {
 	$db = static::$__db;
-	$sql = $this->data_insert_sql($data);
+	$sql = $this->data_insert_sql($data, $params);
+	if (DEBUG_SQL)
+		var_dump($sql);
 	//$q = $db->query($sql);
 	//$this->log($params, 'i', $data);
 }
-public function data_insert_sql($data)
+/**
+ * @param $data donnée à insérer
+ * @param $params données supplémentaires servant de paramètres
+ */
+public function data_insert_sql($data, $params=[])
 {
 	//echo '<p>Création</p>'; var_dump($data);
 	$f = $v = [];
-	foreach($data as $fieldname=>$value) {
+	foreach(array_merge($data, $params) as $fieldname=>$value) {
 		$f[] = '`'.$fieldname.'`';
 		$v[] = (is_null($value) || (empty($value) && $fieldname==$this->f_pk)) ?'NULL' :'"'.static::$__db->real_escape_string($value).'"';
 	}
 	$sql = 'INSERT INTO `'.static::$_db_prefix.$this->ref.'` ('.implode(', ', $f).') VALUES ('.implode(', ', $v).')';
-	//echo $sql;
 	return $sql;
 }
 
@@ -382,6 +438,8 @@ public function data_delete($params)
 {
 	$db = static::$__db;
 	$sql = $this->data_delete_sql($params);
+	if (DEBUG_SQL)
+		var_dump($sql);
 	//$q = $db->query($sql);
 	//$this->log($params, 'd');
 }
@@ -389,7 +447,6 @@ public function data_delete_sql($params)
 {
 	//echo '<p>Suppression</p>'; var_dump($params);
 	$sql = 'DELETE FROM `'.static::$_db_prefix.$this->ref.'` WHERE '.$this->sql_params($params);
-	//echo $sql;
 	return $sql;
 }
 
@@ -423,8 +480,9 @@ public function log($id, $action, $data=null)
 		(`ts`, `tid`, `oid`, `rev`, `action`, `fields`, `details`)
 		VALUES
 		(NOW(), '.$this->id.', '.$id.', '.$rev.', "'.$action.'", "'.json_encode(is_array($data) ?array_keys($data) :NULL).'", "'.json_encode($data).'")';
-	echo $sql; die();
-	//$q = $db->query($sql);
+	if (DEBUG_SQL)
+		var_dump($sql);
+	$q = $db->query($sql);
 }
 
 }

+ 0 - 40
src/controller/synchro_order.php

@@ -12,46 +12,6 @@ protected $viewmodel_name = 'sync/sync';
 
 protected $params = [];
 
-/**
- * Associe des objets
- * Ensuite on pourra les synchroniser
- * Ordre d'association : dp = Doli => Presta
- */
-protected function assoc_exec($order='dp', $r)
-{
-	static::__log(__METHOD__);
-	
-	if(is_string($r))
-		$r = explode('-', $r);
-	var_dump($r);
-	
-	$id = $r[0];
-	$d_product_id = $r[1];
-	$p_product_id = $r[2];
-	$p_product_attribute_id = $r[3];
-	$ref = $r[4];
-	
-	// Association CRUD
-	
-	// Add sync object
-	if (empty($id)) {
-		$id = $this->model_add($ref);
-		
-		if (!empty($d_product_id)) {
-			$this->model_dt_assoc($id, $this->d_product_tid, $d_product_id);
-		}
-		if (!empty($p_product_id)) {
-			$this->model_pt_assoc($id, $this->p_product_tid, $p_product_id);
-		}
-		if (!empty($p_product_attribute_id)) {
-			$this->model_pt_assoc($id, $this->p_product_attribute_tid, $p_product_attribute_id);
-		}
-		die();
-	}
-	else {
-	}
-}
-
 }
 
 synchro_order::__init();

+ 0 - 21
src/controller/synchro_supplier.php

@@ -12,27 +12,6 @@ protected $viewmodel_name = 'sync/sync';
 
 protected $params = [];
 
-/**
- * Associe des objets
- * Ensuite on pourra les synchroniser
- * Ordre d'association : dp = Doli => Presta
- */
-protected function assoc_exec($order='dp', $r)
-{
-	static::__log(__METHOD__);
-	
-	if(is_string($r))
-		$r = explode('-', $r);
-	var_dump($r);
-	
-	$id = $r[0];
-	$d_product_id = $r[1];
-	$p_product_id = $r[2];
-	$p_product_attribute_id = $r[3];
-	$ref = $r[4];
-	
-}
-
 }
 
 synchro_supplier::__init();

+ 48 - 1
src/model/order.php

@@ -21,8 +21,55 @@ protected static $_dt_alias = [];
 protected static $_maps = [];
 
 protected static $_map_values = [];
-protected static $_map_fct = [];
+protected static $_map_fct = [
+	'd' => [
+		//'tva_tx' => '',
+		'fk_product'=>'',
+		'fk_customer'=>'',
+	],
+	'p' => [
+		//'id_tax_rules_group' => '',
+	],
+];
+
+public static function _d_map_fk_product($p_data, $d_tree=[])
+{
+	$orig = 'p';
+	//var_dump($p_data); var_dump($d_tree);
+	$id_product = $p_data['order_detail']['product_id'];
+	$id_product_attribute = $p_data['order_detail']['product_attribute_id'];
+	
+	$modelname = 'product';
+	
+	if (empty($id_product_attribute)) {
+		$map_id = 1;
+		$tablename = 'product';
+		$oid = $id_product;
+	}
+	else {
+		$map_id = 2;
+		$tablename = 'product_attribute';
+		$oid = $id_product_attribute;
+	}
+	
+	return static::_map_fk($orig, $modelname, $map_id, $tablename, $oid);
+}
+
+public static function _d_map_fk_customer($p_data, $d_tree=[])
+{
+	$orig = 'p';
+	//var_dump($p_data); var_dump($d_tree);
+	$oid = $p_data['orders']['id_customer'];
+	//
+	$modelname = 'customer';
+	$map_id = 4;
+	$tablename = 'customer';
+	
+	return static::_map_fk($orig, $modelname, $map_id, $tablename, $oid);
+}
+
 
 }
 
 order::__init();
+

+ 27 - 0
src/model/product.php

@@ -28,12 +28,14 @@ protected static $_map_fct = [
 		'barcode_type' => '',
 		'is_batch' => '',
 		'tva_tx' => '',
+		'fk_supplier' => '',
 	],
 	'p' => [
 		'id_tax_rules_group' => '',
 		'ean' => '',
 		'isbn' => '',
 		'upc' => '',
+		'fk_supplier' => '',
 	],
 ];
 
@@ -44,6 +46,31 @@ protected static $_p_product_attribute_tid = 5;
 protected static $_d_product_tname = '';
 protected static $_d_product_tid = 1;
 
+public static function _d_map_fk_supplier($p_data, $d_tree=[])
+{
+	$orig = 'p';
+	//var_dump($p_data); var_dump($d_tree);
+	$oid = $p_data['product_supplier']['id_supplier'];
+	//
+	$modelname = 'supplier';
+	$map_id = 3;
+	$tablename = 'supplier';
+	
+	return static::_map_fk($orig, $modelname, $map_id, $tablename, $oid);
+}
+public static function _p_map_fk_supplier($d_data, $d_tree=[])
+{
+	$orig = 'd';
+	//var_dump($p_data); var_dump($d_tree);
+	$oid = $d_data['product_fournisseur_price']['fk_soc'];
+	//
+	$modelname = 'supplier';
+	$map_id = 3;
+	$tablename = 'societe';
+	
+	return static::_map_fk($orig, $modelname, $map_id, $tablename, $oid);
+}
+
 public static function _d_map_product_url($p_data, $d_tree=[])
 {
 	return static::$__p_params['url'].'/'.static::$__p_params['lang'].'/'.$p_data['product']['id_product'].'-'.$p_data['product_lang']['link_rewrite'];

+ 15 - 0
src/viewmodel/model/index.php

@@ -0,0 +1,15 @@
+<?php
+
+namespace ViewModel;
+
+require_once CLASS_PATH.'/viewmodel/base.php';
+
+class IndexViewModel extends BaseViewModel
+{
+
+protected $filename = 'model/index';
+
+}
+
+IndexViewModel::__init();
+

+ 14 - 0
web/order.php

@@ -0,0 +1,14 @@
+<?php
+
+require_once "bootstrap.inc.php";
+//echo 'bootstrap loaded';
+
+require_once CONTROLLER_PATH."/synchro_order.php";
+
+$controller = new Controller\synchro_order();
+
+$controller->execute();
+
+$controller->display();
+
+//echo '<hr />'; echo '<h2>Debug</h2>'; $logger->display();