Przeglądaj źródła

updated SystemObjectField reisntall, structure

Piotr Labudda 9 lat temu
rodzic
commit
0ee4b4c287

+ 108 - 42
SE/se-lib/Route/Storage.php

@@ -642,46 +642,58 @@ jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', fun
 		UI::gora();
 		UI::menu();
 		$this->navView();
+		UI::startTag('div', [ 'class' => 'container-fluid' ]);
 		try {
 			$namespace = V::get('namespace', '', $_GET);
 			if (empty($namespace)) throw new Exception("Missing param namespace");
-			$item = $this->getObjectAclRow($namespace);
+			$item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
 			DBG::nicePrint($item, '$item');
-			// DBG::log($item, 'array', '$item');
-			switch ($item['_type']) {
-				case 'TableAcl': $this->structTableAclView($item); break;
-				default: throw new Exception("Not implemented struct view for '{$namespace}'");
-			}
+			usort($item['field'], function ($a, $b) {
+				if ($a['fieldNamespace'] > $b['fieldNamespace']) return 1;
+				if ($a['fieldNamespace'] < $b['fieldNamespace']) return -1;
+				return 0;
+			});
+			echo ($item['idZasob'] > 0)
+				? UI::h('h3', [], "Nr zasobu {$item['idZasob']}")
+				: UI::h('h3', [], "Nr zasobu ???");// TODO: UI::hButtonAjax(...)
+			UI::table([
+				'caption' => UI::h('h3', [], "Struktura obiektu '{$item['namespace']}'"),
+				'rows' => array_map(function ($field) {
+					$tblItem = []; foreach ($field as $k => $v) $tblItem[$k] = $v;
+					$tblItem['namespace'] = UI::h('span', [], [
+						UI::h('span', ['style' => "color:#aaa"], substr($field['namespace'], 0, strlen($field['objectNamespace']) + 1)),
+						UI::h('span', ['style' => "color:#000"], substr($field['namespace'], strlen($field['objectNamespace']) + 1)),
+					]);
+					$tblItem['idZasob'] = ($field['idZasob'] > 0)
+						? $field['idZasob']
+						: UI::hButtonAjax("+ do zasobów", 'addFieldToZasoby', [
+							'class' => "btn btn-xs btn-primary",
+							'href' => Request::getPathUri() . "index.php?_route=Storage&_task=addFieldToZasoby",
+							'data' => [
+								'namespace' => $field['namespace'],
+							]
+						]);
+					unset($tblItem['objectNamespace']);
+					unset($tblItem['fieldNamespace']);
+					return $tblItem;
+				}, $item['field'])
+			]);
+			UI::hButtonAjaxOnResponse('addFieldToZasoby', "
+				if (!payload.type) return false
+				console.log('TODO: addFieldToZasoby response', payload);
+				if (payload.data && payload.data.id && payload.data.id > 0) { // if ('success' == payload.type) {
+					n.parentNode.replaceChild(document.createTextNode(payload.data.id), n)
+				} else {
+					console.log('TODO: addFieldToZasoby unknown response', payload);
+				}
+			");
 		} catch (Exception $e) {
 			UI::alert('danger', "Error #" . $e->getCode() .  "|" . $e->getLine() .  ": " . $e->getMessage());
 			DBG::log($e);
 		}
+		UI::endTag('div'); // .container-fluid
 		UI::dol();
 	}
-	public function structTableAclView($item) {
-		UI::table([
-			'caption' => UI::h('h3', [], "Struktura obiektu '{$item['namespace']}'"),
-			'rows' => array_map(function ($field) {
-				return $field;
-			}, $this->getObjectFields($item))
-		]);
-	}
-	public function getObjectFields($namespace) {
-		Lib::loadClass('Schema_SystemObjectFieldStorageAcl');
-		$acl = new Schema_SystemObjectFieldStorageAcl();
-		$items = $acl->getItems([
-			'#refFrom' => [
-				'namespace' => 'default_objects/SystemObject',
-				'primaryKey' => $namespace
-			],
-			'order_by' => 'namespace',
-			'order_dir' => 'asc'
-		]);
-		if (empty($items)) throw new Exception("SystemObject '{$namespace}' not found");
-		$item = reset($items);
-		if (empty($item)) throw new Exception("SystemObject '{$namespace}' not found");
-		return $item;
-	}
 
 	public function tableStructAction() {
 		UI::gora();
@@ -1542,6 +1554,72 @@ jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', fun
 		Response::sendJsonExit($response);
 	}
 
+	public function addFieldToZasobyAction() {
+		DBG::log($_REQUEST, 'array', '$_REQUEST');
+		Response::sendTryCatchJson(array($this, 'addFieldToZasoby'), $_REQUEST);
+	}
+	public function addFieldToZasoby($args) {
+		$namespace = V::get('namespace', '', $args);
+		if (empty($namespace)) throw new HttpException("Missing namespace");
+
+		$fieldItem = SchemaFactory::loadDefaultObject('SystemObjectField')->getItem($namespace);
+		$zasobTableName = substr($fieldItem['objectNamespace'], strlen('default_db/'));
+		$zasobTableName = (false !== strpos($zasobTableName, '/'))
+			? $fieldItem['objectNamespace']
+			: $zasobTableName;
+		$zasobItem = DB::getPDO()->fetchFirst("
+			select zField.ID, zField.`DESC`, zField.`TYPE`, zField.PARENT_ID
+			from CRM_LISTA_ZASOBOW as zField
+				join CRM_LISTA_ZASOBOW as zTable on(zTable.ID = zField.PARENT_ID)
+			where zTable.PARENT_ID = {$fieldItem['idDatabase']}
+				and zTable.`DESC` = '{$zasobTableName}'
+				and zTable.`TYPE` = 'TABELA'
+				and zField.`DESC` = '{$fieldItem['fieldNamespace']}'
+				and zField.`TYPE` = 'KOMORKA'
+		");
+		if ($zasobItem) {
+			SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
+				'namespace' => $namespace,
+				'idZasob' => $zasobItem['ID']
+			]);
+			return [
+				'type' => 'success',
+				'msg' => "Zasob już istnieje",
+				'data' => [
+					'id' => $zasobItem['ID']
+				],
+				'__DBG__' => [
+					$zasobItem,
+					$fieldItem,
+					$args,
+				]
+			];
+		}
+
+		return [
+			'type' => 'success',
+			'msg' => "TODO: addFieldToZasoby",
+			'data' => [
+				'id' => 123
+			],
+			'__DBG__' => [
+				$zasobItem,
+				$fieldItem,
+				$args,
+			]
+		];
+
+		// throw new Exception("TODO: F.addFieldToZasoby");
+
+		return [
+			'type' => 'success',
+			'msg' => "TODO: addFieldToZasoby",
+			'data' => [
+				'id' => 123
+			],
+			'__DBG__args' => $args
+		];
+	}
 	public function addCellToZasobyAction() {// sends JSON
 		$response = new stdClass();
 		try {
@@ -1664,18 +1742,6 @@ jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', fun
 		UI::dol();
 	}
 
-	public function getObjectAclRow($namespace) {
-		Lib::loadClass('Schema_SystemObjectStorageAcl');
-		$acl = new Schema_SystemObjectStorageAcl();
-		$items = $acl->getItems([
-			'f_namespace' => "={$namespace}",
-		]);
-		if (empty($items)) throw new Exception("SystemObject '{$namespace}' not found");
-		$item = reset($items);
-		if (empty($item)) throw new Exception("SystemObject '{$namespace}' not found");
-		return $item;
-	}
-
 	public function objectReinstallAction() {
 		UI::gora();
 		UI::startContainer();

+ 54 - 39
SE/se-lib/Schema/SystemObjectFieldStorageAcl.php

@@ -9,10 +9,11 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
   public $_simpleSchema = [
     'root' => [
       '@namespace' => 'default_objects/SystemObjectField',
-      '@primaryKey' => 'fieldNamespace',
+      '@primaryKey' => 'namespace',
       'idZasob' => [ '@type' => 'xsd:integer' ],
       'idDatabase' => [ '@type' => 'xsd:integer' ],
       '_rootTableName' => [ '@type' => 'xsd:string' ],
+      'namespace' => [ '@type' => 'xsd:string' ],
       'objectNamespace' => [ '@type' => 'xsd:string' ],
       'fieldNamespace' => [ '@type' => 'xsd:string' ],
       'xsdType' => [ '@type' => 'xsd:string' ],
@@ -36,6 +37,7 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
     // DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}` "); // TODO: DBG
     DB::getPDO()->execSql("
       create table if not exists `{$this->_rootTableName}` (
+        `namespace` varchar(255) DEFAULT '',
         `fieldNamespace` varchar(255) DEFAULT '',
         `idZasob` int(11) DEFAULT NULL,
         `idDatabase` int(11) NOT NULL,
@@ -48,7 +50,7 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
         `isActive` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'installed',
         `description` varchar(255) DEFAULT '',
         UNIQUE KEY `idZasob` (idZasob),
-        UNIQUE KEY `namespace` (objectNamespace, fieldNamespace),
+        PRIMARY KEY (`namespace`),
         KEY `isActive` (isActive)
       ) ENGINE=MyISAM  DEFAULT CHARSET=latin2
     ");
@@ -155,7 +157,7 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
 					DBG::log($n, 'array', "Schema xsd parse error - Not implemented node type '{$f[0]}'");
 					continue;
 				}
-				$fieldName = V::get('name', '', $f[1]);
+				$fieldName = XML::findElementName($schema, $f); // V::get('name', '', $f[1]);
 				if (!$fieldName) throw new Exception("Error Parsing Schema - expected 'element[@name]'");
 				if ('__' === substr($fieldName, 0, 2)) continue;
 				if (!V::get('type', '', $f[1]) && !V::get('ref', '', $f[1]) && empty($f[2])) {
@@ -163,43 +165,11 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
 					continue;
 				}
 				$xsdType['struct'][$fieldName] = [
-					'type' => V::get('type', '', $f[1]),
-					'ref' => V::get('ref', '', $f[1]),
+          'type' => XML::findElementType($schema, $f),
 					'minOccurs' => V::get('minOccurs', 0, $f[1], 'int'),
 					'maxOccurs' => V::get('maxOccurs', '1', $f[1]),
-          'restrictions' => [],
+          'restrictions' => XML::findElementRestrictions($schema, $f),
 				];
-        if (!empty($f[1]['nillable']) && 'true' === $f[1]['nillable']) $xsdType['struct'][$fieldName]['restrictions']['nillable'] = true;
-        if (!empty($f[2])) {
-          if (empty($f[2][0][0]) || 'xsd:simpleType' != $f[2][0][0]) throw new Exception("Missing 'xsd:simpleType' for field '{$fieldName}'");
-          if (empty($f[2][0][2][0]) || 'xsd:restriction' != $f[2][0][2][0][0]) throw new Exception("Missing 'xsd:restriction' for field '{$fieldName}'");
-          if (empty($f[2][0][2][0][1]['base'])) throw new Exception("Missing 'xsd:restriction/@base' for field '{$fieldName}'");
-          // [2] => Array:
-          //    [0] => Array:
-          //             [0] => xsd:simpleType
-          //             [1] => Array:
-          //             [2] => Array:
-          //                 [0] => Array:
-          //                     [0] => xsd:restriction
-          //                     [1] => Array:
-          //                         [base] => xsd:string
-          //                     [2] => Array:
-          foreach ($f[2][0][2][0][2] as $tagRestriction) {
-            //                         [0] => Array:
-            //                             [0] => xsd:maxLength
-            //                             [1] => Array:
-            //                                 [value] => 20
-            //                             [2] =>
-            $val = $tagRestriction[1]['value'];
-            if ('xsd:enumeration' == $tagRestriction[0]) {
-              $restrictions['enumeration'][$val] = $val;
-            } else {
-              $restrictions[substr($tagRestriction[0], 4)] = $val;
-            }
-          }
-          DBG::nicePrint(['f'=>$f, '$restr'=>$restrictions], 'TODO: field childrens f[2]');
-          if (!empty($restrictions)) $xsdType['struct'][$fieldName]['restrictions'] = $restrictions;
-        }
 			}
 		}
 
@@ -207,11 +177,12 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
     if (empty($xsdType['struct'])) throw new Exception("Field list not found for '{$item['namespace']}'");
     foreach ($xsdType['struct'] as $fieldName => $x) {
       DB::getPDO()->insertOrUpdate($this->_rootTableName, [
+        'namespace' => "{$item['namespace']}/{$fieldName}",
         'objectNamespace' => $item['namespace'],
         'idDatabase' => $item['idDatabase'],
         '_rootTableName' => $item['_rootTableName'],
         'fieldNamespace' => $fieldName,
-        'xsdType' => (!empty($x['type'])) ? $x['type'] : "ref:{$x['ref']}",
+        'xsdType' => $x['type'],
         'xsdRestrictions' => json_encode($x['restrictions']),
         'minOccurs' => $x['minOccurs'],
         'maxOccurs' => $x['maxOccurs'],
@@ -222,9 +193,13 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
       'namespace' => $item['namespace'],
       'isStructInstalled' => 1
     ]);
+    $zasobTableName = substr($item['objectNamespace'], strlen('default_db/'));
+		$zasobTableName = (false !== strpos($zasobTableName, '/'))
+			? $item['objectNamespace']
+			: $zasobTableName;
     DB::getPDO()->execSql("
       update `{$this->_rootTableName}` t
-        join CRM_LISTA_ZASOBOW zp on(zp.PARENT_ID = {$item['idDatabase']} and zp.`DESC` = '{$item['_rootTableName']}')
+        join CRM_LISTA_ZASOBOW zp on(zp.PARENT_ID = {$item['idDatabase']} and zp.`DESC` = '{$zasobTableName}')
         join CRM_LISTA_ZASOBOW z on(z.PARENT_ID = zp.ID and z.`DESC` = t.fieldNamespace)
       set t.idZasob = z.ID
       where t.objectNamespace = '{$item['namespace']}'
@@ -261,6 +236,7 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
 
     foreach ($xsdInfo as $fieldName => $x) {
       DB::getPDO()->insertOrUpdate($this->_rootTableName, [
+        'namespace' => "{$item['namespace']}/{$fieldName}",
         'fieldNamespace' => $fieldName,
         'isActive' => 1,
         'idDatabase' => $item['idDatabase'],
@@ -274,6 +250,17 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
       'namespace' => $item['namespace'],
       'isStructInstalled' => 1
     ]);
+    $zasobTableName = substr($item['namespace'], strlen('default_db/'));
+		$zasobTableName = (false !== strpos($zasobTableName, '/'))
+			? $item['namespace']
+			: $zasobTableName;
+    DB::getPDO()->execSql("
+      update `{$this->_rootTableName}` t
+        join CRM_LISTA_ZASOBOW zp on(zp.PARENT_ID = {$item['idDatabase']} and zp.`DESC` = '{$zasobTableName}' and zp.PARENT_ID = {$item['idDatabase']})
+        join CRM_LISTA_ZASOBOW z on(z.PARENT_ID = zp.ID and z.`DESC` = t.fieldNamespace)
+      set t.idZasob = z.ID
+      where t.objectNamespace = '{$item['namespace']}'
+    ");
 
     $struct = $this->getItems([
       '__backRef' => [
@@ -415,6 +402,20 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
     ");
   }
 
+  public function getItem($pk, $params = []) {
+    if (!$pk) throw new Exception("Missing primary key '{$this->_namespace}'");
+    $pkField = $this->getSqlPrimaryKeyField();
+    if (!$pkField) throw new Exception("Missing primary key field defined in '{$this->_namespace}'");
+    $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
+    $item = DB::getPDO()->fetchFirst("
+      select t.*
+      from `{$this->_rootTableName}` t
+      where t.`{$pkField}` = {$sqlPk}
+    ");
+    if (!$item) throw new Exception("Item '{$pk}' not exists - type '{$this->_namespace}'");
+    return $this->buildFeatureFromSqlRow($item, $params);
+  }
+
   public function getItems($params = []) {
     $sqlWhere = $this->_parseWhere($params);
 
@@ -455,4 +456,18 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
     return $item;
   }
 
+  public function updateItem($itemPatch) {
+    $pkField = $this->getPrimaryKeyField();
+    $pk = V::get($pkField, null, $itemPatch);
+    if (null === $pk) throw new Exception("BUG missing primary key field for '{$this->_namespace}' updateItem");
+    DBG::log(['updateItem $itemPatch', $itemPatch]);
+    unset($itemPatch[$pkField]);
+    if (empty($itemPatch)) return 0;
+    foreach ($itemPatch as $fieldName => $value) {
+      if ('idZasob' == $fieldName) continue;
+      throw new Exception("Update field '{$fieldName}' not allowed for '{$this->_namespace}'");
+    }
+    return DB::getPDO()->update($this->_rootTableName, $pkField, $pk, $itemPatch);
+  }
+
 }