From 3ab77d673e6089231454865be554f247b6dcd07d Mon Sep 17 00:00:00 2001 From: John BOTELLA <68917336+thersane-john@users.noreply.github.com> Date: Wed, 15 Apr 2026 17:47:50 +0200 Subject: [PATCH] NEW : Quick memo module (#37422) * Add quick memo module * remove backport * remove under v24 code * fix css * remove dirt * Fix icon and z index * Fix option coherance * Missing trad * css * Move sql files * Mv langs files * missing langs files * PHP stan add lang trans from Dolibarr JS context * missing langs * remove duplicate lang * Fix lang load after lang move * remove useless try to include main * mv jsonResponce.class.php * rm comment * rm useless files * Fix lang load and remove module backport * Fix lang duplicate * fix php stan errors * fix php stan errors * fix query * Update memo.class.php * Update properties to allow null values * Remove old img * Fix sql filter * fields def change for php stan * PHP doc update * Comment * Fix php doc * Fix php doc * Fix php doc * Fix php doc * Fix php doc * Fix php stan feedback * Fix php stan feedback * Fix php stan feedback * Fix php stan feedback * Fix php stan feedback * Fix php stan feedback * Use new native css tooltips * php doc * php doc * php doc * Fix sql * remove static method * travis * travis * travis * Move modQuickMemo.class.php * Update llx_quickmemo_memo-quickmemo.sql --------- Co-authored-by: Laurent Destailleur --- dev/tools/phan/config.php | 1 + .../sanity_check_trans_missing_unused.sh | 6 +- htdocs/core/class/commonobject.class.php | 50 +- htdocs/core/class/jsonResponse.class.php | 90 + htdocs/core/modules/modQuickMemo.class.php | 401 +++ .../llx_quickmemo_memo-quickmemo.key.sql | 19 + .../tables/llx_quickmemo_memo-quickmemo.sql | 49 + ...ickmemo_memo_extrafields-quickmemo.key.sql | 19 + ...x_quickmemo_memo_extrafields-quickmemo.sql | 22 + .../llx_quickmemo_memo_user-quickmemo.key.sql | 17 + .../llx_quickmemo_memo_user-quickmemo.sql | 28 + htdocs/langs/en_US/quickmemo.lang | 100 + htdocs/langs/fr_FR/quickmemo.lang | 95 + htdocs/quickmemo/admin/memo_extrafields.php | 128 + htdocs/quickmemo/admin/setup.php | 287 ++ .../class/actions_quickmemo.class.php | 138 + htdocs/quickmemo/class/memo.class.php | 1612 ++++++++++ htdocs/quickmemo/css/memo-dialog.css | 276 ++ htdocs/quickmemo/css/memo.css | 601 ++++ htdocs/quickmemo/css/setup.css | 72 + htdocs/quickmemo/img/private.svg | 1 + htdocs/quickmemo/interface.php | 1052 ++++++ htdocs/quickmemo/js/QuickMemo.js | 2816 +++++++++++++++++ htdocs/quickmemo/lib/quickmemo.lib.php | 83 + htdocs/quickmemo/lib/quickmemo_memo.lib.php | 111 + htdocs/quickmemo/memo_list.php | 992 ++++++ test/phpunit/CommonClassTest.class.php | 1 + 27 files changed, 9055 insertions(+), 12 deletions(-) create mode 100644 htdocs/core/class/jsonResponse.class.php create mode 100644 htdocs/core/modules/modQuickMemo.class.php create mode 100644 htdocs/install/mysql/tables/llx_quickmemo_memo-quickmemo.key.sql create mode 100644 htdocs/install/mysql/tables/llx_quickmemo_memo-quickmemo.sql create mode 100644 htdocs/install/mysql/tables/llx_quickmemo_memo_extrafields-quickmemo.key.sql create mode 100644 htdocs/install/mysql/tables/llx_quickmemo_memo_extrafields-quickmemo.sql create mode 100644 htdocs/install/mysql/tables/llx_quickmemo_memo_user-quickmemo.key.sql create mode 100644 htdocs/install/mysql/tables/llx_quickmemo_memo_user-quickmemo.sql create mode 100644 htdocs/langs/en_US/quickmemo.lang create mode 100644 htdocs/langs/fr_FR/quickmemo.lang create mode 100644 htdocs/quickmemo/admin/memo_extrafields.php create mode 100644 htdocs/quickmemo/admin/setup.php create mode 100644 htdocs/quickmemo/class/actions_quickmemo.class.php create mode 100644 htdocs/quickmemo/class/memo.class.php create mode 100644 htdocs/quickmemo/css/memo-dialog.css create mode 100644 htdocs/quickmemo/css/memo.css create mode 100644 htdocs/quickmemo/css/setup.css create mode 100644 htdocs/quickmemo/img/private.svg create mode 100644 htdocs/quickmemo/interface.php create mode 100644 htdocs/quickmemo/js/QuickMemo.js create mode 100644 htdocs/quickmemo/lib/quickmemo.lib.php create mode 100644 htdocs/quickmemo/lib/quickmemo_memo.lib.php create mode 100644 htdocs/quickmemo/memo_list.php diff --git a/dev/tools/phan/config.php b/dev/tools/phan/config.php index a6247dd6eab..46d1d9335e9 100644 --- a/dev/tools/phan/config.php +++ b/dev/tools/phan/config.php @@ -152,6 +152,7 @@ $VALID_MODULE_MAPPING = array( 'productsupplierprice' => null, 'project' => 'Projet', 'propal' => 'Propale', + 'quickmemo' => null, 'receiptprinter' => 'ReceiptPrinter', 'reception' => 'Reception', 'recruitment' => 'Recruitment', diff --git a/dev/translation/sanity_check_trans_missing_unused.sh b/dev/translation/sanity_check_trans_missing_unused.sh index 381701bb969..b02a9a1da87 100755 --- a/dev/translation/sanity_check_trans_missing_unused.sh +++ b/dev/translation/sanity_check_trans_missing_unused.sh @@ -74,7 +74,7 @@ sort -u \ # EXTRACT_STR="" JOIN_STR="" -for t in '->trans' '->transnoentities' '->transnoentitiesnoconv' '->newItem' '->buttonsSaveCancel'; do +for t in '->trans' '->transnoentities' '->transnoentitiesnoconv' '->newItem' '->buttonsSaveCancel' 'Dolibarr.tools.langs.trans' 'Dolibarr.tools.langs.transNoEntities'; do MATCH_STR="$MATCH_STR$JOIN_STR$t" EXTRACT_STR="$EXTRACT_STR$JOIN_STR(?<=${t}\\([\"'])([^\"']+)(?=[\"']\$)" JOIN_STR="|" @@ -90,7 +90,7 @@ done # With std grep: `grep --no-filename -r ${GREP_OPTS} -- '->trans(' . ` # Using git grep avoiding to look into unversioned files # transnoentitiesnoconv - git grep -h -r -P -- "${MATCH_STR}\\(" ':*.php' ':*.html' \ + git grep -h -r -P -- "${MATCH_STR}\\(" ':*.php' ':*.html' ':*.js' \ | sed 's@\(^#\|[^:]//\|/\*\|^\s*\*\).*@@' \ | sed 's@)\|\(['"'"'"]\)\(,\)@\1\n@g' \ | grep -aPo "$EXTRACT_STR(?=.$)" @@ -162,7 +162,7 @@ if [ -s "${MISSING_FILE}.grep" ] ; then echo "##[group]List missing translations (used by code but not found into lang files) - Generate CTI errors" - git grep -n --column -r -F -f "${MISSING_FILE}.grep" -- ':*.php' ':*.html' \ + git grep -n --column -r -F -f "${MISSING_FILE}.grep" -- ':*.php' ':*.html' ':*.js' \ | sort -t: -k 4 \ | sed 's@^\([^:]*:[^:]*:[^:]*:\)\s*@\1 Missing translation; @' > "${MISSING_FILE}.result" diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 461bdae578b..c8f65a10903 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -153,8 +153,40 @@ abstract class CommonObject /** - * @var array|string,position:int,notnull?:int,visible:int<-6,6>|string,alwayseditable?:int<0,1>|string,noteditable?:int<0,1>,default?:string,index?:int,foreignkey?:string,searchall?:int<0,1>,isameasure?:int<0,1>,css?:string,cssview?:string,csslist?:string,help?:string,showoncombobox?:int<0,4>|string,disabled?:int<0,1>,arrayofkeyval?:array,autofocusoncreate?:int<0,1>,comment?:string,copytoclipboard?:int<1,2>,validate?:int<0,1>|string,showonheader?:int<0,1>,searchmulti?:int<0,1>}> Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. - * + * @var array> + * @phpstan-var array|string, + * position: int, + * visible: int<-6, 6>|string, + * langfile?: string, + * notnull?: int<-1, 1>, + * noteditable?: int<0, 1>, + * alwayseditable?: int<0, 1>|string, + * default?: string|int, + * index?: int<0, 1>, + * foreignkey?: string, + * searchall?: int<0, 1>, + * isameasure?: int<0, 1>, + * css?: string, + * cssview?: string, + * csslist?: string, + * help?: string, + * helplist?: string, + * showoncombobox?: int<0, 4>|string, + * disabled?: int<0, 1>|string, + * arrayofkeyval?: array, + * autofocusoncreate?: int<0, 1>, + * comment?: string, + * copytoclipboard?: int<1, 2>, + * validate?: int<0, 1>|string, + * showonheader?: int<0, 1>, + * searchmulti?: int<0, 1>, + * picto?: string, + * required?: int<0, 1>, + * placeholder?: string + * }> * 'type' field format: * 'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]', * 'select' (list of values are in 'options'. for integer list of values are in 'arrayofkeyval'), @@ -8702,13 +8734,13 @@ abstract class CommonObject * Return HTML string to show a field into a page * Code very similar with showOutputField of extra fields * - * @param array{type:string,label:string,enabled:int<0,2>|string,position:int,notnull?:int,visible:int,noteditable?:int,default?:string,index?:int,foreignkey?:string,searchall?:int,isameasure?:int,css?:string,csslist?:string,help?:string,showoncombobox?:int,disabled?:int,arrayofkeyval?:array,comment?:string} $val Array of properties of field to show - * @param string $key Key of attribute - * @param string|int $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) - * @param string $moreparam To add more parameters on html tag - * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names) - * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names) - * @param mixed $morecss Value for CSS to use (Old usage: May also be a numeric to define a size). + * @param array{type:string,label:string,enabled:int<0,2>|string,position:int,notnull?:int,visible:int<-6,6>,noteditable?:int,default?:int|string,index?:int,foreignkey?:string,searchall?:int,isameasure?:int,css?:string,csslist?:string,cssview?:string,help?:string,showoncombobox?:int,disabled?:int,arrayofkeyval?:array,comment?:string,validate?:int,required?:int,picto?:string} $val Array of properties of field to show + * @param string $key Key of attribute + * @param string|int|null $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) + * @param string $moreparam To add more parameters on html tag + * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names) + * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names) + * @param mixed $morecss Value for CSS to use (Old usage: May also be a numeric to define a size). * @return string */ public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '') diff --git a/htdocs/core/class/jsonResponse.class.php b/htdocs/core/class/jsonResponse.class.php new file mode 100644 index 00000000000..8bb492c91bf --- /dev/null +++ b/htdocs/core/class/jsonResponse.class.php @@ -0,0 +1,90 @@ +. + */ + + +/** + * Class JsonResponse + * used for ajax responses in Dolibarr + */ +class JsonResponse +{ + + /** + * the call status to determine if success or fail + * + * @var int $result 0|1 + */ + public $result = 0; + + /** + * data to return to call can be all type you want + * + * @var mixed + */ + public $data; + + /** + * debug data + * + * @var mixed + */ + public $debug; + + /** + * returned message used usually as set event message + * + * @var string $msg + */ + public $msg = ''; + + /** + * the current newToken + * + * @var mixed|string + */ + public $newToken = ''; + + /** + * JsonResponse constructor. + */ + public function __construct() + { + $this->newToken = newToken(); + } + + /** + * return json encoded of object + * + * @return string JSON + */ + public function getResponse() + { + + if (!$this->result && !headers_sent()) { + http_response_code(400); + } + + $jsonResponse = new stdClass(); + $jsonResponse->result = $this->result; + $jsonResponse->msg = $this->msg; + $jsonResponse->newToken = $this->newToken; + $jsonResponse->data = $this->data; + $jsonResponse->debug = $this->debug; + + return json_encode($jsonResponse, JSON_PRETTY_PRINT); + } +} diff --git a/htdocs/core/modules/modQuickMemo.class.php b/htdocs/core/modules/modQuickMemo.class.php new file mode 100644 index 00000000000..8ed45df74d1 --- /dev/null +++ b/htdocs/core/modules/modQuickMemo.class.php @@ -0,0 +1,401 @@ + + * Copyright (C) 2018-2019 Nicolas ZABOURI + * Copyright (C) 2019-2024 Frédéric France + * Copyright (C) 2026 John BOTELLA + * + * 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 3 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, see . + */ + +/** + * \defgroup quickmemo Module QuickMemo + * \brief QuickMemo module descriptor. + * + * \file htdocs/quickmemo/core/modules/modQuickMemo.class.php + * \ingroup quickmemo + * \brief Description and activation file for module QuickMemo + */ +include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; + + +/** + * Description and activation class for module QuickMemo + */ +class modQuickMemo extends DolibarrModules +{ + /** + * Constructor. Define names, constants, directories, boxes, permissions + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + global $conf, $langs; + + $this->db = $db; + + // Id for module (must be unique). + // Use here a free id (See in Home -> System information -> Dolibarr for list of used modules id). + $this->numero = 141916; + + // Key text used to identify module (for permissions, menus, etc...) + $this->rights_class = 'quickmemo'; + + // Family can be 'base' (core modules),'crm','financial','hr','projects','products','ecm','technic' (transverse modules),'interface' (link with external tools),'other','...' + // It is used to group modules by family in module setup page + $this->family = "other"; + + // Module position in the family on 2 digits ('01', '10', '20', ...) + $this->module_position = '90'; + + // Gives the possibility for the module, to provide his own family info and position of this family (Overwrite $this->family and $this->module_position. Avoid this) + //$this->familyinfo = array('myownfamily' => array('position' => '01', 'label' => $langs->trans("MyOwnFamily"))); + // Module label (no space allowed), used if translation string 'ModuleQuickMemoName' not found (QuickMemo is name of module). + $this->name = preg_replace('/^mod/i', '', get_class($this)); + + // DESCRIPTION_FLAG + // Module description, used if translation string 'ModuleQuickMemoDesc' not found (QuickMemo is name of module). + $this->description = "QuickMemoDescription"; + // Used only if file README.md and README-LL.md not found. + $this->descriptionlong = "QuickMemoDescription"; + + // Author + $this->editor_squarred_logo = ''; // Must be image filename into the module/img directory followed with @modulename. Example: 'myimage.png@quickmemo' + + // Possible values for version are: 'development', 'experimental', 'dolibarr', 'dolibarr_deprecated', 'experimental_deprecated' or a version string like 'x.y.z' + $this->version = 'experimental'; + // Url to the file with your last numberversion of this module + //$this->url_last_version = 'http://www.example.com/versionmodule.txt'; + + // Key used in llx_const table to save module status enabled/disabled (where QUICKMEMO is value of property name of module in uppercase) + $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); + + // Name of image file used for this module. + // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue' + // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module' + // To use a supported fa-xxx css style of font awesome, use this->picto='xxx' + $this->picto = 'fa-sticky-note_far_#9bdb07'; + + // Define some features supported by module (triggers, login, substitutions, menus, css, etc...) + $this->module_parts = array( + // Set this to 1 if module has its own trigger directory (core/triggers) + 'triggers' => 0, + // Set this to 1 if module has its own login method file (core/login) + 'login' => 0, + // Set this to 1 if module has its own substitution function file (core/substitutions) + 'substitutions' => 0, + // Set this to 1 if module has its own menus handler directory (core/menus) + 'menus' => 0, + // Set this to 1 if module overwrite template dir (core/tpl) + 'tpl' => 0, + // Set this to 1 if module has its own barcode directory (core/modules/barcode) + 'barcode' => 0, + // Set this to 1 if module has its own models directory (core/modules/xxx) + 'models' => 0, + // Set this to 1 if module has its own printing directory (core/modules/printing) + 'printing' => 0, + // Set this to 1 if module has its own theme directory (theme) + 'theme' => 0, + // Set this to relative path of css file if module has its own css file + 'css' => array( + // '/quickmemo/css/quickmemo.css.php', + ), + // Set this to relative path of js file if module must load a js on all pages + 'js' => array( + // '/quickmemo/js/quickmemo.js.php', + ), + // Set here all hooks context managed by module. To find available hook context, make a "grep -r '>initHooks(' *" on source code. You can also set hook context to 'all' + + 'hooks' => array( + 'data' => array( + 'globalcard', + 'index', + ), + 'entity' => '0', + ), + + // Set this to 1 if features of module are opened to external users + 'moduleforexternal' => 0, + // Set this to 1 if the module provides a website template into doctemplates/websites/website_template-mytemplate + 'websitetemplates' => 0, + // Set this to 1 if the module provides a captcha driver + 'captcha' => 0 + ); + + // Data directories to create when module is enabled. + // Example: this->dirs = array("/quickmemo/temp","/quickmemo/subdir"); + $this->dirs = array(""); + + // Config pages. Put here list of php page, stored into quickmemo/admin directory, to use to setup module. + $this->config_page_url = array("setup.php@quickmemo"); + + // Dependencies + // A condition to hide module + $this->hidden = getDolGlobalInt('MODULE_QUICKMEMO_DISABLED'); // A condition to disable module; + // List of module class names that must be enabled if this module is enabled. Example: array('always'=>array('modModuleToEnable1','modModuleToEnable2'), 'FR'=>array('modModuleToEnableFR')...) + $this->depends = array(); + // List of module class names to disable if this one is disabled. Example: array('modModuleToDisable1', ...) + $this->requiredby = array(); + // List of module class names this module is in conflict with. Example: array('modModuleToDisable1', ...) + $this->conflictwith = array(); + + // The language file dedicated to your module + $this->langfiles = array("quickmemo@quickmemo"); + + // Prerequisites + $this->phpmin = array(7, 2); // Minimum version of PHP required by module + // $this->phpmax = array(8, 0); // Maximum version of PHP required by module + $this->need_dolibarr_version = array(19, -3); // Minimum version of Dolibarr required by module + // $this->max_dolibarr_version = array(19, -3); // Maximum version of Dolibarr required by module + $this->need_javascript_ajax = 0; + + // Messages at activation + $this->warnings_activation = array(); // Warning to show when we activate a module. Example: array('always'='text') or array('FR'='textfr','MX'='textmx'...) + $this->warnings_activation_ext = array(); // Warning to show when we activate a module if another module is on. Example: array('modOtherModule' => array('always'=>'text')) or array('always' => array('FR'=>'textfr','MX'=>'textmx'...)) + //$this->automatic_activation = array('FR'=>'QuickMemoWasAutomaticallyActivatedBecauseOfYourCountryChoice'); + //$this->always_enabled = false; // If true, can't be disabled. Value true is reserved for core modules. Not allowed for external modules. + + // Constants + // List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive) + // Example: $this->const=array(1 => array('QUICKMEMO_MYNEWCONST1', 'chaine', 'myvalue', 'This is a constant to add', 1), + // 2 => array('QUICKMEMO_MYNEWCONST2', 'chaine', 'myvalue', 'This is another constant to add', 0, 'current', 1) + // ); + $this->const = array(); + + // Some keys to add into the overwriting translation tables + /*$this->overwrite_translation = array( + 'en_US:ParentCompany'=>'Parent company or reseller', + 'fr_FR:ParentCompany'=>'Maison mère ou revendeur' + )*/ + + if (!isModEnabled("quickmemo")) { + $conf->quickmemo = new stdClass(); + $conf->quickmemo->enabled = 0; + } + + + // Array to add new pages in new tabs + /* BEGIN MODULEBUILDER TABS */ + // Don't forget to deactivate/reactivate your module to test your changes + $this->tabs = array(); + /* END MODULEBUILDER TABS */ + // Example: + // To add a new tab identified by code tabname1 + // $this->tabs[] = array('data' => 'objecttype:+tabname1:Title1:mylangfile@quickmemo:$user->hasRight('quickmemo', 'memo', 'read'):/quickmemo/mynewtab1.php?id=__ID__'); + // To add another new tab identified by code tabname2. Label will be result of calling all substitution functions on 'Title2' key. + // $this->tabs[] = array('data' => 'objecttype:+tabname2:SUBSTITUTION_Title2:mylangfile@quickmemo:$user->hasRight('othermodule', 'otherobject', 'read'):/quickmemo/mynewtab2.php?id=__ID__', + // To remove an existing tab identified by code tabname + // $this->tabs[] = array('data' => 'objecttype:-tabname:NU:conditiontoremove'); + // + // Where objecttype can be + // 'categories_x' to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member) + // 'contact' to add a tab in contact view + // 'contract' to add a tab in contract view + // 'delivery' to add a tab in delivery view + // 'group' to add a tab in group view + // 'intervention' to add a tab in intervention view + // 'invoice' to add a tab in customer invoice view + // 'supplier_invoice' to add a tab in supplier invoice view + // 'member' to add a tab in foundation member view + // 'opensurveypoll' to add a tab in opensurvey poll view + // 'order' to add a tab in sale order view + // 'supplier_order' to add a tab in supplier order view + // 'payment' to add a tab in payment view + // 'supplier_payment' to add a tab in supplier payment view + // 'product' to add a tab in product view + // 'propal' to add a tab in propal view + // 'project' to add a tab in project view + // 'stock' to add a tab in stock view + // 'thirdparty' to add a tab in third party view + // 'user' to add a tab in user view + + + // Dictionaries + /* Example: + $this->dictionaries=array( + 'langs' => 'quickmemo@quickmemo', + // List of tables we want to see into dictionary editor + 'tabname' => array("table1", "table2", "table3"), + // Label of tables + 'tablib' => array("Table1", "Table2", "Table3"), + // Request to select fields + 'tabsql' => array('SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.$this->db->prefix().'table1 as f', 'SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.$this->db->prefix().'table2 as f', 'SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.$this->db->prefix().'table3 as f'), + // Sort order + 'tabsqlsort' => array("label ASC", "label ASC", "label ASC"), + // List of fields (result of select to show dictionary) + 'tabfield' => array("code,label", "code,label", "code,label"), + // List of fields (list of fields to edit a record) + 'tabfieldvalue' => array("code,label", "code,label", "code,label"), + // List of fields (list of fields for insert) + 'tabfieldinsert' => array("code,label", "code,label", "code,label"), + // Name of columns with primary key (try to always name it 'rowid') + 'tabrowid' => array("rowid", "rowid", "rowid"), + // Condition to show each dictionary + 'tabcond' => array(isModEnabled('quickmemo'), isModEnabled('quickmemo'), isModEnabled('quickmemo')), + // Tooltip for every fields of dictionaries: DO NOT PUT AN EMPTY ARRAY + 'tabhelp' => array(array('code' => $langs->trans('CodeTooltipHelp'), 'field2' => 'field2tooltip'), array('code' => $langs->trans('CodeTooltipHelp'), 'field2' => 'field2tooltip'), ...), + ); + */ + /* BEGIN MODULEBUILDER DICTIONARIES */ + $this->dictionaries = array(); + /* END MODULEBUILDER DICTIONARIES */ + + // Boxes/Widgets + // Add here list of php file(s) stored in quickmemo/core/boxes that contains a class to show a widget. + /* BEGIN MODULEBUILDER WIDGETS */ + $this->boxes = array( + // 0 => array( + // 'file' => 'quickmemowidget1.php@quickmemo', + // 'note' => 'Widget provided by QuickMemo', + // 'enabledbydefaulton' => 'Home', + // ), + // ... + ); + /* END MODULEBUILDER WIDGETS */ + + // Cronjobs (List of cron jobs entries to add when module is enabled) + // unit_frequency must be 60 for minute, 3600 for hour, 86400 for day, 604800 for week + /* BEGIN MODULEBUILDER CRON */ + $this->cronjobs = array( + // 0 => array( + // 'label' => 'MyJob label', + // 'jobtype' => 'method', + // 'class' => '/quickmemo/class/memo.class.php', + // 'objectname' => 'Memo', + // 'method' => 'doScheduledJob', + // 'parameters' => '', + // 'comment' => 'Comment', + // 'frequency' => 2, + // 'unitfrequency' => 3600, + // 'status' => 0, + // 'test' => 'isModEnabled("quickmemo")', + // 'priority' => 50, + // ), + ); + /* END MODULEBUILDER CRON */ + // Example: $this->cronjobs=array( + // 0=>array('label'=>'My label', 'jobtype'=>'method', 'class'=>'/dir/class/file.class.php', 'objectname'=>'MyClass', 'method'=>'myMethod', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>'isModEnabled("quickmemo")', 'priority'=>50), + // 1=>array('label'=>'My label', 'jobtype'=>'command', 'command'=>'', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>1, 'unitfrequency'=>3600*24, 'status'=>0, 'test'=>'isModEnabled("quickmemo")', 'priority'=>50) + // ); + + // Permissions provided by this module + $this->rights = array(); + $r = 0; + // Add here entries to declare new permissions + + $o = 1; + $this->rights[$r][0] = $this->numero . sprintf("%02d", ($o * 10) + 1); // Permission id (must not be already used) + $this->rights[$r][1] = 'Read objects of QuickMemo'; // Permission label + $this->rights[$r][4] = 'memo'; + $this->rights[$r][5] = 'read'; // In php code, permission will be checked by test if ($user->hasRight('quickmemo', 'memo', 'read')) + $r++; + $this->rights[$r][0] = $this->numero . sprintf("%02d", ($o * 10) + 2); // Permission id (must not be already used) + $this->rights[$r][1] = 'Create/Update objects of QuickMemo'; // Permission label + $this->rights[$r][4] = 'memo'; + $this->rights[$r][5] = 'write'; // In php code, permission will be checked by test if ($user->hasRight('quickmemo', 'memo', 'write')) + $r++; + $this->rights[$r][0] = $this->numero . sprintf("%02d", ($o * 10) + 3); // Permission id (must not be already used) + $this->rights[$r][1] = 'Delete objects of QuickMemo'; // Permission label + $this->rights[$r][4] = 'memo'; + $this->rights[$r][5] = 'delete'; // In php code, permission will be checked by test if ($user->hasRight('quickmemo', 'memo', 'delete')) + $r++; + + + // Main menu entries to add + $this->menu = array(); + $r = 0; + // Add here entries to declare new menus + + $this->menu[$r++] = array( + 'fk_menu' => 'fk_mainmenu=tools', + 'type' => 'left', + 'titre' => 'Memo', + 'prefix' => img_picto('', $this->picto, 'class="paddingright pictofixedwidth valignmiddle"'), + 'mainmenu' => 'tools', + 'leftmenu' => 'memo', + 'url' => '/quickmemo/memo_list.php', + 'langs' => 'quickmemo', + 'position' => 1000 + $r, + 'enabled' => 'isModEnabled("quickmemo")', + 'perms' => '1', + 'target' => '', + 'user' => 2, + 'object' => 'Memo' + ); + $this->menu[$r++] = array( + 'fk_menu' => 'fk_mainmenu=tools,fk_leftmenu=memo', + 'type' => 'left', + 'titre' => 'List Memo', + 'mainmenu' => 'tools', + 'leftmenu' => 'quickmemo_memo_list', + 'url' => '/quickmemo/memo_list.php', + 'langs' => 'quickmemo', + 'position' => 1000 + $r, + 'enabled' => 'isModEnabled("quickmemo")', + 'perms' => '1', + 'target' => '', + 'user' => 2, + 'object' => 'Memo' + ); + } + + /** + * Function called when module is enabled. + * The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database. + * It also creates data directories + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int<-1,1> 1 if OK, <=0 if KO + */ + public function init($options = '') + { + + // Create tables of module at module activation + $result = $this->_load_tables('/install/mysql/', 'quickmemo'); + if ($result < 0) { + return -1; // Do not activate module if error 'not allowed' returned when loading module SQL queries (the _load_table run sql with run_sql with the error allowed parameter set to 'default') + } + + // Create extrafields during init + //include_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + //$extrafields = new ExtraFields($this->db); + //$result0=$extrafields->addExtraField('quickmemo_separator1', "Separator 1", 'separator', 1, 0, 'thirdparty', 0, 0, '', array('options'=>array(1=>1)), 1, '', 1, 0, '', '', 'quickmemo@quickmemo', 'isModEnabled("quickmemo")'); + //$result1=$extrafields->addExtraField('quickmemo_myattr1', "New Attr 1 label", 'boolean', 1, 3, 'thirdparty', 0, 0, '', '', 1, '', -1, 0, '', '', 'quickmemo@quickmemo', 'isModEnabled("quickmemo")'); + //$result2=$extrafields->addExtraField('quickmemo_myattr2', "New Attr 2 label", 'varchar', 1, 10, 'project', 0, 0, '', '', 1, '', -1, 0, '', '', 'quickmemo@quickmemo', 'isModEnabled("quickmemo")'); + //$result3=$extrafields->addExtraField('quickmemo_myattr3', "New Attr 3 label", 'varchar', 1, 10, 'bank_account', 0, 0, '', '', 1, '', -1, 0, '', '', 'quickmemo@quickmemo', 'isModEnabled("quickmemo")'); + //$result4=$extrafields->addExtraField('quickmemo_myattr4', "New Attr 4 label", 'select', 1, 3, 'thirdparty', 0, 1, '', array('options'=>array('code1'=>'Val1','code2'=>'Val2','code3'=>'Val3')), 1,'', -1, 0, '', '', 'quickmemo@quickmemo', 'isModEnabled("quickmemo")'); + //$result5=$extrafields->addExtraField('quickmemo_myattr5', "New Attr 5 label", 'text', 1, 10, 'user', 0, 0, '', '', 1, '', -1, 0, '', '', 'quickmemo@quickmemo', 'isModEnabled("quickmemo")'); + + // Permissions + $this->remove($options); + + $sql = array(); + + return $this->_init($sql, $options); + } + + /** + * Function called when module is disabled. + * Remove from database constants, boxes and permissions from Dolibarr database. + * Data directories are not deleted + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int<-1,1> 1 if OK, <=0 if KO + */ + public function remove($options = '') + { + $sql = array(); + return $this->_remove($sql, $options); + } +} diff --git a/htdocs/install/mysql/tables/llx_quickmemo_memo-quickmemo.key.sql b/htdocs/install/mysql/tables/llx_quickmemo_memo-quickmemo.key.sql new file mode 100644 index 00000000000..b9814a80e0d --- /dev/null +++ b/htdocs/install/mysql/tables/llx_quickmemo_memo-quickmemo.key.sql @@ -0,0 +1,19 @@ +-- Copyright (C) 2026 John BOTELLA +-- +-- 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 3 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, see https://www.gnu.org/licenses/. + + +ALTER TABLE llx_quickmemo_memo ADD INDEX idx_quickmemo_memo_rowid (rowid); +ALTER TABLE llx_quickmemo_memo ADD INDEX idx_quickmemo_memo_element (fk_element, element_type); +ALTER TABLE llx_quickmemo_memo ADD INDEX idx_quickmemo_memo_status (status); diff --git a/htdocs/install/mysql/tables/llx_quickmemo_memo-quickmemo.sql b/htdocs/install/mysql/tables/llx_quickmemo_memo-quickmemo.sql new file mode 100644 index 00000000000..117cdb30337 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_quickmemo_memo-quickmemo.sql @@ -0,0 +1,49 @@ +-- Copyright (C) 2026 John BOTELLA +-- +-- 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 3 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, see https://www.gnu.org/licenses/. + + +CREATE TABLE llx_quickmemo_memo( + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + entity integer DEFAULT 1 NOT NULL, + + fk_element integer NOT NULL, + element_type varchar(64) NOT NULL, + + quick_note text, + date_creation datetime NOT NULL, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + fk_user_creat integer NOT NULL, + fk_user_modif integer, + fk_user_archived integer, + date_archived timestamp DEFAULT NULL, + + import_key varchar(14), + + pos_z integer NOT NULL DEFAULT 0, + pos_y integer NOT NULL DEFAULT 0, + pos_x integer NOT NULL DEFAULT 0, + pos_w integer NOT NULL DEFAULT 0, + pos_h integer NOT NULL DEFAULT 0, + + color varchar(10), + + context_tab varchar(64), + private tinyint NOT NULL DEFAULT 1, + private_tpl tinyint NULL DEFAULT 0, + rank_tpl integer DEFAULT 0, + name_tpl varchar(256), + shared_on_element integer NOT NULL DEFAULT 0, + status integer NOT NULL DEFAULT 1 +) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_quickmemo_memo_extrafields-quickmemo.key.sql b/htdocs/install/mysql/tables/llx_quickmemo_memo_extrafields-quickmemo.key.sql new file mode 100644 index 00000000000..6b0d4017cdc --- /dev/null +++ b/htdocs/install/mysql/tables/llx_quickmemo_memo_extrafields-quickmemo.key.sql @@ -0,0 +1,19 @@ +-- Copyright (C) 2026 John BOTELLA +-- +-- 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 3 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, see https://www.gnu.org/licenses/. + + +-- BEGIN MODULEBUILDER INDEXES +ALTER TABLE llx_quickmemo_memo_extrafields ADD UNIQUE INDEX uk_memo_fk_object(fk_object); +-- END MODULEBUILDER INDEXES diff --git a/htdocs/install/mysql/tables/llx_quickmemo_memo_extrafields-quickmemo.sql b/htdocs/install/mysql/tables/llx_quickmemo_memo_extrafields-quickmemo.sql new file mode 100644 index 00000000000..d7d2d13ce62 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_quickmemo_memo_extrafields-quickmemo.sql @@ -0,0 +1,22 @@ +-- Copyright (C) 2026 John BOTELLA +-- +-- 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 3 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, see https://www.gnu.org/licenses/. + +create table llx_quickmemo_memo_extrafields +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + fk_object integer NOT NULL, + import_key varchar(14) -- import key +) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_quickmemo_memo_user-quickmemo.key.sql b/htdocs/install/mysql/tables/llx_quickmemo_memo_user-quickmemo.key.sql new file mode 100644 index 00000000000..5d5be03f766 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_quickmemo_memo_user-quickmemo.key.sql @@ -0,0 +1,17 @@ +-- Copyright (C) 2026 John BOTELLA +-- +-- 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 3 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, see https://www.gnu.org/licenses/. + +ALTER TABLE llx_quickmemo_memo_user ADD INDEX idx_quickmemo_memo_rowid (fk_memo); +ALTER TABLE llx_quickmemo_memo_user ADD UNIQUE KEY uk_memo_user (fk_memo, fk_user); diff --git a/htdocs/install/mysql/tables/llx_quickmemo_memo_user-quickmemo.sql b/htdocs/install/mysql/tables/llx_quickmemo_memo_user-quickmemo.sql new file mode 100644 index 00000000000..3a515bc8e2b --- /dev/null +++ b/htdocs/install/mysql/tables/llx_quickmemo_memo_user-quickmemo.sql @@ -0,0 +1,28 @@ +-- Copyright (C) 2026 John BOTELLA +-- +-- 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 3 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, see https://www.gnu.org/licenses/. + + +CREATE TABLE llx_quickmemo_memo_user( + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + fk_memo integer NOT NULL, + date_creation datetime NOT NULL, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + fk_user integer NOT NULL, + pos_z integer NOT NULL DEFAULT 0, + pos_y integer NOT NULL DEFAULT 0, + pos_x integer NOT NULL DEFAULT 0, + pos_w integer NOT NULL DEFAULT 0, + pos_h integer NOT NULL DEFAULT 0 +) ENGINE=innodb; diff --git a/htdocs/langs/en_US/quickmemo.lang b/htdocs/langs/en_US/quickmemo.lang new file mode 100644 index 00000000000..55565004ce6 --- /dev/null +++ b/htdocs/langs/en_US/quickmemo.lang @@ -0,0 +1,100 @@ +ModuleQuickMemoName = Quick Memo +ModuleQuickMemoDesc = Allows adding quick notes on documents +QuickMemoSetup = QuickMemo Setup +QUICKMEMO_COLORS_PRESET = Define your custom memo colors here +QuickMemoSetupPage = QuickMemo Configuration Page +QuickMemoAbout = About QuickMemo +QuickMemoAboutPage = QuickMemo Home Page +QuickMemoArea = QuickMemo Home +MyPageName = My Page Name +QuickMemoCreated = Created +QuickMemoModified = Modified +QuickMemoBy = by +QuickMemoEnterNote = Enter your memo +QuickMemoEnterNoteMdCompabible = Markdown style compatible +QuickMemoMd_Bold = Bold +QuickMemoMd_Italic = Italic +QuickMemoMd_Title = Title +QuickMemoMd_TaskNotDone = Task not done +QuickMemoMd_TaskDone = Task done +QuickMemoMd_List = List +QuickMemoMd_Link = Link +QuickMemoMd_LinkText = Link text +QuickMemoTemplateName = Template name + +QuickMemoActionArchive = Archive memo +QuickMemoActionDelete = Delete memo +QuickMemoActionDeleteEmpty = Delete empty memo +QuickMemoActionShareMode = Share mode +QuickMemoActionShareModeNotActive = Share mode is inactive +QuickMemoActionShareModeActive = Share mode is active +QuickMemoActionChangeColor = Change color + +QuickMemoActionPrivateMode = Public or private display mode +QuickMemoActionPrivateModeActive = Current display mode: Private +QuickMemoActionPrivateModeNotActive = Current display mode: Public + +QuickMemoSavePositionError = An error occurred while saving memo position +QuickMemoSaveError = An error occurred while saving the memo +QuickMemoLoadModelError = An error occurred while loading memo templates +QuickMemoCreateError = An error occurred while creating the memo +QuickMemoLoadMemosError = An error occurred while loading memos +QuickMemoArchiveError = An error occurred while archiving the memo +QuickMemoArchived = Archived +QuickMemoAdd = Add memo +QuickMemoSavedTemplate = Saved templates +QuickMemoColorsPresets = Preset colors +QuickMemoShowArchives = View archives +QuickMemoCantDeleteThisPrivateNote = You cannot delete this memo +QuickMemoCantArchiveThisPrivateNote = You cannot archive this memo +QuickMemoCantMoveThisPrivateNote = You cannot move this memo +QuickMemoCantChangeThisPrivateNote = You cannot edit this memo +MemoLinkedTo = Memo linked to +ContextTab = Context +ContextTab_card = Card +SharedBetweenElement = Shared memo +Archived = Archived +QuickMemoElementType = Element type +QuickMemoElementType_facture = Invoice +ArchivedBy = Archived by +DateArchived = Archive date +UnarchiveMemo = Retrieve memo +NoTemplatesFound = No templates available +QuickMemoCreateAModelFromThisMemo = Create template from this memo +QuickMemoAskCreateAModelFromThisMemo = Create a template from this memo? +QuickMemoAskLabelModelMemoIsCommon = Template shared for all element types +QuickMemoAskLabelModelMemoIsPrivate = Private template for my use only +PrivateTemplate = Private template +QuickMemoModelName = Template name +QuickMemoModelNamePlaceHolder = Ex: Todo list +QuickMemoConfirmDeleteModel = Are you sure you want to delete this memo template? +DialogAskConfirm = Confirmation +QuickMemoDeleteModel = Delete template +QuickMemoUnArchiveError = An error occurred while retrieving the memo +QuickMemoUnArchiveCount = %s memos retrieved +QuickMemoUnArchived = Recovered memo +QuickMemoMd_HelpIntro = Markdown is a simple system for formatting your notes without using the mouse. Simply add a few symbols around your text: +QuickMemoMd_SectionStyle = Formatting +QuickMemoMd_SectionTitles = Titles and Structure +QuickMemoMd_SectionTasks = Task lists +QuickMemoMd_SectionLinks = Internet links +QuickMemoMd_HelpFooter = Symbols are automatically transformed into visual styles as soon as you exit note editing. +QuickMemoMd_SectionUniversal = A universal standard +QuickMemoMd_UniversalDesc = It's a universal, non-proprietary format. It's the standard used for Wikipedia documentation, on GitLab, Mattermost and by the majority of Open Source projects worldwide, including Dolibarr. +QuickMemoDropDownTitle = Add a memo +QuickMemoHelp_Title = Master your memos with these expert shortcuts and tips +QuickMemoHelp_Visibility = Instant visibility +QuickMemoHelp_EscKey = Hold down the Esc key to temporarily hide all memos and read the content below. +QuickMemoHelp_Management = Model management +QuickMemoHelp_DeleteHover = To delete a model: hover your mouse over it to reveal the delete icon. +QuickMemoHelp_ShiftKeyDelete = Quick tip: Hold down the Shift key while deleting to skip the confirmation (ideal for quick cleanup). +QuickMemoHelp_Organization = Organization +QuickMemoHelp_DragDrop = Templates can be reordered. Click and drag to organize your list according to your priorities. +QuickMemoHelp_Footer = These functionalities respect ergonomic standards to offer you a fluid and productive interface. +ShowMemo = Show memo +NotEnoughRights = Not enough rights +Memo = Memo +Memos = Memos +UpdateError = Update error +QuickMemoCantDeleteThisPrivateModel = Can't delete this private model +PleaseSelectAtLeastOneRow = Please select at least one row diff --git a/htdocs/langs/fr_FR/quickmemo.lang b/htdocs/langs/fr_FR/quickmemo.lang new file mode 100644 index 00000000000..07d7d3de1a6 --- /dev/null +++ b/htdocs/langs/fr_FR/quickmemo.lang @@ -0,0 +1,95 @@ +# Translation file +ModuleQuickMemoName = Mémo rapide +ModuleQuickMemoDesc = Permettre l'ajout de notes rapides sur les documents +QuickMemoSetup = Configuration du QuickMemo +QuickMemoSetupPage = Page de configuration de QuickMemo +QuickMemoAbout = A propos de QuickMemo +QuickMemoAboutPage = Page d'accueil de QuickMemo +QuickMemoArea = Accueil QuickMemo +MyPageName = Nom de ma page +QuickMemoCreated = Créée +QuickMemoModified = Modifié +QuickMemoBy = par +QuickMemoEnterNote = Saisissez votre mémo +QuickMemoEnterNoteMdCompabible = Compatible Markdown +QuickMemoMd_Bold = Gras +QuickMemoMd_Italic = Italique +QuickMemoMd_Title = Titre +QuickMemoMd_TaskNotDone = Tâche à faire +QuickMemoMd_TaskDone = Tâche terminée +QuickMemoMd_List = Liste +QuickMemoMd_Link = Lien +QuickMemoMd_LinkText = Texte du lien +QuickMemoMd_HelpIntro = Le Markdown est un système simple pour mettre en forme vos notes sans utiliser la souris. Il suffit d'ajouter quelques symboles autour de votre texte : +QuickMemoMd_SectionStyle = Mise en forme +QuickMemoMd_SectionTitles = Titres et Structure +QuickMemoMd_SectionTasks = Listes de tâches +QuickMemoMd_SectionLinks = Liens internet +QuickMemoMd_HelpFooter = Les symboles se transforment automatiquement en style visuel dès que vous quittez l'édition de la note. +QuickMemoMd_SectionUniversal = Un standard universel +QuickMemoMd_UniversalDesc = C'est un format universel non-propriétaire. C'est le standard utilisé pour la documentation de Wikipédia, sur GitLab, Mattermost et par la majorité des projets Open Source à travers le monde dont Dolibarr. +QuickMemoTemplateName = Nom du modèle +QuickMemoDropDownTitle = Ajouter un mémo +QuickMemoActionArchive = Archiver le mémo +QuickMemoActionDelete = Supprimer le mémo +QuickMemoActionDeleteEmpty = Supprimer le mémo vide +QuickMemoActionShareMode = Mode partage +QuickMemoActionShareModeNotActive = Le mode partage est désactivé +QuickMemoActionShareModeActive = Le mode partage est actif +QuickMemoActionChangeColor = Changer de couleur + +QuickMemoHelp_Title = Maîtrisez vos mémos grâce à ces raccourcis et astuces d'expert +QuickMemoHelp_Visibility = Visibilité instantanée +QuickMemoHelp_EscKey = Maintenez la touche Échap pour masquer temporairement tous les mémos et lire le contenu situé en dessous. +QuickMemoHelp_Management = Gestion des modèles +QuickMemoHelp_DeleteHover = Pour supprimer un modèle : survolez-le quelques instants avec votre souris pour révéler l'icône de suppression. +QuickMemoHelp_ShiftKeyDelete = Astuce rapidité : Maintenez la touche MAJ lors de la suppression pour ignorer la confirmation (idéal pour le nettoyage rapide). +QuickMemoHelp_Organization = Organisation +QuickMemoHelp_DragDrop = Les modèles sont réordonnables. Cliquez et faites-les glisser pour organiser votre liste selon vos priorités. +QuickMemoHelp_Footer = Ces fonctionnalités respectent les standards d'ergonomie pour vous offrir une interface fluide et productive. + +QuickMemoActionPrivateMode = Mode d'affichage public ou privé +QuickMemoActionPrivateModeActive = Mode d'affichage en cours : Privé +QuickMemoActionPrivateModeNotActive = Mode d'affichage en cours : Public + +QuickMemoSavePositionError = Une erreur c'est produite lors de l'enregistrement de la position du mémo +QuickMemoSaveError = Une erreur c'est produite lors de l'enregistrement du mémo +QuickMemoLoadModelError = Une erreur c'est produite lors du chargement des models de mémos +QuickMemoCreateError = Une erreur c'est produite lors de la création du mémo +QuickMemoLoadMemosError = Une erreur c'est produite lors du chargement des mémos +QuickMemoArchiveError = Une erreur c'est produite lors de l'archivage du mémo +QuickMemoUnArchiveError = Une erreur c'est produite lors de la récupération du mémo +QuickMemoUnArchiveCount = %s mémos récupérés +QuickMemoUnArchived = Mémo récupéré +QuickMemoArchived = Archivé +QuickMemoAdd = Ajouter le mémo +QuickMemoSavedTemplate = Modèles enregistrés +QuickMemoColorsPresets = Couleurs prédéfinies +QuickMemoShowArchives = Consulter les archives +QuickMemoCantDeleteThisPrivateNote = Vous ne pouvez pas supprimer ce mémo +QuickMemoCantArchiveThisPrivateNote = Vous ne pouvez pas archiver ce mémo +QuickMemoCantMoveThisPrivateNote = Vous ne pouvez pas déplacer ce mémo +QuickMemoCantChangeThisPrivateNote = Vous ne pouvez pas modifier ce mémo +MemoLinkedTo = Memo lié à +ContextTab = Context +ContextTab_card = Fiche +SharedBetweenElement = Mémo partagé +Archived = Archivé +QuickMemoElementType = Type d'éléments +QuickMemoElementType_facture = Facture +ArchivedBy = Archivé par +DateArchived = Date archivage +UnarchiveMemo = Récupérer le mémo +NoTemplatesFound = Aucun modèle disponible +QuickMemoCreateAModelFromThisMemo = Créer modèle depuis ce mémo +QuickMemoAskCreateAModelFromThisMemo = Créer un modèle depuis cette mémo ? +QuickMemoAskLabelModelMemoIsCommon = Modèle commun à tous les types d'élément +QuickMemoAskLabelModelMemoIsPrivate = Modèle privé utilisable uniquement par moi +PrivateTemplate = Modèle privé +QuickMemoModelName = Nom du modèle +QuickMemoModelNamePlaceHolder = Ex: Todo list +QuickMemoConfirmDeleteModel = Souhaitez-vous vraiment supprimer ce modèle de mémo ? +DialogAskConfirm = Confirmation +QuickMemoDeleteModel = Supprimer le modèle +ShowMemo = Consulter le mémo +QUICKMEMO_COLORS_PRESET=Définissez ici vos couleurs de mémo personnalisées diff --git a/htdocs/quickmemo/admin/memo_extrafields.php b/htdocs/quickmemo/admin/memo_extrafields.php new file mode 100644 index 00000000000..d2594a1227b --- /dev/null +++ b/htdocs/quickmemo/admin/memo_extrafields.php @@ -0,0 +1,128 @@ + + * Copyright (C) 2003 Jean-Louis Bergamo + * Copyright (C) 2004-2011 Laurent Destailleur + * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2014 Florian Henry + * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2024 Frédéric France + * + * 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 3 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, see . + */ + +/** + * \file admin/memo_extrafields.php + * \ingroup quickmemo + * \brief Page to setup extra fields of memo + */ + + +// Load Dolibarr environment +require '../../main.inc.php'; + +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; +require_once '../lib/quickmemo.lib.php'; + +/** + * @var Conf $conf + * @var DoliDB $db + * @var HookManager $hookmanager + * @var Translate $langs + * @var User $user + */ + +// Load translation files required by the page +$langs->loadLangs(array('quickmemo', 'admin')); + +$extrafields = new ExtraFields($db); +$form = new Form($db); + +// List of supported format +$type2label = ExtraFields::getListOfTypesLabels(); + +$action = GETPOST('action', 'aZ09'); +$attrname = GETPOST('attrname', 'alpha'); +$elementtype = 'quickmemo_memo'; //Must be the $table_element of the class that manage extrafield + +if (!$user->admin) { + accessforbidden(); +} + + +/* + * Actions + */ + +require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; + + + +/* + * View + */ + +$textobject = $langs->transnoentitiesnoconv("Memo"); + +$help_url = ''; +$page_name = "QuickMemoSetup"; + +llxHeader('', $langs->trans("QuickMemoSetup"), $help_url, '', 0, 0, '', '', '', 'mod-quickmemo page-admin_extrafields'); + + +$linkback = ''.img_picto($langs->trans("BackToModuleList"), 'back', 'class="pictofixedwidth"').''.$langs->trans("BackToModuleList").''; +print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup'); + + +$head = quickmemoAdminPrepareHead(); + +print dol_get_fiche_head($head, 'memo_extrafields', $langs->trans($page_name), -1, 'quickmemo@quickmemo'); + +require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; + +print dol_get_fiche_end(); + + +// Buttons +if ((float) DOL_VERSION < 17) { // On v17+, the "New Attribute" button is included into tpl. @phpstan-ignore-line + if ($action != 'create' && $action != 'edit') { + print '
'; + print ''.$langs->trans("NewAttribute").''; + print "
"; + } +} + + +/* + * Creation of an optional field + */ +if ($action == 'create') { + print '
'; + print load_fiche_titre($langs->trans('NewAttribute')); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php'; +} + +/* + * Edition of an optional field + */ +if ($action == 'edit' && !empty($attrname)) { + print "
"; + print load_fiche_titre($langs->trans("FieldEdition", $attrname)); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php'; +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/quickmemo/admin/setup.php b/htdocs/quickmemo/admin/setup.php new file mode 100644 index 00000000000..bcd784e808c --- /dev/null +++ b/htdocs/quickmemo/admin/setup.php @@ -0,0 +1,287 @@ + + * Copyright (C) 2024 Frédéric France + * Copyright (C) 2026 John BOTELLA + * + * 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 3 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, see . + */ + +/** + * \file quickmemo/admin/setup.php + * \ingroup quickmemo + * \brief QuickMemo setup page. + */ + + +// Load Dolibarr environment +require '../../main.inc.php'; + +// Libraries +require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php"; +require_once __DIR__ . '/../lib/quickmemo.lib.php'; +require_once __DIR__ . '/../class/memo.class.php'; +//require_once "../class/myclass.class.php"; + +/** + * @var Conf $conf + * @var DoliDB $db + * @var HookManager $hookmanager + * @var Translate $langs + * @var User $user + */ + +// Translations +$langs->loadLangs(array("admin", "quickmemo")); + +// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context +/** @var HookManager $hookmanager */ +$hookmanager->initHooks(array('quickmemosetup', 'globalsetup')); + +// Parameters +$action = GETPOST('action', 'aZ09'); +$backtopage = GETPOST('backtopage', 'alpha'); +$modulepart = GETPOST('modulepart', 'aZ09'); // Used by actions_setmoduleoptions.inc.php + +$value = GETPOST('value', 'alpha'); +$label = GETPOST('label', 'alpha'); +$scandir = GETPOST('scan_dir', 'alpha'); +$type = 'myobject'; + +$error = 0; +$setupnotempty = 0; + +// Access control +if (!$user->admin) { + accessforbidden(); +} + + +// Set this to 1 to use the factory to manage constants. Warning, the generated module will be compatible with version v15+ only +$useFormSetup = 1; + +if (!class_exists('FormSetup')) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsetup.class.php'; +} +$formSetup = new FormSetup($db); + +$item = $formSetup->newItem('QUICKMEMO_COLORS_PRESET'); +$item->fieldInputOverride = ' +
+
+ + + + +
+ +
+ +
+ + +
'; + +$setupnotempty += count($formSetup->items); + + + +/* + * Actions + */ + +// For retrocompatibility Dolibarr < 15.0 +if (versioncompare(explode('.', DOL_VERSION), array(15)) < 0 && $action == 'update' && !empty($user->admin)) { + $formSetup->saveConfFromPost(); +} + +include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; + + +if (empty($action)) { + $action = 'edit'; +} + + +/* + * View + */ + +$form = new Form($db); + +$help_url = ''; +$title = "QuickMemoSetup"; + +llxHeader('', $langs->trans($title), $help_url, '', 0, 0, '', ['quickmemo/css/setup.css'], '', 'mod-quickmemo page-admin'); + + + + +if ($action == 'edit') : ?> + +'.img_picto($langs->trans("BackToModuleList"), 'back', 'class="pictofixedwidth"').''.$langs->trans("BackToModuleList").''; + +print load_fiche_titre($langs->trans($title), $linkback, 'title_setup'); + +// Configuration header +$head = quickmemoAdminPrepareHead(); +print dol_get_fiche_head($head, 'settings', $langs->trans($title), -1, "quickmemo@quickmemo"); + +// Setup page goes here +echo ''.$langs->trans("QuickMemoSetupPage").'

'; + + +if (!empty($formSetup->items)) { + print $formSetup->generateOutput(true); + print '
'; +} + + + +if (empty($setupnotempty)) { + print '
'.$langs->trans("NothingToSetup"); +} + +// Page end +print dol_get_fiche_end(); + +llxFooter(); +$db->close(); diff --git a/htdocs/quickmemo/class/actions_quickmemo.class.php b/htdocs/quickmemo/class/actions_quickmemo.class.php new file mode 100644 index 00000000000..050d94295ea --- /dev/null +++ b/htdocs/quickmemo/class/actions_quickmemo.class.php @@ -0,0 +1,138 @@ + + * Copyright (C) 2026 John BOTELLA + * + * 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 3 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, see . + */ + +/** + * \file quickmemo/class/actions_quickmemo.class.php + * \ingroup quickmemo + * \brief Example hook overload. + * + */ + +require_once DOL_DOCUMENT_ROOT.'/core/class/commonhookactions.class.php'; + +require_once __DIR__ . '/memo.class.php'; + + +/** + * Class ActionsQuickMemo + */ +class ActionsQuickMemo extends CommonHookActions +{ + /** + * @var DoliDB Database handler. + */ + public $db; + + /** + * @var string Error code (or message) + */ + public $error = ''; + + /** + * @var string[] Errors + */ + public $errors = array(); + + + /** + * @var mixed[] Hook results. Propagated to $hookmanager->resArray for later reuse + */ + public $results = array(); + + /** + * @var ?string String displayed by executeHook() immediately after return + */ + public $resprints; + + /** + * @var int Priority of hook (50 is used if value is not defined) + */ + public $priority; + + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } + + /** + * Overload the llxFooter function : add or replace array of object linkable + * + * @param array $parameters Hook metadata (context, etc...) + * @param CommonObject $object The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...) + * @param ?string $action Current action (if set). Generally create or edit or null + * @param HookManager $hookmanager Hook manager propagated to allow calling another hook + * @return int Return integer < 0 on error, 0 on success, 1 to replace standard code + */ + public function llxFooter($parameters, &$object, &$action, $hookmanager) + { + + $context = Memo::getMemoContext($parameters['context']??''); + if (empty($context)) { return 0; } + + $jsConfVars = [ + 'context' => $context, + ]; + + if (!empty($object) && is_object($object) && isset($object->element)) { + $jsConfVars = array_merge([ + 'archivesUrlParams' => '&search_fk_element='. (int) $object->id .'&search_element_type='.$object->element, + 'elementId' => (int) $object->id, + 'elementType' => $object->element + ], $jsConfVars); + } + + Memo::loadQuickMemoJsInterface($jsConfVars); + + return 0; + } + + + /** + * Overload the addHtmlHeader function : add or replace array of object linkable + * + * @param array $parameters Hook metadata (context, etc...) + * @param CommonObject $object The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...) + * @param ?string $action Current action (if set). Generally create or edit or null + * @param HookManager $hookmanager Hook manager propagated to allow calling another hook + * @return int Return integer < 0 on error, 0 on success, 1 to replace standard code + */ + public function addMoreActionsButtons($parameters, &$object, &$action, $hookmanager) + { + + if (empty($object) || !is_object($object) || !isset($object->element)) { + return 0; + } + + $jsConfVars = [ + 'archivesUrlParams' => '&search_fk_element='. (int) $object->id .'&search_element_type='.$object->element, + 'elementId' => (int) $object->id, + 'elementType' => $object->element, + 'context' => Memo::getMemoContext($parameters['context']??''), + ]; + + Memo::loadQuickMemoJsInterface($jsConfVars); + + return 0; + } +} diff --git a/htdocs/quickmemo/class/memo.class.php b/htdocs/quickmemo/class/memo.class.php new file mode 100644 index 00000000000..8ea92d08041 --- /dev/null +++ b/htdocs/quickmemo/class/memo.class.php @@ -0,0 +1,1612 @@ + + * Copyright (C) 2023-2025 Frédéric France + * Copyright (C) 2026 John BOTELLA + * + * 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 3 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, see . + */ + +/** + * \file class/memo.class.php + * \ingroup quickmemo + * \brief This file is a CRUD class file for Memo (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + +/** + * Class for Memo + */ +class Memo extends CommonObject +{ + /** + * @var string ID of module. + */ + public $module = 'quickmemo'; + + /** + * @var string ID to identify managed object. + */ + public $element = 'memo'; + + /** + * @var string Prefix to check for any trigger code of any business class to prevent bad value for trigger code. + * @see CommonTrigger::call_trigger() + */ + public $TRIGGER_PREFIX = 'QUICKMEMO_MEMO'; // Will be used to build trgiger keys 'QUICKMEMO_MEMO_MODIFY', ... + + /** + * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management (so extrafields know the link to the parent table). + */ + public $table_element = 'quickmemo_memo'; + + /** + * @var string If permission must be checked with hasRight('quickmemo', 'read') and not hasright('quickmemo', 'memo', 'read'), you can uncomment this line + */ + //public $element_for_permission = 'quickmemo'; + + /** + * @var string String with name of icon for memo. Must be a 'fa-xxx' fontawesome code (or 'fa-xxx_fa_color_size') or 'memo@quickmemo' if picto is file 'img/object_memo.png'. + */ + public $picto = 'fa-file'; + + /** + * @var int<0,1> Does object support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 0; + + /** + * @var int<0,1>|string Does this object support multicompany module ? + * 0=No test on entity, 1=Test with field entity in local table, 'field@table'=Test entity into the field@table (example 'fk_soc@societe') + */ + public $ismultientitymanaged = 0; + + + + const STATUS_TPL = 2; + const STATUS_VALIDATED = 1; + const STATUS_CANCELED = 9; // fall back in case of + const STATUS_ARCHIVED = 9; + + /** + * 'type' field format: + * 'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]', + * 'select' (list of values are in 'options'. for integer list of values are in 'arrayofkeyval'), + * 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:CategoryIdType[:CategoryIdList[:SortField]]]]]]', + * 'chkbxlst:...', + * 'varchar(x)', + * 'text', 'text:none', 'html', + * 'double(24,8)', 'real', 'price', 'stock', + * 'date', 'datetime', 'timestamp', 'duration', + * 'boolean', 'checkbox', 'radio', 'array', + * 'email', 'phone', 'url', 'password', 'ip' + * Note: Filter must be a Dolibarr Universal Filter syntax string. Example: "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.status:!=:0) or (t.nature:is:NULL)" + * 'length' the length of field. Example: 255, '24,8' + * 'label' the translation key. + * 'langfile' the key of the language file for translation. + * 'alias' the alias used into some old hard coded SQL requests + * 'picto' is code of a picto to show before value in forms + * 'enabled' is a condition when the field must be managed (Example: 1 or 'getDolGlobalInt("MY_SETUP_PARAM")' or 'isModEnabled("multicurrency")' ...) + * 'position' is the sort order of field. + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form (not create). 5=Visible on list and view form (not create/not update). 6=visible on list and update/view form (not update). Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'noteditable' says if field is not editable (1 or 0) + * 'alwayseditable' says if field can be modified also when status is not draft ('1' or '0') + * 'default' is a default value for creation (can still be overwritten by the Setup of Default Values if the field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created. + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...). + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage) + * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200' + * 'placeholder' to set the placeholder of a varchar field. + * 'help' and 'helplist' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click. + * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record + * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code like the constructor of the class. + * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar' + * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1. + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * 'validate' is 1 if you need to validate the field with $this->validateField(). Need MAIN_ACTIVATE_VALIDATION_RESULT. + * 'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value) + * + * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor. + */ + + /** + * @inheritdoc + * Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields = array( + "rowid" => array("type" => "integer", "label" => "TechnicalID", 'enabled' => 1, 'position' => 1, 'notnull' => 1, "visible" => 0, 'noteditable' => 1, 'index' => 1, "css" => "left", "comment" => "Id"), + "quick_note" => array("type" => "text", "label" => "Note", 'enabled' => 1, 'position' => 61, 'notnull' => 0, "visible" => -1, "cssview" => "wordbreak", "validate" => 1,), + "date_creation" => array("type" => "datetime", "label" => "DateCreation", 'enabled' => 1, 'position' => 500, 'notnull' => 1, "visible" => -2,), + "tms" => array("type" => "timestamp", "label" => "DateModification", 'enabled' => 1, 'position' => 501, 'notnull' => 0, "visible" => -2,), + "date_archived" => array("type" => "timestamp", "label" => "DateArchived", 'enabled' => 1, 'position' => 502, 'notnull' => 0, "visible" => -2,), + "fk_user_creat" => array("type" => "integer:User:user/class/user.class.php", "label" => "UserAuthor", "picto" => "user", 'enabled' => 1, 'position' => 510, 'notnull' => 1, "visible" => -2, "csslist" => "tdoverflowmax150",), + "fk_user_modif" => array("type" => "integer:User:user/class/user.class.php", "label" => "UserModif", "picto" => "user", 'enabled' => 1, 'position' => 511, 'notnull' => -1, "visible" => -2, "csslist" => "tdoverflowmax150",), + "fk_user_archived" => array("type" => "integer:User:user/class/user.class.php", "label" => "ArchivedBy", "picto" => "user", 'enabled' => 1, 'position' => 511, 'notnull' => -1, "visible" => -2, "csslist" => "tdoverflowmax150",), + "fk_element" => array('type' => 'integer','label' => 'MemoLinkedTo','help' => 'MemoLinkedToHelp','enabled' => 1,'visible' => 5,'notnull' => 0,'default' => 0,'index' => 1,'position' => 0), + "element_type" => array('type' => 'varchar(64)','label' => 'QuickMemoElementType','enabled' => 1,'visible' => 5,'position' => 10,'required' => 0), + "pos_z" => array("type" => "integer", "label" => "PosZ", 'enabled' => 1, 'position' => 1000, 'notnull' => 1, "visible" => 0, "default" => 0, "validate" => 1), + "pos_y" => array("type" => "integer", "label" => "PosY", 'enabled' => 1, 'position' => 1000, 'notnull' => 1, "visible" => 0, "default" => 0, "validate" => 1), + "pos_x" => array("type" => "integer", "label" => "PosX", 'enabled' => 1, 'position' => 1000, 'notnull' => 1, "visible" => 0, "default" => 0, "validate" => 1), + "pos_w" => array("type" => "integer", "label" => "PosW", 'enabled' => 1, 'position' => 1000, 'notnull' => 1, "visible" => 0, "default" => 0, "validate" => 1), + "pos_h" => array("type" => "integer", "label" => "PosH", 'enabled' => 1, 'position' => 1000, 'notnull' => 1, "visible" => 0, "default" => 0, "validate" => 1), + "color" => array('type' => 'varchar(10)', 'label' => 'Color','enabled' => 1,'visible' => 1,'position' => 10,'required' => 0), + "context_tab" => array('type' => 'varchar(64)', 'label' => 'ContextTab','enabled' => 1,'visible' => 1,'position' => 10,'required' => 0), + "private" => array("type" => "integer", "label" => "Private", 'enabled' => 1, 'position' => 1990, 'notnull' => 1, "visible" => 1, 'index' => 1, "arrayofkeyval" => array(0 => "No", 1 => "Yes"),'default' => 1, "validate" => 1,), + "private_tpl" => array("type" => "integer", "label" => "PrivateTemplate", 'enabled' => 1, 'position' => 1990, 'notnull' => 0, "visible" => 1, 'index' => 1, "arrayofkeyval" => array(0 => "No", 1 => "Yes"),'default' => 0, "validate" => 1,), + "rank_tpl" => array("type" => "integer", "label" => "TemplateRank", 'enabled' => 1, 'position' => 1990, 'notnull' => 0, "visible" => 0, 'index' => 1,'default' => 0, "validate" => 1,), + "name_tpl" => array('type' => 'varchar(256)','label' => 'QuickMemoTemplateName','enabled' => 1,'visible' => -1,'position' => 1,'required' => 0), + "shared_on_element" => array("type" => "integer", "label" => "SharedBetweenElement", 'enabled' => 1, 'position' => 1991, 'notnull' => 1, "visible" => 1, 'index' => 1, "arrayofkeyval" => array(0 => "No", 1 => "Yes"), "validate" => 1,), + "import_key" => array("type" => "varchar(14)", "label" => "ImportId", 'enabled' => 1, 'position' => 1000, 'notnull' => -1, "visible" => -2,), + "status" => array("type" => "integer", "label" => "Status", 'enabled' => 1, 'position' => 2000, 'notnull' => 1, "visible" => 1, 'index' => 1, "arrayofkeyval" => array(1 => "Active",2 => "Template", 9 => "Archived"), "validate" => 1,), + ); + + /** @var int|null */ + public $rowid; + + /** @var int|null */ + public $date_archived; + + /** @var int|null */ + public $fk_user_archived; + + /** @var string|null */ + public $quick_note; + + /** @var int|string|null */ + public $date_creat; + + /** + * @var string|int Field with ID of parent key if this field has a parent (a string). For example 'fk_product'. + * ID of parent key itself (an int). For example in few classes like 'Comment', 'ActionComm' or 'AdvanceTargetingMailing'. + */ + public $fk_element; + + /** @var string|null */ + public $element_type; + + /** @var int|string|null */ + public $pos_z; + + /** @var int|string|null */ + public $pos_y; + + /** @var int|string|null */ + public $pos_x; + + /** @var int|string|null */ + public $pos_w; + + /** @var int|string|null */ + public $pos_h; + + /** @var int|string|null */ + public $color; + + /** @var string|null */ + public $context_tab; + + /** @var string|null */ + public $import_key; + + /** + * @var null|int|array The object's status (an int). + * Or an array listing all the potential status of the object: + * array: int of the status => translated label of the status + * In some classes status must be able to be null. + * See for example the Account class. + * @see setStatut() + */ + public $status; + + /** @var int|string|null */ + public $private; + + /** @var int|string|null */ + public $private_tpl; + + /** @var string|null */ + public $name_tpl; + + /** @var int|string|null */ + public $shared_on_element; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct(DoliDB $db) + { + global $langs; + + $this->db = $db; + + if (!getDolGlobalInt('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid']) && !empty($this->fields['ref'])) { + $this->fields['rowid']['visible'] = 0; + } + if (!isModEnabled('multicompany') && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } + + // Unset fields that are disabled + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { + unset($this->fields[$key]); + } + } + + // Translate some data of arrayofkeyval + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { + $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); + } + } + } + } + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param int<0,1> $notrigger 0=launch triggers after, 1=disable triggers + * @return int<-1,max> Return integer <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = 0) + { + $result = $this->createCommon($user, $notrigger); + + return $result; + } + + /** + * Clone an object into another one + * + * @param User $user User that creates + * @param int $fromid Id of object to clone + * @return self|int<-1,-1> New object created, <0 if KO + */ + public function createFromClone(User $user, $fromid) + { + global $langs, $extrafields; + $error = 0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + $this->db->begin(); + + // Load source object + $result = $object->fetchCommon($fromid); + if ($result > 0 && !empty($object->table_element_line)) { + $object->fetchLines(); + } + + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); + + + $object->status = self::STATUS_VALIDATED; + + $object->date_creation = dol_now(); + + $object->date_modification = null; + + // ... + // Clear extrafields that are unique + if (is_array($object->array_options) && count($object->array_options) > 0) { + $extrafields->fetch_name_optionals_label($this->table_element); + foreach ($object->array_options as $key => $option) { + $shortkey = preg_replace('/options_/', '', $key); + if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) { + //var_dump($key); + //var_dump($clonedObj->array_options[$key]); exit; + unset($object->array_options[$key]); + } + } + } + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->createCommon($user); + if ($result < 0) { + $error++; + $this->setErrorsFromObject($object); + } + + unset($object->context['createfromclone']); + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @param int<0,1> $noextrafields 0=Default to load extrafields, 1=No extrafields + * @param int<0,1> $nolines 0=Default to load lines, 1=No lines + * @return int<-1,1> Return integer <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null, $noextrafields = 0, $nolines = 0) + { + $result = $this->fetchCommon($id, $ref, '', $noextrafields); + if ($result > 0 && !empty($this->table_element_line) && empty($nolines)) { + $this->fetchLines($noextrafields); + } + return $result; + } + + /** + * Load object lines in memory from the database + * + * @param int<0,1> $noextrafields 0=Default to load extrafields, 1=No extrafields + * @return int<-1,1> Return integer <0 if KO, 0 if not found, >0 if OK + */ + public function fetchLines($noextrafields = 0) + { + $this->lines = array(); + + $result = $this->fetchLinesCommon('', $noextrafields); + return $result; + } + + + /** + * Load list of objects in memory from the database. + * Using a fetchAll() with limit = 0 is a very bad practice. Instead try to forge yourself an optimized SQL request with + * your own loop with start and stop pagination. + * + * @param string $sortorder Sort Order + * @param string $sortfield Sort field + * @param int<0,max> $limit Limit the number of lines returned + * @param int<0,max> $offset Offset + * @param string $filter Filter as an Universal Search string. + * Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')' + * @param string $filtermode No longer used + * @return array|int<-1,-1> <0 if KO, array of pages if OK + */ + public function fetchAll($sortorder = '', $sortfield = '', $limit = 1000, $offset = 0, string $filter = '', $filtermode = 'AND') + { + dol_syslog(__METHOD__, LOG_DEBUG); + + $records = array(); + + $sql = "SELECT "; + $sql .= $this->getFieldList('t'); + $sql .= " FROM ".$this->db->prefix().$this->table_element." as t"; + if (!empty($this->isextrafieldmanaged) && $this->isextrafieldmanaged == 1) { + $sql .= " LEFT JOIN ".$this->db->prefix().$this->table_element."_extrafields as te ON te.fk_object = t.rowid"; + } + if (!empty($this->ismultientitymanaged) && (int) $this->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($this->element).")"; + } elseif (preg_match('/^\w+@\w+$/', (string) $this->ismultientitymanaged)) { + $tmparray = explode('@', (string) $this->ismultientitymanaged); + $sql .= " LEFT JOIN ".$this->db->prefix().$tmparray[1]." as pt ON t.".$this->db->sanitize($tmparray[0])." = pt.rowid"; + $sql .= " WHERE pt.entity IN (".getEntity($this->element).")"; + } else { + $sql .= " WHERE 1 = 1"; + } + + // Manage filter + $errormessage = ''; + $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage); + if ($errormessage) { + $this->errors[] = $errormessage; + dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR); + return -1; + } + + if (!empty($sortfield)) { + $sql .= $this->db->order($sortfield, $sortorder); + } + if (!empty($limit)) { + $sql .= $this->db->plimit($limit, $offset); + } + + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < ($limit ? min($limit, $num) : $num)) { + $obj = $this->db->fetch_object($resql); + + $record = new self($this->db); + $record->setVarsFromFetchObj($obj); + + if (!empty($record->isextrafieldmanaged)) { + $record->fetch_optionals(); + } + + $records[$record->id] = $record; + + $i++; + } + $this->db->free($resql); + + return $records; + } else { + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR); + + return -1; + } + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param int<0,1> $notrigger 0=launch triggers after, 1=disable triggers + * @return int<-1,1> Return integer <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = 0) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Update position of a memo for a specific user + * + * @param User $user Dolibarr user + * @param int $x Position X + * @param int $y Position Y + * @param int $w Width + * @param int $h Height + * @param int $z Z-index (rank) + * + * @return bool True if success, false if error + */ + public function updatePosition(User $user, int $x, int $y, int $w, int $h, int $z) + { + if (empty($this->id)) { + return false; + } + + $x = (int) $x; + $y = (int) $y; + $w = (int) $w; + $h = (int) $h; + $z = (int) $z; + + // CREATEUR + if ((int) $this->fk_user_creat === (int) $user->id) { + $this->pos_x = $x; + $this->pos_y = $y; + $this->pos_w = $w; + $this->pos_h = $h; + $this->pos_z = $z; + + if ($this->update($user) <= 0) { + return false; + } + + return true; + } + + // USER NOT CREATOR + + $sql = 'SELECT rowid'; + $sql .= ' FROM '.$this->db->prefix().'quickmemo_memo_user'; + $sql .= ' WHERE fk_memo = '.((int) $this->id); + $sql .= ' AND fk_user = '.((int) $user->id); + + $resql = $this->db->query($sql); + if (!$resql) { + return false; + } + + if ($this->db->num_rows($resql) > 0) { + // UPDATE + $sql = 'UPDATE '.$this->db->prefix().'quickmemo_memo_user SET'; + $sql .= ' pos_x = '. (int) $x.','; + $sql .= ' pos_y = '. (int) $y.','; + $sql .= ' pos_w = '. (int) $w.','; + $sql .= ' pos_h = '. (int) $h.','; + $sql .= ' pos_z = '. (int) $z; + $sql .= ' WHERE fk_memo = '.((int) $this->id); + $sql .= ' AND fk_user = '.((int) $user->id); + + if (!$this->db->query($sql)) { + return false; + } + } else { + // INSERT + $sql = 'INSERT INTO '.$this->db->prefix().'quickmemo_memo_user ('; + $sql .= 'fk_memo,'; + $sql .= 'fk_user,'; + $sql .= 'date_creation,'; + $sql .= 'pos_x,'; + $sql .= 'pos_y,'; + $sql .= 'pos_w,'; + $sql .= 'pos_h,'; + $sql .= 'pos_z'; + $sql .= ') VALUES ('; + $sql .= ((int) $this->id).','; + $sql .= ((int) $user->id).','; + $sql .= '\''. $this->db->idate(dol_now()) .'\','; + $sql .= (int) $x.','; + $sql .= (int) $y.','; + $sql .= (int) $w.','; + $sql .= (int) $h.','; + $sql .= (int) $z; + $sql .= ')'; + + if (!$this->db->query($sql)) { + return false; + } + } + + return true; + } + + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param int<0,1> $notrigger 0=launch triggers, 1=disable triggers + * @return int<-1,1> Return integer <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = 0) + { + return $this->deleteCommon($user, $notrigger); + //return $this->deleteCommon($user, $notrigger, 1); + } + + /** + * Delete a line of object in database + * + * @param User $user User that deletes + * @param int $idline Id of line to delete + * @param int<0,1> $notrigger 0=launch triggers after, 1=disable triggers + * @return int<-2,1> >0 if OK, <0 if KO + */ + public function deleteLine(User $user, $idline, $notrigger = 0) + { + if ($this->status < 0) { + $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; + return -2; + } + + return $this->deleteLineCommon($user, $idline, $notrigger); + } + + + /** + * Validate object + * + * @param User $user User making status change + * @param int<0,1> $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int<-1,1> Return integer <=0 if OK, 0=Nothing done, >0 if KO + */ + public function validate($user, $notrigger = 0) + { + global $conf; + + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + $error = 0; + + // Protection + if ($this->status == self::STATUS_VALIDATED) { + dol_syslog(get_class($this)."::validate action abandoned: already validated", LOG_WARNING); + return 0; + } + + /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo', 'memo', 'write')) + || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo', 'memo_advance', 'validate'))) + { + $this->error='NotEnoughPermissions'; + dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); + return -1; + }*/ + + $now = dol_now(); + + $this->db->begin(); + + // Define new ref + if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life + $num = $this->getNextNumRef(); + } else { + $num = (string) $this->ref; + } + $this->newref = $num; + + if (!empty($num)) { + // Validate + $sql = "UPDATE ".$this->db->prefix().$this->table_element; + $sql .= " SET "; + if (!empty($this->fields['ref'])) { + $sql .= " ref = '".$this->db->escape($num)."',"; + } + $sql .= " status = ".self::STATUS_VALIDATED; + if (!empty($this->fields['date_validation'])) { + $sql .= ", date_validation = '".$this->db->idate($now)."'"; + } + if (!empty($this->fields['fk_user_valid'])) { + $sql .= ", fk_user_valid = ".((int) $user->id); + } + $sql .= " WHERE rowid = ".((int) $this->id); + + dol_syslog(get_class($this)."::validate()", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + dol_print_error($this->db); + $this->error = $this->db->lasterror(); + $error++; + } + + if (!$error && !$notrigger) { + // Call trigger + $result = $this->call_trigger('MEMO_VALIDATE', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } + } + + if (!$error) { + $this->oldref = $this->ref; + + // Rename directory if dir was a temporary ref + if (preg_match('/^[\(]?PROV/i', $this->ref)) { + // Now we rename also files into index + $sql = 'UPDATE '.$this->db->prefix()."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'memo/".$this->db->escape($this->newref)."'"; + $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'memo/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->error = $this->db->lasterror(); + } + $sql = 'UPDATE '.$this->db->prefix()."ecm_files set filepath = 'memo/".$this->db->escape($this->newref)."'"; + $sql .= " WHERE filepath = 'memo/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->error = $this->db->lasterror(); + } + + // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); + $dirsource = $conf->quickmemo->dir_output.'/memo/'.$oldref; + $dirdest = $conf->quickmemo->dir_output.'/memo/'.$newref; + if (!$error && file_exists($dirsource)) { + dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); + + if (@rename($dirsource, $dirdest)) { + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles = dol_dir_list($conf->quickmemo->dir_output.'/memo/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); + foreach ($listoffiles as $fileentry) { + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } + } + } + } + + // Set new ref and current status + if (!$error) { + $this->ref = $num; + $this->status = self::STATUS_VALIDATED; + } + + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } + + + /** + * Set draft status + * + * @param User $user Object user that modify + * @param int<0,1> $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int<0,1> Return integer <0 if KO, >0 if OK + */ + public function setDraft($user, $notrigger = 0) + { + // Protection + if ($this->status <= self::STATUS_VALIDATED) { + return 0; + } + + /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo','write')) + || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo','quickmemo_advance','validate')))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'QUICKMEMO_MEMO_UNVALIDATE'); + } + + + /** + * Set archived status + * + * @param User $user Object user that modify + * @param int<0,1> $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int<0,1> Return integer <0 if KO, >0 if OK + */ + public function setArchived($user, $notrigger = 0) + { + $this->date_archived = dol_now(); + $this->fk_user_archived = $user->id; + $this->status = self::STATUS_ARCHIVED; + return $this->update($user, $notrigger); + } + + + /** + * Set unarchived status + * + * @param User $user Object user that modify + * @param int<0,1> $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int<0,1> Return integer <0 if KO, >0 if OK + */ + public function setUnArchived($user, $notrigger = 0) + { + $this->date_archived = null; + $this->fk_user_archived = null; + $this->status = self::STATUS_VALIDATED; + return $this->update($user, $notrigger); + } + + /** + * Set cancel status + * + * @param User $user Object user that modify + * @param int<0,1> $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int<-1,1> Return integer <0 if KO, 0=Nothing done, >0 if OK + */ + public function cancel($user, $notrigger = 0) + { + // Protection + if ($this->status != self::STATUS_VALIDATED) { + return 0; + } + + /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo','write')) + || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo','quickmemo_advance','validate')))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'QUICKMEMO_MEMO_CANCEL'); + } + + /** + * Set back to validated status + * + * @param User $user Object user that modify + * @param int<0,1> $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int<-1,1> Return integer <0 if KO, 0=Nothing done, >0 if OK + */ + public function reopen($user, $notrigger = 0) + { + // Protection + if ($this->status == self::STATUS_VALIDATED) { + return 0; + } + + /*if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo','write')) + || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo','quickmemo_advance','validate')))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'QUICKMEMO_MEMO_REOPEN'); + } + + /** + * getTooltipContentArray + * + * @param array $params Params to construct tooltip data + * @since v18 + * @return array{optimize?:string,picto?:string,ref?:string} + */ + public function getTooltipContentArray($params) + { + global $langs; + + $datas = []; + + if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) { + return ['optimize' => $langs->trans("ShowMemo")]; + } + $datas['picto'] = img_picto('', $this->picto).' '.$langs->trans("Memo").''; + if (isset($this->status)) { + $datas['picto'] .= ' '.$this->getLibStatut(5); + } + + return $datas; + } + + /** + * Return a link to the object card (with optionally the picto) + * + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @param string $option On what the link point to ('nolink', ...) + * @param int $notooltip 1=Disable tooltip + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) + { + global $conf, $langs, $hookmanager; + + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } + + $result = ''; + $params = [ + 'id' => (string) $this->id, + 'objecttype' => $this->element.($this->module ? '@'.$this->module : ''), + 'option' => $option, + ]; + $classfortooltip = 'classfortooltip'; + $dataparams = ''; + if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) { + $classfortooltip = 'classforajaxtooltip'; + $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"'; + $label = ''; + } else { + $label = implode($this->getTooltipContentArray($params)); + } + + $baseurl = dol_buildpath('/quickmemo/memo_card.php', 1); + $query = ['id' => $this->id]; + if ($option !== 'nolink') { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $query = array_merge($query, ['save_lastsearch_values' => 1]); + } + } + $url = dolBuildUrl($baseurl, $query); + + $linkclose = ''; + if (empty($notooltip)) { + if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) { + $label = $langs->trans("ShowMemo"); + $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"'; + } + $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"'); + $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"'; + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } + + if ($option == 'nolink') { + $linkstart = ''; + if ($option == 'nolink') { + $linkend = ''; + } else { + $linkend = ''; + } + + $result .= $linkstart; + + if (empty($this->showphoto_on_popup)) { + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1); + } + } else { + if ($withpicto) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + [$class, $module] = explode('@', $this->picto); + $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref); + $filearray = dol_dir_list($upload_dir, "files"); + $filename = $filearray[0]['name']; + if (!empty($filename)) { + $pospoint = strpos($filearray[0]['name'], '.'); + + $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint); + if (!getDolGlobalString(strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) { + $result .= '
No photo
'; + } else { + $result .= '
No photo
'; + } + + $result .= ''; + } else { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1); + } + } + } + + if ($withpicto != 2) { + $result .= $this->ref; + } + + $result .= $linkend; + //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + + global $action, $hookmanager; + $hookmanager->initHooks(array($this->element.'dao')); + $parameters = array('id' => $this->id, 'getnomurl' => &$result); + $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } + + return $result; + } + + /** + * Return a thumb for kanban views + * + * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link) + * @param ?array $arraydata Array of data + * @return string HTML Code for Kanban thumb. + */ + public function getKanbanView($option = '', $arraydata = null) + { + global $conf, $langs; + + $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']); + + $return = '
'; + $isDarkMode = !empty($this->color) && !colorIsLight($this->color) ? '--memo-is-dark' : ''; + $style = !empty($this->color) && Memo::checkColor($this->color) ? ' style="--memo-color : '.$this->color.'" ' : ''; + $return .= '
'; + $return .= '
'; + + $return .= ''.$this->getLibStatut(4).''; + + // $return .= ''.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).''; + if ($selected >= 0) { + $return .= ''; + } + + + + $return .= '
'; + $return .= nl2br(htmlentities($this->quick_note)); + $return .= '
'; + + $return .= '
'; + $return .= '
'; + $return .= ' '.$this->showOutputField($this->fields['fk_user_creat'], 'fk_user_creat', $this->user_creation_id).''; + $return .= ' '.dol_print_date($this->date_creation, '%d/%m/%Y %H:%M').''; + $return .= '
'; + + + if (!empty($this->tms) && $this->tms != $this->date_creation) { + $return .= '
'; + + $return .= ' '.$langs->trans('QuickMemoModified') . ' ' .dol_print_date($this->date_modification, '%d/%m/%Y %H:%M').''; + if ($this->user_modification_id != $this->user_creation_id) { + $return .= ' '.$langs->trans('QuickMemoBy') . ' ' .$this->showOutputField($this->fields['fk_user_modif'], 'fk_user_modif', $this->user_modification_id).''; + } + + $return .= '
'; + } + + if (!empty($this->date_archived) && $this->status == self::STATUS_ARCHIVED) { + $return .= '
'; + + $return .= ' '.$langs->trans('QuickMemoArchived') . ' ' .dol_print_date($this->date_archived, '%d/%m/%Y %H:%M').''; + if ($this->fk_user_modif != $this->fk_user_archived) { + $return .= ' '.$langs->trans('QuickMemoBy') . ' ' .$this->showOutputField($this->fields['fk_user_archived'], 'fk_user_archived', $this->fk_user_archived).''; + } + + $return .= '
'; + } + + $this->date_archived = dol_now(); + $this->fk_user_archived = (int) $this->user->id; + + + $return .= '
'; + + + + + $return .= '
'; + $return .= '
'; + $return .= '
'; + + return $return; + } + + /** + * Return the label of the status + * + * @param int<0,6> $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + public function getLabelStatus($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } + + /** + * Return the label of the status + * + * @param int<0,6> $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return the label of a given status + * + * @param int $status Id status + * @param int<0,6> $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + if (is_null($status)) { + return ''; + } + + $paramsBadge = array('badgeParams' => array('attr' => array( + 'data-status-element' => $this->element, + 'data-status' => (int) $status + ))); + + + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { + global $langs; + //$langs->load("quickmemo@quickmemo"); + $this->labelStatus[self::STATUS_TPL] = $langs->transnoentitiesnoconv('Template'); + $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled'); + $this->labelStatus[self::STATUS_ARCHIVED] = $langs->transnoentitiesnoconv('Archived'); + $this->labelStatusShort[self::STATUS_TPL] = $langs->transnoentitiesnoconv('Template'); + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled'); + $this->labelStatusShort[self::STATUS_ARCHIVED] = $langs->transnoentitiesnoconv('Archived'); + } + + $statusType = 'status'.$status; + //if ($status == self::STATUS_VALIDATED) $statusType = 'status1'; + if ($status == self::STATUS_ARCHIVED) { + $statusType = 'status6'; + } + + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode, '', $paramsBadge); + } + + /** + * Load the info information in the object + * + * @param int $id Id of object + * @return void + */ + public function info($id) + { + $sql = "SELECT t.rowid, t.date_creation as datec"; + if (!empty($this->isextrafieldmanaged) && $this->isextrafieldmanaged == 1) { + $sql .= ", GREATEST(t.tms, te.tms) as datem"; + } else { + $sql .= ", t.tms as datem"; + } + if (!empty($this->fields['date_validation'])) { + $sql .= ", t.date_validation as datev"; + } + if (!empty($this->fields['fk_user_creat'])) { + $sql .= ", t.fk_user_creat"; + } + if (!empty($this->fields['fk_user_modif'])) { + $sql .= ", t.fk_user_modif"; + } + if (!empty($this->fields['fk_user_valid'])) { + $sql .= ", t.fk_user_valid"; + } + $sql .= " FROM ".$this->db->prefix().$this->table_element." as t"; + if (!empty($this->isextrafieldmanaged) && $this->isextrafieldmanaged == 1) { + $sql .= " LEFT JOIN ".$this->db->prefix().$this->table_element."_extrafields as te ON te.fk_object = t.rowid"; + } + $sql .= " WHERE t.rowid = ".((int) $id); + + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + + $this->id = $obj->rowid; + + if (!empty($this->fields['fk_user_creat'])) { + $this->user_creation_id = $obj->fk_user_creat; + } + if (!empty($this->fields['fk_user_modif'])) { + $this->user_modification_id = $obj->fk_user_modif; + } + if (!empty($this->fields['fk_user_valid'])) { + $this->user_validation_id = $obj->fk_user_valid; + } + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem); + if (!empty($obj->datev)) { + $this->date_validation = empty($obj->datev) ? '' : $this->db->jdate($obj->datev); + } + } + + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } + + /** + * Initialize object with example values + * Id must be 0 if object instance is a specimen + * + * @return int + */ + public function initAsSpecimen() + { + // Set here init that are not commonf fields + // $this->property1 = ... + // $this->property2 = ... + + return $this->initAsSpecimenCommon(); + } + + + /** + * Returns the reference to the following non used object depending on the active numbering module. + * + * @return string Object free reference + */ + public function getNextNumRef() + { + return ''; + } + + /** + * Create a document onto disk according to template module. + * + * @param string $modele Force template to use ('' to not force) + * @param Translate $outputlangs object lang a utiliser pour traduction + * @param int<0,1> $hidedetails Hide details of lines + * @param int<0,1> $hidedesc Hide description + * @param int<0,1> $hideref Hide ref + * @param ?array $moreparams Array to provide more information + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) + { + return 0; + } + + /** + * Vérifie si une couleur est un code hex valide + * + * @param mixed $color the color to check + * @return bool + */ + static public function checkColor($color) + { + if (!is_string($color)) { + return false; + } + + // Remove spaces at the beginning/end + $color = trim($color); + + // Vérifie #fff ou #ffffff + return preg_match('/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/', $color) === 1; + } + + /** + * Get color preset + * + * @return string[] + */ + static public function getColorPreset() + { + + $colorsConf = getDolGlobalString('QUICKMEMO_COLORS_PRESET'); + $colors = explode(',', $colorsConf); + if (!empty($colors)) { + foreach ($colors as $iColor => $color) { + if (!preg_match('/^#[a-f0-9]{6}$/i', $color)) { + unset($colors[$iColor]); + } + } + } + + if (empty($colors)) { + $colors = ['#fff8a6', '#ffd6d6', '#d6ffd9', '#d6e6ff', '#f3d6ff', '#ffffff', '#f5f5f5']; + } + + return array_values($colors); + } + + /** + * Get memo context + * + * @param string|array $context Context + * @return mixed|string + */ + public static function getMemoContext($context) + { + global $db,$action, $hookmanager; + + if (!is_array($context)) { + $context = explode(':', $context); + } + + $memoContext = ''; + if (in_array('index', $context)) { + $memoContext = 'index'; + } elseif (in_array('globalcard', $context)) { + $memoContext = 'card'; + } + + + $staticMemo = new self($db); + + $hookmanager->initHooks(array($staticMemo->element.'dao')); + $parameters = array( + 'memoContext' =>& $memoContext + ); + $object = null; + $reshook = $hookmanager->executeHooks('getMemoContext', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) { + return $hookmanager->resPrint; + } + + return $memoContext; + } + + /** + * Get available memo context + * + * @return mixed|mixed[]|string[] + */ + public static function getAvailableMemoContext() + { + global $db,$action, $hookmanager; + + $list = ['card', 'index']; + + $staticMemo = new self($db); + $hookmanager->initHooks(array($staticMemo->element.'dao')); + $parameters = array( + 'list' =>& $list + ); + $object = null; + $reshook = $hookmanager->executeHooks('getAvailableMemoContext', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) { + return $hookmanager->resArray; + } + + return $list; + } + + + /** + * Count archived memo query + * + * @param string $element_type Type of element + * @param int $element_id Id of element + * @param string $context Context + * @param int $id Id + * + * @return int|false + */ + public function countArchivedMemoQuery($element_type, $element_id, $context, $id = 0) + { + global $user; + + $sql = 'SELECT COUNT(m.rowid) nb + FROM '.MAIN_DB_PREFIX.$this->table_element.' m + WHERE m.element_type = \''.$this->db->escape($element_type).'\' + AND ( m.fk_element = '.(int) $element_id.' OR m.shared_on_element = 1 ) + AND m.context_tab = \''.$this->db->escape($context).'\' + AND m.status = '.Memo::STATUS_ARCHIVED.' + AND (m.private = 0 OR m.fk_user_creat = '.(int) $user->id.') + '; + + if ((int) $id > 0 ) { + $sql.= ' AND m.rowid = ' . (int) $id; + } + + $obj = $this->db->getRow($sql); + if (!$obj) { + return false; + } + + return (int) $obj->nb; + } + + /** + * Get memos query + * + * @param string $element_type Type of element + * @param int $element_id Id of element + * @param string $context Context + * @param int $id Id + * + * @return string + */ + public function getMemosQuery($element_type, $element_id, $context, $id = 0) + { + global $user; + + $sql = 'SELECT m.rowid, m.quick_note, m.pos_x, m.pos_y, m.pos_w, m.pos_h, m.pos_z, m.color, m.fk_user_creat, m.fk_user_modif, m.shared_on_element, m.date_creation, m.tms, m.private, + mu.pos_x as user_pos_x, mu.pos_y as user_pos_y, mu.pos_w as user_pos_w, mu.pos_h as user_pos_h, mu.pos_z as user_pos_z + FROM '.MAIN_DB_PREFIX.$this->table_element.' m + LEFT JOIN '.MAIN_DB_PREFIX.$this->table_element.'_user mu + ON mu.fk_memo = m.rowid + AND mu.fk_user = '.(int) $user->id.' + WHERE m.element_type = \''.$this->db->escape($element_type).'\' + AND ( m.fk_element = '.(int) $element_id.' OR m.shared_on_element = 1 ) + AND m.context_tab = \''.$this->db->escape($context).'\' + AND m.status = '.self::STATUS_VALIDATED.' + AND (COALESCE(m.private, 0) = 0 OR m.fk_user_creat = '.(int) $user->id.') + '; + + if ((int) $id > 0 ) { + $sql.= ' AND m.rowid = ' . (int) $id; + } + + $sql.= ' ORDER BY COALESCE(mu.pos_z, m.pos_z) ASC'; + return $sql; + } + + + /** + * Get template memos query + * + * @param string $element_type Type of element + * @param string $context_tab Context tab + * @param int $id Id + * + * @return string + */ + public function getTemplateMemosQuery($element_type, $context_tab = '', $id = 0) + { + global $user; + + $sql = 'SELECT m.rowid, m.quick_note, m.pos_x, m.pos_y, m.pos_w, m.pos_h, m.color, m.pos_z, + m.fk_user_creat, m.fk_user_modif, m.shared_on_element, m.date_creation, m.tms, m.private, m.name_tpl,m.rank_tpl, + mu.pos_x as user_pos_x, mu.pos_y as user_pos_y, mu.pos_w as user_pos_w, mu.pos_h as user_pos_h, mu.pos_z as user_pos_z + FROM '.MAIN_DB_PREFIX.$this->table_element.' m + LEFT JOIN '.MAIN_DB_PREFIX.$this->table_element.'_user mu + ON mu.fk_memo = m.rowid + AND mu.fk_user = '.(int) $user->id.' + WHERE m.element_type IN (\''.$this->db->escape($element_type).'\', \'\') + AND m.status = '.self::STATUS_TPL.' + AND (COALESCE(m.private_tpl, 0) = 0 OR m.fk_user_creat = '.(int) $user->id.') + '; + + if (!empty($context_tab)) { + //$sql.= ' AND (m.context_tab = \''.$this->db->escape($context_tab).'\' OR m.element_type = \'\' ) '; + } + + if ((int) $id > 0 ) { + $sql.= ' AND m.rowid = ' . (int) $id; + } + + $sql.= " ORDER BY m.rank_tpl DESC, m.rowid ASC "; // Due to multiple type of sort panel rank_tpl is reversed higher is first and rowid ASC to keep last add is last + + return $sql; + } + + /** + * Return HTML string to show a field into a page + * Code very similar with showOutputField of extra fields + * + * @param array{type:string,label:string,enabled:int<0,2>|string,position:int,notnull?:int,visible:int,noteditable?:int,default?:string,index?:int,foreignkey?:string,searchall?:int,isameasure?:int,css?:string,csslist?:string,help?:string,showoncombobox?:int,disabled?:int,arrayofkeyval?:array,comment?:string} $val Array of properties of field to show + * @param string $key Key of attribute + * @param string|int|null $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) + * @param string $moreparam To add more parameters on html tag + * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names) + * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names) + * @param mixed $morecss Value for CSS to use (Old usage: May also be a numeric to define a size). + * @return string + */ + public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '') + { + global $conf, $langs, $form; + + if ($key == 'color' && self::checkColor($value)) { + $badgeBase = colorIsLight($value) ? 'badge-light' : 'badge-dark'; + return ''.$value.''; + } + + if ($key == 'quick_note') { + return nl2br(htmlentities($value)); + } + + return parent::showOutputField($val, $key, $value, $moreparam, $keysuffix, $keyprefix, $morecss); + } + + /** + * Load the Javascript interface for QuickMemo + * + * @param array $jsConfVars Configuration variables + * @return bool + */ + public static function loadQuickMemoJsInterface($jsConfVars) + { + global $user; + + // DO NOT LOAD TWICE + if (defined('QUICKMEMOJS')) { + return false; + } + + if (defined('NOREQUIRETRAN') || empty($user) || empty($user->id) || (int) $user->socid> 0 ) { + return false; + } + + if (!$user->hasRight('quickmemo', 'memo', 'read')) { + return false; + } + + $defaultJsConfVars = [ + 'interfaceUrl' => dol_buildpath('quickmemo/interface.php', 1), + 'archivesUrl' => dol_buildpath('quickmemo/memo_list.php', 1) . '?mode=kanban&search_status='.Memo::STATUS_ARCHIVED . ($jsConfVars['archivesUrlParams'] ?? ''), + 'elementId' => 0, + 'elementType' => '', + 'context' => null, + 'token' => newToken(), + 'colors' => Memo::getColorPreset(), + 'userReadRight' => $user->hasRight('quickmemo', 'memo', 'read'), + 'userWriteRight' => $user->hasRight('quickmemo', 'memo', 'write'), + 'userDeleteRight' => $user->hasRight('quickmemo', 'memo', 'delete') + ]; + $jsConfVars = array_merge($defaultJsConfVars, $jsConfVars); + + // LOAD Memo class + print ''."\n"; + print ''."\n"; + print ''."\n"; + + print ''."\n"; + + define('QUICKMEMOJS', true); + return true; + } + + /** + * Get JS memo + * + * @param User $currentUser Current user + * + * @return stdClass + */ + public function getJsMemo(User $currentUser) + { + global $langs; + + $memo = self::getJsMemoDefault(); + $memo->id = $this->id; + $memo->color = $this->color; + $memo->note = $this->quick_note; + + $memo->pos_x = (int) $this->pos_x; + $memo->pos_y = (int) $this->pos_y; + $memo->pos_w = (int) $this->pos_w; + $memo->pos_h = (int) $this->pos_h; + + if ($currentUser->id != $memo->fk_user_creat) { + // TODO update positions + } + + $memo->shared_on_element = $this->shared_on_element; + $memo->private = (int) $this->private; + $memo->date_creation = dol_print_date($this->date_creation, '%d/%m/%Y %H:%M'); + $memo->date_change = ''; + if (!empty($this->tms) && ((int) $this->date_creation !== (int) $this->tms || (int) $this->fk_user_modif > 0)) { + $memo->date_change = dol_print_date($this->tms, '%d/%m/%Y %H:%M'); + } + + $memo->fk_user_creat = $this->fk_user_creat; + $memo->user_name = ''; + if ((int) $this->fk_user_creat > 0) { + $userCreate = new User($this->db); + if ($userCreate->fetch((int) $this->fk_user_creat) > 0) { + $memo->user_name = $userCreate->getFullName($langs); + } + } + + $memo->fk_user_modif = $this->fk_user_modif; + $memo->user_change_name = ''; + if ((int) $this->fk_user_modif > 0) { + $userMod = new User($this->db); + if ($userMod->fetch((int) $this->fk_user_modif) > 0) { + $memo->user_change_name = $userMod->getFullName($langs); + } + } + + return $memo; + } + + /** + * Get JS memo default + * + * @return stdClass + */ + static public function getJsMemoDefault() + { + $memo = new stdClass(); + $memo->id = null; + $memo->color = null; + $memo->note = null; + $memo->pos_x = 0; + $memo->pos_y = 0; + $memo->pos_w = 0; + $memo->pos_h = 0; + $memo->shared_on_element = 0; + $memo->private = 0; + $memo->date_creation = ''; + $memo->date_change = ''; + $memo->fk_user_creat = null; + $memo->user_name = ''; + $memo->fk_user_modif = null; + $memo->user_change_name = ''; + return $memo; + } +} diff --git a/htdocs/quickmemo/css/memo-dialog.css b/htdocs/quickmemo/css/memo-dialog.css new file mode 100644 index 00000000000..50abd1e0bf6 --- /dev/null +++ b/htdocs/quickmemo/css/memo-dialog.css @@ -0,0 +1,276 @@ +dialog.quickmemo-modal { + --default-padding: 10px; + color: #121c2f; + border: none; + outline: none; + background: #fff; + padding: 20px; + border-radius: 8px; + max-width: 400px; + max-height: 90vh; + width: 90%; + box-shadow: 0 2px 10px rgba(0,0,0,0.2); +} + +dialog.quickmemo-modal.dialog-lg { + max-width: 800px; +} + +dialog.quickmemo-modal.dialog-xl { + max-width: 80%; +} + +dialog.quickmemo-modal.dialog-full-screen { + width: 80vw; + max-width: 95vw; + height: 90vh; + max-height: 95vh; +} + +.dialog-content{ + display: flex; + flex-direction: column; /* Stack header, body, and footer vertically */ + max-height: 90vh; /* Inherit the max-height constraint */ +} + + +dialog.quickmemo-modal::backdrop { + background: rgba(0,0,0,0.5); +} + +dialog.quickmemo-modal.--dialog-danger::backdrop { + background: rgba(30, 0, 0, 0.5); + backdrop-filter: blur(5px); +} + +.quickmemo-modal-actions { + margin-top: 16px; + display: flex; + justify-content: flex-end; + gap: 8px; +} + +.noselect { + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Old versions of Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; /* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */ +} +.quickmemo-modal-input-group{ + margin-bottom: 10px; +} +.quickmemo-modal-text-input { + width: 100%; +} + +.quickmemo-modal header{ + flex-shrink: 0; /* Prevent header from being squashed */ + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 10px; + + padding: 0; + margin-bottom: 20px; +} + +.quickmemo-modal-title{ + padding: 0; + margin: 0; + font-size: 1rem; + font-weight: 600; + text-align: left; + word-break: break-word; +} + +.header-actions { + display: flex; + gap: 5px; + transform: translateY( calc(-1 * var(--default-padding))) translateX(calc(var(--default-padding))); + flex-shrink: 0; /* Empêche le bouton de s'écraser */ +} + +/* Scrollable Body */ +.dialog-body { + flex: 1 1 auto; /* Take up all remaining vertical space */ + overflow-y: auto; /* Enable vertical scrolling only for this section */ + line-height: 1.6; + + /* Subtle inner shadows to indicate more content is available */ + /* 1. Shadow that scrolls with the content (hides the fixed shadow) */ + /* 2. Fixed shadow that stays at the top/bottom */ + background: + linear-gradient(white 30%, rgba(255,255,255,0)), + linear-gradient(rgba(255,255,255,0), white 70%) 0 100%, + radial-gradient(farthest-side at 50% 0, rgba(0,0,0,0.2), rgba(0,0,0,0)), + radial-gradient(farthest-side at 50% 100%, rgba(0,0,0,0.2), rgba(0,0,0,0)) 0 100%; + + background-repeat: no-repeat; + background-size: 100% 40px, 100% 40px, 100% 14px, 100% 14px; + background-attachment: local, local, scroll, scroll; +} + +/* Custom scrollbar for a cleaner look */ +.dialog-body::-webkit-scrollbar { + width: 6px; +} + +.dialog-body::-webkit-scrollbar-thumb { + background-color: rgba(0,0,0,0.1); + border-radius: 10px; +} + +.quickmemo-modal-confirm-text{ + font-size: .875rem; + line-height: calc(1.25 / .875); +} + + +.dialog-btn { + display: inline-flex; + justify-content: center; + align-items: center; + + height: 36px; + padding: 0 16px; + + font-family: InterVariable, system-ui, sans-serif; + font-size: 14px; + font-weight: 600; + line-height: 20px; + + border-radius: 6px; + border: 0; + + box-shadow: + inset 0 0 0 1px transparent, + 0 1px 2px rgba(0, 0, 0, 0.05); + + cursor: pointer; + transition: background-color 0.15s ease, box-shadow 0.15s ease; +} + +/* CANCEL */ + +.dialog-btn.dialog-btn-secondary { + background: #ffffff; + color: #1f2433; + + box-shadow: + inset 0 0 0 1px #d9dee6, + 0 1px 2px rgba(0, 0, 0, 0.05); +} + +.dialog-btn.dialog-btn-secondary:hover { + background: #f5f7fa; +} + +/* PRIMARY */ + +.dialog-btn.dialog-btn-primary { + position: relative; + background: var(--colortextlink); + color: #fff; +} + +.dialog-btn.dialog-btn-primary::after { + content: ""; + position: absolute; + inset: 0; + background: rgba(0,0,0,0); + transition: background 0.15s; +} + +.dialog-btn.dialog-btn-primary:hover::after { + background: rgba(0,0,0,0.1); /* léger assombrissement */ +} + +/* DANGER */ + +.dialog-btn.dialog-btn-destructive { + background: #dc2626; + color: #ffffff; +} + +.dialog-btn.dialog-btn-destructive:hover { + background: #b91c1c; +} + + +@media (min-width: 40rem) { + dialog.quickmemo-modal { + max-width: 32rem; + } +} + +@media (min-width: 40rem) { + dialog.quickmemo-modal { + width: 100%; + } +} + +.dialog-content footer{ + flex-shrink: 0; /* Keep footer size constant */ +} + + + + +/* close btn */ + + /* The Close Button Design */ +.dialog-close-icon { + /* Reset default button styles */ + appearance: none; + background: transparent; + border: none; + padding: 0; + cursor: pointer; + + /* Perfect Circle Shape */ + width: 28px; + height: 28px; + border-radius: 50%; /* Makes it round */ + + /* Content Alignment (centering the ×) */ + display: flex; + align-items: center; + justify-content: center; + + /* Typography for the '×' character */ + font-size: 20px; + line-height: 1; + font-family: Arial, sans-serif; /* Clean font for the multiplication sign */ + color: #888; /* Subtle default color */ + + /* Smooth Transitions */ + transition: + background-color 0.2s ease, + color 0.2s ease, + transform 0.1s ease; + + /* Ensure it doesn't shrink in flex headers */ + flex-shrink: 0; +} + +/* --- Interactive States --- */ + +/* Hover State */ +.dialog-close-icon:hover { + background-color: rgba(0, 174, 255, 0.08); + color: #3599dc; +} + +/* Active State (Clicking) */ +.dialog-close-icon:active { + transform: scale(0.92); + background-color: rgba(0, 0, 255, 0.15); +} + +/* Focus State (Accessibility - when tabbing) */ +.dialog-close-icon:focus-visible { + outline: 2px solid #3599dc; + outline-offset: 1px; +} diff --git a/htdocs/quickmemo/css/memo.css b/htdocs/quickmemo/css/memo.css new file mode 100644 index 00000000000..eea6c4a5fbb --- /dev/null +++ b/htdocs/quickmemo/css/memo.css @@ -0,0 +1,601 @@ +#quickmemo-create-dropdown { + position: relative; +} +.dropdown-quickmemo-create{ + min-width: 250px; +} + + + +/* fix Dolibarr < 22 */ +.login_block .dropdown-menu.dropdown-quickmemo-create { + right: 0; + transform: translateX(30px); +} +@media (max-width: 1118px) { + .login_block .dropdown-menu.dropdown-quickmemo-create { + right: auto; + transform: translateX(0); + } +} +/* end fix Dolibarr < 22 */ + + +#quickmemo-create-dropdown .dropdown-menu{ + --colortextbackhmenu : #333; + /*color: var(--colortextbackhmenu) !important;*/ + animation: dropdown-quickmemo-slide-up 0.3s ease-in-out; +} + +@keyframes dropdown-quickmemo-slide-up { + 0% { + transform: translate(0, 5px) translateX(30px); + opacity: 0; + } + 100% { + transform: translate(0, 0%) translateX(30px); + opacity: 1; + } +} + + + +.dropdown-quickmemo-create .dropdown-header{ + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 10px 10px 10px 15px; +} + +.dropdown-header-title{ + padding: 0; + margin: 0; + font-size: 14px; + line-height: 1.2; + font-weight: 600; + text-align: left; + word-break: break-word; +} + +.dropdown-header-actions { + display: flex; + align-items: center; + gap: 5px; + flex-shrink: 0; +} + + + +.quickmemo-archive-list,.quickmemo-tpl-title{ + margin: 20px 0 5px 0; +} +#quickmemo-create-dropdown a.top-menu-dropdown-quicknote-link{ + color: var(--colortextlink);; +} +.quickmemo-tpl-title{ + color: #333; + padding: 5px 0; +} +.quickmemo-tpl-title:first-child{ + margin-top: 0px; + padding-top: 0; +} +.quickmemo-tpl-list { + color: #3d3d3d; + + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.no-models { + opacity: 0.5; + text-align: center; + width: 100%; +} + +.quickmemo-model-btn, .quickmemo-model-placeholder{ + --color-block-size : 36px; + width: var(--color-block-size); + height: var(--color-block-size); + border-radius: 6px; + position: relative; + border: 1px solid #ccc; + cursor: pointer; +} +.quickmemo-model-placeholder{ + border-style: dashed; + cursor: default; +} + +.quickmemo-model-btn:hover:before { + content: "\f067"; + -webkit-font-smoothing: antialiased; + display: inline-block; + font-style: normal; + font-variant: normal; + text-rendering: auto; + line-height: var(--color-block-size, 36px); + font-weight: 900; + font-family: "Font Awesome 5 Free"; + opacity: 0.5; + + color: white; + mix-blend-mode: difference; + + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); +} + + + +.quickmemo-model-delete { + display: none; + position: absolute; + top: 0px; + right: 0px; + width: 16px; + height: 16px; + align-items: center; + justify-content: center; + font-size: 14px; + background: rgba(0,0,0,0.4); + color: #fff; + border-radius: 50%; + cursor: pointer; + transform: translateX(50%) translateY(-50%); +} +.quickmemo-model-delete:before{ + content: '\00d7'; /* code Unicode pour × */ +} +.quickmemo-model-delete.--show { + display: flex; +} + +#quickmemo-model-list:has(.quickmemo-model-btn.--dragging) .quickmemo-model-btn:hover:before, +#quickmemo-model-list:has(.quickmemo-model-btn.--dragging) .quickmemo-model-delete.--show { + display:none; +} + +.quickmemo-model-placeholder { + border: 1px dashed #999; + margin: 0 0; + border-radius: 4px; +} + +.quickmemo-note{ + --memo-color: #fff8a6; + box-sizing: border-box; + position: relative; + filter: drop-shadow(0px 2px 3px rgba(0,0,0,0.25)); + padding: 6px; + border-radius: 2px; + background: var(--memo-color); + border: 2px dotted var(--memo-color); + + position: absolute; + cursor: grab; + + opacity: 1; + transition: opacity 0.3s ease; +} + +.quickmemo-note[data-private="1"] { + background-image: url("../img/private.svg"); + background-position: center; + background-repeat: no-repeat; + background-size: 50% 50% ; + background-blend-mode: exclusion; +} + +.quickmemo-note[data-shared="1"] { + border: 2px dotted rgba(0, 0, 0, 0.2); +} +.quickmemo-note.--memo-is-dark[data-shared="1"] { + border: 2px dotted rgba(255, 255, 255, 0.8); +} + +.quickmemo-note.--memo-is-dark, .info-box-quickmemo.--memo-is-dark { + color: #ffffff; +} + +body.hide-quickmemo .quickmemo-note { + opacity: 0; + pointer-events: none; +} + +.quickmemo-footer{ +padding-top: 5px; +} + +.quickmemo-header{ + position: relative; +} + +.quickmemo-actions{ + position: absolute; + right: 0; + top: 0; + + transform: translateY(-20%); + opacity: 0; + pointer-events: none; + + border-radius: 10px 10px 0 0 ; + padding: 3px 5px; + background: var(--memo-color); + + transition: + transform 0.25s ease, /* delay sur transform si nécessaire */ + opacity 0.2s ease; /* delay sur fade in */ +} + +.quickmemo-note:hover .quickmemo-actions{ + transform: translateY(-100%); + opacity: 1; + pointer-events: auto; + z-index: -1; +} + + + +.quickmemo-note.--dragging * { + cursor: grabbing; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Old versions of Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; /* Non-prefixed version, currently */ +} + +input[type="color"].quickmemo-color-input { + padding: 0; + width: 20px; + height: 20px; + box-sizing: border-box; + margin: 0 5px; +} +.quickmemo-actions { + cursor: default; +} + +.quickmemo-info { + font-size: 0.7em; + opacity: 70%; + cursor: grab; + min-height: 20px; +} + +.quickmemo-info__user-create-name { + font-weight: bold; +} + +.quickmemo-info__date_create, .quickmemo-info__date_update, .quickmemo-info__user-change-name { + +} + +.quickmemo-info__create{ + display: block; +} + +.quickmemo-meta{ + text-align: right; +} + +.quickmemo-note { + display: flex; + flex-direction: column; +} + +.quickmemo-note textarea, .quickmemo-markdown-preview { + flex: 1 1 auto; /* prend tout l'espace restant */ + width: 100%; + height: 100%; + min-height: 0; /* important pour que flex calcule bien */ + font-size: 1.1em; + padding: 5px; + margin: 0px; + line-height: 1.1em; + + border: none !important; + outline: none !important; + box-sizing: border-box !important; + background: transparent; + background-color: transparent !important; + resize: none; + + + /* Subtle inner shadows to indicate more content is available */ + /* 1. Shadow that scrolls with the content (hides the fixed shadow) */ + /* 2. Fixed shadow that stays at the top/bottom */ + background: + linear-gradient(var(--memo-color) 30%, rgba(255,255,255,0)), + linear-gradient(rgba(255,255,255,0), var(--memo-color) 70%) 0 100%, + radial-gradient(farthest-side at 50% 0, rgba(0,0,0,0.1), rgba(0,0,0,0)), + radial-gradient(farthest-side at 50% 100%, rgba(0,0,0,0.1), rgba(0,0,0,0)) 0 100%; + + background-repeat: no-repeat; + background-size: 100% 40px, 100% 40px, 100% 14px, 100% 14px; + background-attachment: local, local, scroll, scroll; +} + +/* Custom scrollbar for a cleaner look */ +:is(.quickmemo-note textarea, .quickmemo-markdown-preview )::-webkit-scrollbar { + width: 6px; +} + +:is(.quickmemo-note textarea, .quickmemo-markdown-preview )::-webkit-scrollbar-thumb { + background-color: rgba(0,0,0,0.2); + border-radius: 10px; +} +.quickmemo-note.--memo-is-dark :is(.quickmemo-note textarea, .quickmemo-markdown-preview )::-webkit-scrollbar-thumb { + background-color: rgba(255,255,255,0.7); +} + +.quickmemo-note.--edit-mode textarea { + display: block; +} +.quickmemo-note.--edit-mode .quickmemo-markdown-preview { + display: none; +} + +.markdown-line:has(.markdown-checkbox:checked) { + text-decoration: line-through; +} +/*.quickmemo-note textarea:not(:focus) { + display: none; +}*/ + +.quickmemo-note textarea { + resize: none; + display: none; +} +.quickmemo-note textarea:read-only { + cursor: grab; +} + +.quickmemo-note.--memo-is-dark textarea{ + color: #ffffff; +} + + +.quickmemo-note textarea::placeholder,.quickmemo-placeholder { + color: rgba(0, 0, 0, 0.5); /* gris clair, ajustable */ + opacity: 1; /* certains navigateurs rendent le placeholder plus transparent par défaut */ +} + +.quickmemo-note.--memo-is-dark textarea::placeholder,.quickmemo-note.--memo-is-dark .quickmemo-placeholder{ + color: rgba(255, 255, 255, 0.5); /* gris clair, ajustable */ +} + + +.quickmemo-markdown-preview { + overflow: auto; + cursor: grab; +} + + +/* Base styles for post-it headings */ +.quickmemo-markdown-preview :is(h1, h2, h3, h4, h5) { + margin: 0.5em 0 0.2em 0; + padding: 0; + font-weight: 700; /* Bold for hierarchy */ + line-height: 1.2; + color: inherit; +} + +.quickmemo-markdown-preview .markdown-line:first-child > :is(h1, h2, h3, h4, h5) { + margin-top: 0; +} + +.quickmemo-markdown-preview .markdown-line:has(:is(h1, h2, h3, h4, h5)) + .markdown-line.empty-line { + display: none; +} +/* Scaled down for Post-it constraints */ +.quickmemo-markdown-preview h1 { + font-size: 1.4em; /* Not too big, just enough to lead */ + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + padding-bottom: 0.2em; +} + +.quickmemo-markdown-preview h2 { + font-size: 1.25em; + border-bottom: 1px solid rgba(0, 0, 0, 0.05); + padding-bottom: 0.2em; +} + +.quickmemo-markdown-preview h3 { + font-size: 1.15em; +} + +.quickmemo-markdown-preview h4 { + font-size: 1.05em; + text-decoration: underline; /* Style hint to distinguish from H3 */ + text-underline-offset: 2px; +} + +.quickmemo-markdown-preview h5 { + font-size: 1em; + font-style: italic; /* Using style instead of size for the last level */ +} + +/* Dark mode adjustment */ +.quickmemo-note.--memo-is-dark .quickmemo-markdown-preview h1 { + border-bottom-color: rgba(255, 255, 255, 0.2); +} + + + +button.btn-low-emphasis.--btn-icon.quickmemo-btn-archive{ + margin-left : 20px +} + +.quickmemo-note.--memo-is-dark .btn-low-emphasis{ + color: rgba(255, 255, 255, 0.7); /* gris clair, ajustable */ +} + + +.quickmemo-note.--note-delete-animation { + animation: note-delete-animation 0.2s ease-in-out; +} + +@keyframes note-delete-animation { + 0% { + transform: scale(1) translateY(0); + opacity: 1; + } + 100% { + transform: scale(0.8) translateY(50%); + opacity: 0; + } +} + +/* *********** */ +/* KANBAN VIEW */ +/* *********** */ + +.info-box-quickmemo { + --memo-color: #fff8a6; + box-sizing: border-box; + position: relative; + filter: drop-shadow(0px 2px 3px rgba(0,0,0,0.25)); + padding: 8px; + border-radius: 4px 4px 0 0; + background: var(--memo-color); + + position: relative; +} + +.info-box-content-quicknote { + padding: 5px 0px; + max-height: 100px; + min-height: 64px; + overflow: auto; +} + +.info-box-quickmemo .quickmemo-info { + cursor: default; +} + +.quickmemo-markdown-preview__badge { + display: inline-block; + position: absolute; + font-weight: bold; + left:0; + top: 0; + padding: 3px 8px 2px 8px; + border-radius: 20px; + font-size: 10px; + line-height: 10px; + color: #666; + background-color: #ededed; + box-shadow: 1px 1px 1px rgba(0,0,0,.2); + transform: translateY(calc(-50% - 5px)); + cursor: s-resize; +} + +.quickmemo-markdown-preview__badge.success { + background-color: #00ac2d; + color: #ffffff; +} + + + +.quickmemo-editor-toolbar { + display: flex; + position: absolute; + + /* --- VERTICAL ALIGN CENTER --- */ + top: 50%; /* On place le haut de la barre au milieu du mémo */ + left: 4px; + flex-direction: column; + gap: 4px; + background: var(--memo-color); + padding: 4px; + border-right: 1px solid rgba(150,150,150,0.1); + border-radius: 6px; + z-index: 100; + pointer-events: none; + opacity: 0; + + /* --- FOR 3D EFFECT --- */ + transform-origin: right center; + + /** * initial state : + * 1. translateX(-100%) : Sort la barre à gauche du mémo + * 2. translateY(-50%) : Remonte la barre de la moitié de sa propre hauteur pour le centrage + * 3. rotateY(-90deg) : L'effet de rotation "cachée" + */ + transform: translateX(-100%) translateY(-50%) rotateY(-90deg); + + transition: + transform 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275), + opacity 0.2s ease; +} + +/* Show only when parent has the edit mode class */ +.quickmemo-note.--edit-mode .quickmemo-editor-toolbar { + /* On garde le X et le Y, on remet juste la rotation à 0 */ + transform: translateX(-100%) translateY(-50%) rotateY(0deg); + opacity: 1; + pointer-events: auto; +} + +.quickmemo-toolbar-btn { + --btn-size: 24px; + width: var(--btn-size); + height: var(--btn-size); + color: var(--colortextlink, inherit); + font-size: 12px; + border: none; + background: none; + cursor: pointer; + border-radius: 4px; + display: flex; + align-items: center; + justify-content: center; + transition: background 0.2s; +} + +.quickmemo-note.--memo-is-dark .quickmemo-toolbar-btn{ + color: rgba(255, 255, 255, 0.7); +} + + +.quickmemo-toolbar-btn:hover { + background: rgba(255, 255, 255, 0.7); + color: #000; +} +.quickmemo-note.--memo-is-dark .quickmemo-toolbar-btn:hover { + color: var(--memo-color); +} + +.quickmemo-toolbar-btn.--active { + background: #e2eafc; + color: #007bff; + border: 1px solid #007bff; + } +.quickmemo-note.--memo-is-dark .quickmemo-toolbar-btn.--active { + background: #e2eafc; + color: #007bff; + border: 1px solid #007bff; +} + +.quickmemo-note .quickmemo-toolbar-separator { + height: 1px; + width: 50%; + border: none; + background-color: rgba(0, 0, 0, 0.7); + margin: 4px auto; + + transform: scaleY(0.5); + transform-origin: center; +} + +.quickmemo-note.--memo-is-dark .quickmemo-toolbar-separator { + background-color: rgba(255, 255, 255, 0.7); +} diff --git a/htdocs/quickmemo/css/setup.css b/htdocs/quickmemo/css/setup.css new file mode 100644 index 00000000000..68e198af862 --- /dev/null +++ b/htdocs/quickmemo/css/setup.css @@ -0,0 +1,72 @@ + +.color-manager { + max-width: 500px; +} + +.controls { + display: flex; + gap: 10px; + margin-bottom: 10px; +} + +.palette { + display: flex; + gap: 8px; + flex-wrap: wrap; + margin-bottom: 15px; +} + +.palette-color { + width: 28px; + height: 28px; + border-radius: 4px; + cursor: pointer; + border: 1px solid #ccc; +} + +.colors-container { + box-sizing: border-box; + max-width: 100%; + min-width: 300px; + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.color-badge { + width: 36px; + height: 36px; + border-radius: 6px; + position: relative; + border: 1px solid #ccc; + cursor: grab; + +} + +.color-badge.dragging { + opacity: 0.4; +} + +.color-placeholder { + box-sizing: border-box; + width: 36px; + height: 36px; + border-radius: 6px; + position: relative; + border: 1px dashed #999; +} + +.color-badge span { + position: absolute; + top: -6px; + right: -6px; + background: #000; + color: #fff; + width: 16px; + height: 16px; + font-size: 12px; + line-height: 16px; + text-align: center; + border-radius: 50%; + cursor: pointer; +} diff --git a/htdocs/quickmemo/img/private.svg b/htdocs/quickmemo/img/private.svg new file mode 100644 index 00000000000..03bd4d652a3 --- /dev/null +++ b/htdocs/quickmemo/img/private.svg @@ -0,0 +1 @@ + diff --git a/htdocs/quickmemo/interface.php b/htdocs/quickmemo/interface.php new file mode 100644 index 00000000000..735567cbd72 --- /dev/null +++ b/htdocs/quickmemo/interface.php @@ -0,0 +1,1052 @@ +. + */ + +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification + + +// Load Dolibarr environment +require '../main.inc.php'; + +// Load required classes +require_once DOL_DOCUMENT_ROOT . '/core/class/jsonResponse.class.php'; +require_once __DIR__ . '/class/memo.class.php'; +if (!class_exists('Validate')) { + require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; +} + +global $langs, $db, $hookmanager, $user, $mysoc; +/** + * @var DoliDB $db + */ + +// Initialize hooks for the interface +$hookmanager->initHooks(['quickmemoInterface']); + +// Load translation files required by the page +$langs->loadLangs(["quickmemo", "other", 'main']); + +$action = GETPOST('action'); + +// Security check: check if the module is enabled +if (!isModEnabled('quickmemo')) accessforbidden('Module not enabled'); + +$jsonResponse = new JsonResponse(); + +// Security check: basic read permission +if (!$user || !$user->hasRight('quickmemo', 'memo', 'read')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + print $jsonResponse->getResponse(); + $db->close(); // Close $db database opened handler + exit; +} + +// Execute hooks before standard actions +$reshook = $hookmanager->executeHooks('quickMemoInterface', [], $jsonResponse, $action); +if ($reshook < 0) { + $jsonResponse->msg = $hookmanager->error; + if (!empty($hookmanager->errors)) { + $jsonResponse->msg = (!empty($hookmanager->error) ? '
' : '') . implode('
', $hookmanager->errors); + } + $jsonResponse->result = 0; + print $jsonResponse->getResponse(); + $db->close(); // Close $db database opened handler + exit; +} + +// Action Dispatcher: Routes the request to the appropriate function based on the 'action' parameter +if ($reshook > 0) { + // Action handled by hook +} elseif ($action === 'update_position') { + quickMemoIntefaceActionUpdatePosition($jsonResponse); +} elseif ($action === 'update_all_positions') { + quickMemoIntefaceActionUpdateAllPositions($jsonResponse); +} elseif ($action === 'list') { + quickMemoIntefaceActionList($jsonResponse); +} elseif ($action === 'list_models') { + quickMemoIntefaceActionListModels($jsonResponse); +} elseif ($action === 'update-color') { + quickMemoIntefaceActionUpdateColor($jsonResponse); +} elseif ($action === 'update-shared-on-element') { + quickMemoIntefaceActionUpdateSharedOnElement($jsonResponse); +} elseif ($action === 'update-private') { + quickMemoIntefaceActionUpdatePrivate($jsonResponse); +} elseif ($action === 'archive') { + quickMemoIntefaceActionArchiveNote($jsonResponse); +} elseif ($action === 'delete') { + quickMemoIntefaceActionDeleteNote($jsonResponse); +} elseif ($action === 'create') { + quickMemoIntefaceActionCreate($jsonResponse); +} elseif ($action === 'create_model') { + quickMemoIntefaceActionCreateModel($jsonResponse); +} elseif ($action === 'delete_model') { + quickMemoIntefaceActionDeleteModel($jsonResponse); +} elseif ($action === 'update_model_rank') { + quickMemoIntefaceActionUpdateModelRank($jsonResponse); +} elseif ($action === 'update_note') { + quickMemoIntefaceActionUpdateNote($jsonResponse); +} else { + $jsonResponse->msg = 'Action not found'; +} + +print $jsonResponse->getResponse(); + +$db->close(); // Close $db database opened handler + +/** + * Update the coordinates (X, Y), dimensions (W, H), and Z-index of a single memo. + * @param JsonResponse $jsonResponse The response object to populate. + * @return bool Returns false on failure, true on success. + */ +function quickMemoIntefaceActionUpdatePosition($jsonResponse) +{ + global $user, $langs, $db; + + // Read permission is sufficient as this only affects the current user's view + if (!$user->hasRight('quickmemo', 'memo', 'read')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + return false; + } + + $id = GETPOSTINT("id"); + + if (empty($id) && !is_numeric($id)) { + $jsonResponse->msg = 'Need memo Id'; + return false; + } + + $memo = new Memo($db); + if ($memo->fetch($id) <= 0) { + $jsonResponse->msg = 'Memo not found'; + return false; + } + + // Prevent moving a private note belonging to another user + if ($user->id != $memo->fk_user_creat && $memo->private) { + $jsonResponse->msg = $langs->trans('QuickMemoCantMoveThisPrivateNote'); + return false; + } + + $z = GETPOST("z", "int"); + $x = GETPOST("x", "int"); + $y = GETPOST("y", "int"); + $w = GETPOST("w", "int"); + $h = GETPOST("h", "int"); + + if (!$memo->updatePosition($user, (int) $x, (int) $y, (int) $w, (int) $h, (int) $z)) { + $jsonResponse->result = 0; + $jsonResponse->msg = $langs->trans('UpdateError') . ' : ' . $memo->errorsToString(); + return false; + } else { + $jsonResponse->result = 1; + $jsonResponse->data = null; + return true; + } +} + +/** + * Batch update coordinates and Z-index for multiple memos. + * @param JsonResponse $jsonResponse The response object. + * @return bool|void + */ +function quickMemoIntefaceActionUpdateAllPositions($jsonResponse) +{ + global $user, $langs, $db; + + // In case of position, read permission is enough because changing position will affect only this user not others. + // So he can't modify the content but can move it for himself. + if (!$user->hasRight('quickmemo', 'memo', 'read')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + return false; + } + + $json = file_get_contents('php://input'); + $data = json_decode($json, true); + + if (!is_array($data) || empty($data['memos'])) { + $jsonResponse->result = 0; + $jsonResponse->msg = 'No data received'; + return; + } + + $db->begin(); + + foreach ($data['memos'] as $item) { + $memo = new Memo($db); + if ($memo->fetch((int) $item['id']) > 0) { + // Security check for private notes + if ($user->id != $memo->fk_user_creat && $memo->private) continue; + + $memo->updatePosition( + $user, + (int) $item['x'], + (int) $item['y'], + (int) $item['w'], + (int) $item['h'], + (int) $item['z'] + ); + } + } + + $db->commit(); + $jsonResponse->result = 1; + + return true; +} + +/** + * Create a new memo linked to an element or context. + * @param JsonResponse $jsonResponse The response object. + * @return bool Returns false on failure, true on success. + */ +function quickMemoIntefaceActionCreate($jsonResponse) +{ + global $user, $langs, $db; + + if (!$user->hasRight('quickmemo', 'memo', 'write')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + return false; + } + + $element_id = GETPOST("element_id", "int"); + $element_type = GETPOST("element_type"); + + + if (empty($element_id) && !is_numeric($element_id) && !empty($element_type)) { + $jsonResponse->msg = 'Need memo element_id'; + return false; + } + + $memo = new Memo($db); + $context_tab = GETPOST('context'); + if (!in_array($context_tab, $memo->getAvailableMemoContext())) { + $jsonResponse->result = 0; + $jsonResponse->msg = $langs->trans('UpdateError') . ' : Context unknown'; + return false; + } + + // Handle color selection with preset fallback + $colorPresets = Memo::getColorPreset(); + $firstColor = !empty($colorPresets) ? $colorPresets[0] : null; + $memo->color = GETPOST("color"); + if (!Memo::checkColor($memo->color)) { + $memo->color = $firstColor; + } + + $memo->quick_note = GETPOST("note", "alphanohtml"); + $memo->fk_element = $element_id; + $memo->element_type = $element_type; + $jsonResponse->debug = GETPOST("color", $firstColor); + $memo->context_tab = $context_tab; + $memo->shared_on_element = GETPOST("shared_on_element", "int") ? 1 : 0; + $memo->private = GETPOST("private", "int") ? 1 : 0; + + $memo->pos_x = GETPOST("x", "int"); + $memo->pos_y = GETPOST("y", "int"); + $memo->pos_w = GETPOST("w", "int"); + $memo->pos_h = GETPOST("h", "int"); + $memo->pos_z = GETPOST("z", "int"); + $memo->status = Memo::STATUS_VALIDATED; + + $resCre = $memo->create($user); + if ($resCre <= 0 ) { + $jsonResponse->result = 0; + $jsonResponse->msg = $langs->trans('UpdateError') . ' : ' . $memo->errorsToString(); + return false; + } else { + $jsonResponse->result = 1; + $jsonResponse->data = new stdClass(); + $jsonResponse->data->id = (int) $resCre; + + return true; + } +} + + +/** + * Set a memo status to archived. + * @param JsonResponse $jsonResponse The response object. + * @return bool Returns false on failure, true on success. + */ +function quickMemoIntefaceActionArchiveNote($jsonResponse) +{ + global $user, $langs, $db; + + if (!$user->hasRight('quickmemo', 'memo', 'write')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + return false; + } + + $id = GETPOSTINT("id"); + + if (empty($id) && !is_numeric($id)) { + $jsonResponse->msg = 'Need memo Id'; + return false; + } + + $memo = new Memo($db); + if ($memo->fetch($id) <= 0) { + $jsonResponse->msg = 'Memo not found'; + return false; + } + + if ($user->id != $memo->fk_user_creat && $memo->private) { + $jsonResponse->msg = $langs->trans('QuickMemoCantArchiveThisPrivateNote'); + return false; + } + + if ($memo->setArchived($user) < 0) { + $jsonResponse->result = 0; + $jsonResponse->msg = $langs->trans('UpdateError') . ' : ' . $memo->errorsToString(); + return false; + } else { + $jsonResponse->result = 1; + $jsonResponse->data = null; + return true; + } +} + +/** + * Transform an existing note into a template (model) for future use. + * @param JsonResponse $jsonResponse The response object. + * @return bool Returns false on failure, true on success. + */ +function quickMemoIntefaceActionCreateModel($jsonResponse) +{ + global $user, $langs, $db; + + if (!$user->hasRight('quickmemo', 'memo', 'write')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + return false; + } + + $id = GETPOSTINT("id"); + + if (empty($id) && !is_numeric($id)) { + $jsonResponse->msg = 'Need memo Id'; + return false; + } + + $memo = new Memo($db); + if ($memo->fetch($id) <= 0) { + $jsonResponse->msg = 'Memo not found'; + return false; + } + + if ($user->id != $memo->fk_user_creat && $memo->private) { + $jsonResponse->msg = $langs->trans('QuickMemoCantChangeThisPrivateNote'); + return false; + } + + $element_type = GETPOST("element_type"); + if (empty($element_type)) { + $memo->element_type = ''; + } + + $memo->status = Memo::STATUS_TPL; + $memo->private_tpl = GETPOST("tpl_private", "int"); + $memo->name_tpl = GETPOST("tpl_name"); + $memo->fk_user_creat = $user->id; + $memo->date_creation = dol_now(); + $memo->fk_user_modif = null; + $memo->date_modification = null; + $memo->fk_user_archived = null; + $memo->date_archived = null; + + if ($memo->update($user) < 0) { + $jsonResponse->result = 0; + $jsonResponse->msg = $langs->trans('UpdateError') . ' : ' . $memo->errorsToString(); + return false; + } else { + $jsonResponse->result = 1; + $jsonResponse->data = null; + return true; + } +} + + +/** + * Delete a memo template. + * @param JsonResponse $jsonResponse The response object. + * @return bool Returns false on failure, true on success. + */ +function quickMemoIntefaceActionDeleteModel($jsonResponse) +{ + global $user, $langs, $db; + + if (!$user->hasRight('quickmemo', 'memo', 'delete')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + return false; + } + + $id = GETPOSTINT("id"); + + if (empty($id) && !is_numeric($id)) { + $jsonResponse->msg = 'Need model Id'; + return false; + } + + $memo = new Memo($db); + if ($memo->fetch($id) <= 0) { + $jsonResponse->msg = 'Memo not found'; + return false; + } + + if ($memo->status != Memo::STATUS_TPL) { + $jsonResponse->msg = 'Not a model'; + return false; + } + + if ($user->id != $memo->fk_user_creat && $memo->private_tpl) { + $jsonResponse->msg = $langs->trans('QuickMemoCantDeleteThisPrivateModel'); + return false; + } + + if ($memo->delete($user) < 0) { + $jsonResponse->result = 0; + $jsonResponse->msg = $langs->trans('UpdateError') . ' : ' . $memo->errorsToString(); + return false; + } else { + $jsonResponse->result = 1; + $jsonResponse->data = null; + return true; + } +} + +/** + * Update template ranking after a drag & drop operation. + * + * This is intentionally NOT implemented as a simple single UPDATE + * on the moved row. + * + * The ranking system is based on a continuous and ordered sequence + * (rank_tpl) shared by all compatible templates (same context_tab + * and element_type). When one element moves, the relative position + * of the entire set may change. + * + * For this reason we: + * - Reload the full compatible dataset from database + * - Rebuild the ordered list in memory + * - Reinsert the moved element at its new visual position + * - Recalculate a clean, continuous ranking sequence + * - Persist the full sequence in a transaction + * + * This guarantees: + * - No duplicated ranks + * - No gaps in ranking + * - Deterministic ordering + * - Proper handling of private templates + * - Consistency in concurrent environments + * + * A single UPDATE on the moved row would inevitably produce + * rank collisions or inconsistent ordering over time. + * + * @param JsonResponse $jsonResponse The response object + * + * @return bool + */ +function quickMemoIntefaceActionUpdateModelRank($jsonResponse) +{ + global $user, $langs, $db; + + if (!$user->hasRight('quickmemo', 'memo', 'write')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + return false; + } + + $json = file_get_contents('php://input'); + $data = json_decode($json, true); + + if (!is_array($data) || empty($data['moved']['id']) || !isset($data['moved']['newPos'])) { + $jsonResponse->result = 0; + $jsonResponse->msg = 'INVALID MOVED DATA'; + return false; + } + + + + $movedId = (int) $data['moved']['id']; + $newPos = max(1, (int) $data['moved']['newPos']); + + $tmpMemo = new Memo($db); + + // 1 Retrieve the moved model + $sql = 'SELECT rowid, element_type, context_tab + FROM '.MAIN_DB_PREFIX.$tmpMemo->table_element.' + WHERE rowid = '. (int) $movedId.' + AND status = '. (int) Memo::STATUS_TPL; + + $res = $db->query($sql); + if (!$res || !$db->num_rows($res)) { + $jsonResponse->result = 0; + $jsonResponse->msg = 'MODEL NOT FOUND'; + return false; + } + + $movedModel = $db->fetch_object($res); + + // 2 Retrieve ALL compatible models + $sqlAll = 'SELECT rowid + FROM '.MAIN_DB_PREFIX.$tmpMemo->table_element.' + WHERE status = '. (int) Memo::STATUS_TPL.' + AND element_type IN (\''.$db->escape($movedModel->element_type).'\', \'\') + ORDER BY rank_tpl DESC'; + + // AND context_tab = \''.$db->escape($movedModel->context_tab).'\' + + $resAll = $db->query($sqlAll); + if (!$resAll) { + $jsonResponse->result = 0; + $jsonResponse->msg = $db->error(); + return false; + } + + $orderedIds = []; + while ($obj = $db->fetch_object($resAll)) { + $orderedIds[] = (int) $obj->rowid; + } + + // 3 Remove the moved ID + $orderedIds = array_values(array_diff($orderedIds, [$movedId])); + + // 4 Calculate actual index (0 based) + $newIndex = min(count($orderedIds), $newPos - 1); + + // 5 Insert at new position + array_splice($orderedIds, $newIndex, 0, [$movedId]); + + // 6 Clean re-indexing + $total = count($orderedIds); + $currentRank = $total; + + $db->begin(); + + foreach ($orderedIds as $id) { + $sqlUp = 'UPDATE '.MAIN_DB_PREFIX.$tmpMemo->table_element.' + SET rank_tpl = '.(int) $currentRank.' + WHERE rowid = '.(int) $id.' + AND status = '. (int) Memo::STATUS_TPL.' + AND (private_tpl = 0 OR fk_user_creat = '.(int) $user->id.')'; + + if (!$db->query($sqlUp)) { + $db->rollback(); + $jsonResponse->result = 0; + $jsonResponse->msg = $db->error(); + return false; + } + + $currentRank--; + } + + $db->commit(); + + $jsonResponse->result = 1; + $jsonResponse->data = null; + return true; +} +/** + * Permanently delete a note record from the database. + * @param JsonResponse $jsonResponse The response object. + * @return bool Returns false on failure, true on success. + */ +function quickMemoIntefaceActionDeleteNote($jsonResponse) +{ + global $user, $langs, $db; + + if (!$user->hasRight('quickmemo', 'memo', 'write')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + return false; + } + + $id = GETPOSTINT("id"); + + if (empty($id) && !is_numeric($id)) { + $jsonResponse->msg = 'Need memo Id'; + return false; + } + + $memo = new Memo($db); + if ($memo->fetch($id) <= 0) { + $jsonResponse->msg = 'Memo not found'; + return false; + } + + if ($memo->status == Memo::STATUS_TPL) { // In case of models need check other stuff + $jsonResponse->msg = 'Can\'t delete model'; + return false; + } + + if ($user->id != $memo->fk_user_creat && $memo->private) { + $jsonResponse->msg = $langs->trans('QuickMemoCantDeleteThisPrivateNote'); + return false; + } + + if ($memo->delete($user) < 0) { + $jsonResponse->result = 0; + $jsonResponse->msg = $langs->trans('UpdateError') . ' : ' . $memo->errorsToString(); + return false; + } else { + $jsonResponse->result = 1; + $jsonResponse->data = null; + return true; + } +} + + +/** + * Update the text content of an existing note. + * @param JsonResponse $jsonResponse The response object. + * @return bool Returns false on failure, true on success. + */ +function quickMemoIntefaceActionUpdateNote($jsonResponse) +{ + global $user, $langs, $db; + + if (!$user->hasRight('quickmemo', 'memo', 'write')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + return false; + } + + $id = GETPOSTINT("id"); + + if (empty($id) && !is_numeric($id)) { + $jsonResponse->msg = 'Need memo Id'; + return false; + } + + $memo = new Memo($db); + if ($memo->fetch($id) <= 0) { + $jsonResponse->msg = 'Memo not found'; + return false; + } + + $memo->quick_note = GETPOST("note", "alphanohtml"); + $memo->tms = dol_now(); + $memo->fk_user_modif = $user->id; + + if ($memo->update($user) < 0) { + $jsonResponse->result = 0; + $jsonResponse->msg = $langs->trans('UpdateError') . ' : ' . $memo->errorsToString(); + return false; + } else { + $jsonResponse->result = 1; + $jsonResponse->data = new stdClass(); + + // return new memo + $jsonResponse->data->memo = $memo->getJsMemo($user); + return true; + } +} + +/** + * Update the background color of a memo. + * @param JsonResponse $jsonResponse The response object. + * @return bool Returns false on failure, true on success. + */ +function quickMemoIntefaceActionUpdateColor($jsonResponse) +{ + global $user, $langs, $db; + + if (!$user->hasRight('quickmemo', 'memo', 'write')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + return false; + } + + $id = GETPOSTINT("id"); + + if (empty($id) && !is_numeric($id)) { + $jsonResponse->msg = 'Need memo Id'; + return false; + } + + $color = GETPOST("color"); + if (!Memo::checkColor($color)) { + $jsonResponse->msg = 'Need valide Color'; + return false; + } + + $memo = new Memo($db); + if ($memo->fetch($id) <= 0) { + $jsonResponse->msg = 'Memo not found'; + return false; + } + + if ($user->id != $memo->fk_user_creat && $memo->private) { + $jsonResponse->msg = $langs->trans('QuickMemoCantChangeThisPrivateNote'); + return false; + } + + $memo->color = $color; + + if (!$memo->update($user) < 0) { + $jsonResponse->result = 0; + $jsonResponse->msg = $langs->trans('UpdateError') . ' : ' . $memo->errorsToString(); + return false; + } else { + $jsonResponse->result = 1; + $jsonResponse->data = new stdClass(); + + // return new memo + $jsonResponse->data->memo = $memo->getJsMemo($user); + return true; + } +} + +/** + * Toggle visibility: Shared globally on the context or restricted to current element. + * @param JsonResponse $jsonResponse The response object. + * @return bool Returns false on failure, true on success. + */ +function quickMemoIntefaceActionUpdateSharedOnElement($jsonResponse) +{ + global $user, $langs, $db; + + if (!$user->hasRight('quickmemo', 'memo', 'write')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + return false; + } + + $id = GETPOSTINT("id"); + + if (empty($id) && !is_numeric($id)) { + $jsonResponse->msg = 'Need memo Id'; + return false; + } + + $shared_on_element = GETPOST("shared_on_element", "int"); + + $memo = new Memo($db); + if ($memo->fetch($id) <= 0) { + $jsonResponse->msg = 'Memo not found'; + return false; + } + + if ($user->id != $memo->fk_user_creat && $memo->private) { + $jsonResponse->msg = $langs->trans('QuickMemoCantChangeThisPrivateNote'); + return false; + } + + $memo->shared_on_element = $shared_on_element ? 1 : 0; + + if (!$memo->update($user) < 0) { + $jsonResponse->result = 0; + $jsonResponse->msg = $langs->trans('UpdateError') . ' : ' . $memo->errorsToString(); + return false; + } else { + $jsonResponse->result = 1; + $jsonResponse->data = null; + $jsonResponse->data = new stdClass(); + + // return new memo + $jsonResponse->data->memo = $memo->getJsMemo($user); + return true; + } +} + + +/** + * Toggle private status (visible only to creator vs shared). + * @param JsonResponse $jsonResponse The response object. + * @return bool Returns false on failure, true on success. + */ +function quickMemoIntefaceActionUpdatePrivate($jsonResponse) +{ + global $user, $langs, $db; + + if (!$user->hasRight('quickmemo', 'memo', 'write')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + return false; + } + + $id = GETPOSTINT("id"); + + if (empty($id) && !is_numeric($id)) { + $jsonResponse->msg = 'Need memo Id'; + return false; + } + + $private = GETPOST("private", "int"); + + $memo = new Memo($db); + if ($memo->fetch($id) <= 0) { + $jsonResponse->msg = 'Memo not found'; + return false; + } + + if ($user->id != $memo->fk_user_creat && $memo->private) { + $jsonResponse->msg = $langs->trans('QuickMemoCantChangeThisPrivateNote'); + return false; + } + + $memo->private = $private ? 1 : 0; + + if (!$memo->update($user) < 0) { + $jsonResponse->result = 0; + $jsonResponse->msg = $langs->trans('UpdateError') . ' : ' . $memo->errorsToString(); + return false; + } else { + $jsonResponse->result = 1; + $jsonResponse->data = new stdClass(); + + // return new memo + $jsonResponse->data->memo = $memo->getJsMemo($user); + return true; + } +} + +/** + * List available template models and standard color presets. + * @param JsonResponse $jsonResponse The response object. + * @return bool|void Returns false on failure. + */ +function quickMemoIntefaceActionListModels($jsonResponse) +{ + global $user, $langs, $db; + + if (!$user->hasRight('quickmemo', 'memo', 'read')) { + $jsonResponse->msg = $langs->trans('NotEnoughRights'); + $jsonResponse->result = 0; + return false; + } + + $element_type = GETPOST('element_type', 'alpha'); + $context = GETPOST('context', 'alpha'); + + $jsonResponse->data = new stdClass(); + $jsonResponse->data->modelTemplate = []; + $jsonResponse->data->presetTemplate = []; + + // Get standard color list presets + $colorList = Memo::getColorPreset(); + + foreach ($colorList as $color) { + $default = new stdClass(); + $default->name = ''; + $default->color = $color; + $default->note = ''; + $default->pos_w = 0; + $default->pos_h = 0; + $default->pos_x = 0; + $default->pos_y = 0; + $default->shared_on_element = 0; + $default->private = 0; + $default->user_name = $user->getFullName($langs); + $default->date_creation = dol_print_date(dol_now()); + $default->date_change = ''; + $default->user_change_name = ''; + + + $jsonResponse->data->presetTemplate[] = $default; + } + + // GET all memo templates (tpl) + $memoStatic = new Memo($db); + $sql = $memoStatic->getTemplateMemosQuery($element_type, $context); + $resql = $db->query($sql); + if (!$resql) { + $jsonResponse->result = 0; + $jsonResponse->msg = $db->lasterror(); + return; + } + + while ($obj = $db->fetch_object($resql)) { + // fallback user-specific position + $jsonResponse->data->modelTemplate[] = quickMemoInterfacePopulateMemoTplFromQueryObj($obj); + } + + $jsonResponse->result = 1; +} + +/** + * List active notes for a specific object (element_id) or global context. + * @param JsonResponse $jsonResponse The response object. + * @return void + */ +function quickMemoIntefaceActionList($jsonResponse) +{ + global $user, $langs, $db; + + if (!$user->hasRight('quickmemo', 'memo', 'read')) { + $jsonResponse->msg = $langs->trans('NotEnoughPermissions'); + $jsonResponse->result = 0; + return; + } + + $element_id = GETPOSTINT('element_id'); + $element_type = GETPOST('element_type', 'alpha'); + $context = GETPOST('context', 'alpha'); + $jsonResponse->data = new stdClass(); + $jsonResponse->data->memos = []; + $jsonResponse->data->nbArchives = 0; + + if (empty($element_id) && !empty($element_type)) { + $jsonResponse->msg = 'Need element_id '; + $jsonResponse->result = 0; + return; + } + + $staticMemo = new Memo($db); + + // GET all active memos + $sql = $staticMemo->getMemosQuery($element_type, $element_id, $context); + $resql = $db->query($sql); + if (!$resql) { + $jsonResponse->result = 0; + $jsonResponse->msg = $db->lasterror(); + return; + } + + + $memos = []; + while ($obj = $db->fetch_object($resql)) { + // fallback user-specific position + $memos[] = quickMemoInterfacePopulateMemoFromQueryObj($obj); + } + + $jsonResponse->data->memos = $memos; + + // Count archived notes for display + $nbArchives = $staticMemo->countArchivedMemoQuery($element_type, $element_id, $context); + if ($nbArchives === false) { + $jsonResponse->result = 0; + $jsonResponse->msg = 'Error count archive'; + return; + } + + $jsonResponse->data->nbArchives = $nbArchives; + + $jsonResponse->result = 1; +} + + +/** + * Helper to populate a JS-friendly memo object from a database record. + * @param object $obj Database record object. + * @return stdClass The populated JS-ready memo object. + */ +function quickMemoInterfacePopulateMemoFromQueryObj($obj) +{ + global $db, $langs; + $obj->date_creation = $db->jdate($obj->date_creation); + $obj->tms = $db->jdate($obj->tms); + + $memo = Memo::getJsMemoDefault(); + $memo->id = $obj->rowid; + $memo->color = $obj->color; + $memo->note = $obj->quick_note; + // Use user-specific position if available, otherwise fallback to default + $memo->pos_x = $obj->user_pos_x !== null ? (int) $obj->user_pos_x : (int) $obj->pos_x; + $memo->pos_y = $obj->user_pos_y !== null ? (int) $obj->user_pos_y : (int) $obj->pos_y; + $memo->pos_w = $obj->user_pos_w !== null ? (int) $obj->user_pos_w : (int) $obj->pos_w; + $memo->pos_h = $obj->user_pos_h !== null ? (int) $obj->user_pos_h : (int) $obj->pos_h; + $memo->pos_z = $obj->user_pos_z !== null ? (int) $obj->user_pos_z : (int) $obj->pos_z; + + $memo->shared_on_element = $obj->shared_on_element; + $memo->private = (int) $obj->private; + $memo->date_creation = dol_print_date($obj->date_creation, '%d/%m/%Y %H:%M'); + $memo->date_change = ''; + if (!empty($obj->tms) && ((int) $obj->date_creation !== (int) $obj->tms || (int) $obj->fk_user_modif > 0)) { + $memo->date_change = dol_print_date($obj->tms, '%d/%m/%Y %H:%M'); + } + + $memo->fk_user_creat = $obj->fk_user_creat; + $memo->user_name = ''; + if ((int) $obj->fk_user_creat > 0) { + $userCreate = new User($db); + if ($userCreate->fetch((int) $obj->fk_user_creat) > 0) { + $memo->user_name = $userCreate->getFullName($langs); + } + } + + $memo->fk_user_modif = $obj->fk_user_modif; + $memo->user_change_name = ''; + if ((int) $obj->fk_user_modif > 0) { + $userMod = new User($db); + if ($userMod->fetch((int) $obj->fk_user_modif) > 0) { + $memo->user_change_name = $userMod->getFullName($langs); + } + } + + return $memo; +} + +/** + * Helper to populate a JS-friendly template (model) object from a database record. + * @param object $obj Database record object. + * @return stdClass The populated JS-ready template object. + */ +function quickMemoInterfacePopulateMemoTplFromQueryObj($obj) +{ + global $db, $langs, $user; + $obj->date_creation = $db->jdate($obj->date_creation); + $obj->tms = $db->jdate($obj->tms); + + + $memo = new stdClass(); + $memo->name = $obj->name_tpl; + $memo->id = $obj->rowid; + $memo->color = $obj->color; + $memo->note = $obj->quick_note; + $memo->pos_x = $obj->user_pos_x !== null ? (int) $obj->user_pos_x : (int) $obj->pos_x; + $memo->pos_y = $obj->user_pos_y !== null ? (int) $obj->user_pos_y : (int) $obj->pos_y; + $memo->pos_w = $obj->user_pos_w !== null ? (int) $obj->user_pos_w : (int) $obj->pos_w; + $memo->pos_h = $obj->user_pos_h !== null ? (int) $obj->user_pos_h : (int) $obj->pos_h; + $memo->pos_z = $obj->user_pos_z !== null ? (int) $obj->user_pos_z : (int) $obj->pos_z; + $memo->rank_tpl = (int) $obj->rank_tpl; + + $memo->shared_on_element = $obj->shared_on_element; + $memo->private = (int) $obj->private; + $memo->date_creation = dol_print_date($obj->date_creation, '%d/%m/%Y %H:%M'); + $memo->fk_user_creat = $user->id; + $memo->user_name = $user->getFullName($langs); + $memo->date_creation = dol_print_date(dol_now()); + $memo->date_change = ''; + $memo->user_change_name = ''; + + return $memo; +} diff --git a/htdocs/quickmemo/js/QuickMemo.js b/htdocs/quickmemo/js/QuickMemo.js new file mode 100644 index 00000000000..8a55fcfc902 --- /dev/null +++ b/htdocs/quickmemo/js/QuickMemo.js @@ -0,0 +1,2816 @@ +/** + * QuickMemo Class + * Manages interactive sticky notes (memos) with drag-and-drop, resizing, + * Markdown support, and server-side persistence. + */ +class QuickMemo { + + /** + * @constructor + * @param {Object} param - Configuration parameters for the instance. + */ + constructor(param = {}) { + + /** + * @type {Object} defaultParams - Default configuration values + */ + const defaultParams = { + interfaceUrl: '', + archivesUrl: false, + userWriteRight: false, + userDeleteRight: false, + elementId: 0, + autoResizeFontSize: true, + elementType: '', + context: '', + token: '', + colors: ['#fff8a6', '#ffd6d6', '#d6ffd9', '#d6e6ff', '#f3d6ff', '#ffffff', '#f5f5f5'], + publicFontAIcon: 'far fa-eye', + privateFontAIcon: 'far fa-eye-slash', + archiveFontAIcon: 'far fa-trash-alt', + sharedFontAIcon: 'far fa-copy', + notSharedFontAIcon: 'far fa-file', + modelFontAIcon: 'far fa-share-square', + menuDropDownId: 'quickmemo-create-dropdown', + menuDropDownModelListContainerId: 'quickmemo-model-list', + menuDropDownPresetListContainerId: 'quickmemo-preset-list' + }; + + // Merge default parameters with user-provided parameters + this.param = {...defaultParams, ...param}; + + /** @type {number} countedArchivedMemo - Local counter for archived notes */ + this.countedArchivedMemo = 0; + + // Validation of required parameters + if (!this.param.interfaceUrl || (!this.param.elementId && this.param.elementType !== '')) { + console.warn('QuickMemo: missing required parameters'); + return; + } + + /** @type {HTMLElement} container - Global container (body) */ + this.container = document.body; + + /** @type {number} currentZ - Initial z-index for notes */ + this.currentZ = 200; + + /** @type {Array} memos - Stores objects containing {memoData, domElement} */ + this.memos = []; + + this.init(); + } + + /** + * Initializes the component by loading languages, fetching data, and setting up events. + * @async + */ + async init() { + // Load translation files via Dolibarr tools + await Dolibarr.tools.langs.load('quickmemo'); + await Dolibarr.tools.langs.load('main'); + await Dolibarr.tools.langs.load('other'); + + // Load existing memos from server + this.loadMemos(); + + // Set initial z-indexes based on stored position + this.memos.forEach((m, i) => { + // Default pos_z if it does not exist + if (!('pos_z' in m.memo) || m.memo.pos_z < 1) m.memo.pos_z = i + 1; + // z-index CSS + m.el.style.zIndex = this.currentZ + m.memo.pos_z; + }); + + // Ensure notes stay within viewport on window resize + window.addEventListener('resize', () => this.ensureAllVisible()); + + // Initialize top-bar menu if user has write permissions + if (this.param.userWriteRight) { + this.initMenuMemoDropdown(); + } + + // Setup global shortcut behaviors (Escape key) + this.escapeKeyBehavior(); + } + + /** + * Manages the Escape key behavior to hide/show notes with animations. + */ + escapeKeyBehavior() { + let escTimer = null; + let escActivated = false; + + /** Hides all notes by setting display to none */ + function applyDisplayNone() { + document.querySelectorAll('.quickmemo-note').forEach(el => { + el.style.display = 'none'; + }); + } + + /** Restores notes visibility */ + function removeDisplayNone() { + document.querySelectorAll('.quickmemo-note').forEach(el => { + el.style.display = ''; + }); + } + + // Keydown handler: triggers after a delay to hide notes + document.addEventListener('keydown', function (e) { + if (e.key === 'Escape' && !escTimer) { + escTimer = setTimeout(function () { + document.body.classList.add('hide-quickmemo'); + escActivated = true; + + // Single global listener + document.addEventListener('transitionend', function handler(ev) { + if (ev.target.classList.contains('quickmemo-note')) { + applyDisplayNone(); + document.removeEventListener('transitionend', handler); + } + }); + + }, 300); + } + }); + + // Keyup handler: restores notes when Escape is released + document.addEventListener('keyup', function (e) { + if (e.key === 'Escape') { + clearTimeout(escTimer); + escTimer = null; + + if (escActivated) { + removeDisplayNone(); + + requestAnimationFrame(() => { + document.body.classList.remove('hide-quickmemo'); + }); + + escActivated = false; + } + } + }); + } + + /* =============================== + LOAD + ================================= */ + + /** + * Fetches memos from the server and renders them. + * @async + */ + async loadMemos() { + try { + + const res = await fetch(this.param.interfaceUrl + '?action=list', { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({ + element_id: this.param.elementId, + element_type: this.param.elementType, + context: this.param.context, + token: this.param.token + }) + }); + + const json = await res.json(); + + if (!json.result) { + throw new Error(json.msg); + } + + // Render each fetched memo + json.data.memos.forEach(memo => this.renderMemo(memo)); + // Update the UI with the archive count + this.setArchivesNb(json.data.nbArchives); + + } catch (err) { + Dolibarr.tools.setEventMessage(Dolibarr.tools.langs.trans('QuickMemoLoadMemosError') + ' : ' + err, 'errors'); + console.error('QuickMemo load error', err); + } + } + + /** + * Updates the internal counter and the DOM badge for archived memos. + * @param {number|string} nb - Number of archived items. + */ + setArchivesNb(nb) { + this.countedArchivedMemo = parseInt(nb); + + // Update badge + if (document.getElementById('quick-note-archives-link-mumber')) { + const nbArchiveBadge = document.getElementById('quick-note-archives-link-mumber'); + nbArchiveBadge.textContent = this.countedArchivedMemo; + } + } + + /** + * Finds the memo data object associated with a DOM element. + * @param {HTMLElement} el + * @returns {Object|boolean} + */ + getMemoFromElement(el) { + const m = this.memos.find(x => x.el === el); + if (!m) return false; + return m; + } + + /** + * Places the selected note at the end of the stack and re-indexes all notes from 1 to N. + * @param {HTMLElement} el + */ + bringToTop(el) { + const m = this.getMemoFromElement(el); + if (!m) return; + + // 1. Sort all notes by their current z-index + const sortedMemos = [...this.memos].sort((a, b) => + (parseInt(a.memo.pos_z) || 0) - (parseInt(b.memo.pos_z) || 0) + ); + + // 2. Remove the current note from its position and push it to the end (the top) + const others = sortedMemos.filter(x => x !== m); + others.push(m); + + // 3. Re-assign clean indexes (1 to N) to everyone + others.forEach((x, i) => { + const newZ = i + 1; + x.memo.pos_z = newZ; + x.el.style.zIndex = this.currentZ + newZ; + }); + + } + + + /* =============================== + RENDER + ================================= */ + + /** + * Creates and appends the DOM structure for a memo. + * @async + * @param {Object} memo - The data object for the note. + * @returns {HTMLElement} The created note element. + */ + async renderMemo(memo) { + + const note = document.createElement('div'); + this.memos.push({memo, el: note}); + + note.className = 'quickmemo-note'; + note.dataset.id = memo.id; + + + let posX = parseInt(memo.pos_x); + let posY = parseInt(memo.pos_y); + let posW = parseInt(memo.pos_w); + let posH = parseInt(memo.pos_h); + + const containerWidth = this.container.clientWidth; + + // Prevent note from appearing outside of the viewport + if (posX + posW > containerWidth) { + posX = Math.max(32, containerWidth - posW - 32); + } + + note.style.position = 'absolute'; + note.style.left = posX + 'px'; + note.style.top = posY + 'px'; + note.style.width = posW + 'px'; + note.style.height = posH + 'px'; + // note.style.background = memo.color || '#fff8a6'; + // note.style.setProperty('--memo-color', memo.color || '#fff8a6'); + this.setMemoColor(note, memo.color); + if (parseInt(memo.id) === 0) { // Uniquement pour les nouvelles notes en cours de création + const maxZ = this.memos.length > 0 ? Math.max(...this.memos.map(x => parseInt(x.memo.pos_z) || 0)) : 0; + memo.pos_z = maxZ + 1; + } + note.style.zIndex = (this.currentZ || 0) + parseInt(memo.pos_z); + + + const noteHeader = document.createElement('div'); + noteHeader.className = 'quickmemo-header'; + + /* ================= MEMO FOOTER & ACTIONS ================= */ + + const noteFooter = document.createElement('div'); + noteFooter.className = 'quickmemo-footer'; + + const meta = document.createElement('div'); + meta.className = 'quickmemo-meta'; + const hasDateChange = memo.date_change && memo.date_change.trim() !== '' && memo.date_creation !== memo.date_change; + const hasUserChange = memo.user_change_name && memo.user_change_name.trim() !== '' && memo.user_name !== memo.user_change_name; + + let updateBlock = ''; + + // Template for "Modified on/by" information + updateBlock = ` + + ${hasDateChange ? ` + + ${await Dolibarr.tools.langs.trans('QuickMemoModified')} : ${memo.date_change} + + ` : ''} + ${hasUserChange ? ` + + ${await Dolibarr.tools.langs.trans('QuickMemoBy')} ${memo.user_change_name} + + ` : ''} + + `; + + + meta.innerHTML = ` +
+ + ${memo.user_name || ''} + ${memo.date_creation || ''} + + ${updateBlock} +
+ `; + + const actions = document.createElement('div'); + actions.className = 'quickmemo-actions'; + + /* ===== ARCHIVE ===== */ + + const btnArchive = document.createElement('button'); + btnArchive.className = 'btn-low-emphasis --btn-icon quickmemo-btn-archive'; + btnArchive.innerHTML = ``; + btnArchive.title = await Dolibarr.tools.langs.transNoEntities('QuickMemoActionArchive'); + this.initTooltips(btnArchive); + btnArchive.addEventListener('click', async (e) => { + e.stopPropagation(); + this.removeTooltips(btnArchive); // JQUERY tooltip need to be destroy because it active at this moment + + try { + // If empty, delete permanently, otherwise archive + const textarea = note.querySelector('textarea'); + const actionDelete = textarea.value.length ? 'archive' : 'delete'; + + if (actionDelete === 'delete') { + this.deleteWithAnimation(note); + } else { + this.archiveWithAnimation(note); + } + + const res = await fetch(this.param.interfaceUrl + '?action=' + actionDelete, { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({ + id: note.dataset.id, + token: this.param.token + }) + }); + + const json = await res.json(); + + if (!json.result) { + throw new Error(json.msg); + } + + this.memos = this.memos.filter(m => m.el !== note); + } catch (err) { + Dolibarr.tools.setEventMessage(Dolibarr.tools.langs.trans('QuickMemoArchiveError') + ' : ' + err, 'errors'); + console.error('QuickMemo archive error', err); + } + }); + + /* ===== TOGGLE SHARING ===== */ + + const btnShare = document.createElement('button'); + btnShare.className = 'btn-low-emphasis --btn-icon quickmemo-btn-share'; + btnShare.title = await Dolibarr.tools.langs.transNoEntities('QuickMemoActionShareMode'); + this.initTooltips(btnShare); + + + /** Updates icon based on sharing status */ + const updateShareIcon = async () => { + note.setAttribute('data-shared', parseInt(memo.shared_on_element)); + btnShare.title = await Dolibarr.tools.langs.transNoEntities(memo.shared_on_element == 1 ? 'QuickMemoActionShareModeActive' : 'QuickMemoActionShareModeNotActive'); + btnShare.innerHTML = ``; + + this.initTooltips(btnShare); + }; + + updateShareIcon(); + + btnShare.addEventListener('click', async (e) => { + e.stopPropagation(); + + memo.shared_on_element = memo.shared_on_element == 1 ? 0 : 1; + + updateShareIcon(); + + await fetch(this.param.interfaceUrl + '?action=update-shared-on-element', { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({ + id: note.dataset.id, + shared_on_element: memo.shared_on_element, + token: this.param.token + }) + }); + }); + + + /* ===== SET AS TEMPLATE ===== */ + const btnCreateModel = document.createElement('button'); + btnCreateModel.className = 'btn-low-emphasis --btn-icon'; + btnCreateModel.innerHTML = ``; + btnCreateModel.title = await Dolibarr.tools.langs.transNoEntities('QuickMemoCreateAModelFromThisMemo'); + this.initTooltips(btnCreateModel); + + btnCreateModel.addEventListener('click', () => this.openCreateModelDialog(memo, note)); + + /* ===== TOGGLE PRIVATE ===== */ + + const btnPrivate = document.createElement('button'); + btnPrivate.className = 'btn-low-emphasis --btn-icon quickmemo-btn-private'; + btnPrivate.title = await Dolibarr.tools.langs.transNoEntities('QuickMemoActionPrivateMode'); + this.initTooltips(btnPrivate); + + /** Updates icon based on privacy status */ + const updatePrivateIcon = async () => { + note.setAttribute('data-private', parseInt(memo.private)); + + btnPrivate.title = await Dolibarr.tools.langs.transNoEntities(memo.private == 1 ? 'QuickMemoActionPrivateModeActive' : 'QuickMemoActionPrivateModeNotActive'); + btnPrivate.innerHTML = ``; + this.initTooltips(btnPrivate); + }; + + updatePrivateIcon(); + + btnPrivate.addEventListener('click', async (e) => { + e.stopPropagation(); + + memo.private = parseInt(memo.private) === 1 ? 0 : 1; // Toggle private status + + updatePrivateIcon(); + + await fetch(this.param.interfaceUrl + '?action=update-private', { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({ + id: note.dataset.id, + private: memo.private, + token: this.param.token + }) + }); + }); + + /* ===== COLOR PICKER ===== */ + + const colorListId = 'quickmemo-color-list'; + + // Create a datalist for predefined colors if not already existing + if (!document.getElementById(colorListId)) { + const datalist = document.createElement('datalist'); + datalist.id = colorListId; + + this.param.colors.forEach(c => { + const option = document.createElement('option'); + option.value = c; + datalist.appendChild(option); + }); + + document.body.appendChild(datalist); + } + + const colorInput = document.createElement('input'); + colorInput.type = 'color'; + colorInput.className = 'quickmemo-color-input'; + colorInput.value = memo.color || '#fff8a6'; + colorInput.setAttribute('list', colorListId); + colorInput.title = await Dolibarr.tools.langs.trans('QuickMemoActionChangeColor'); + this.initTooltips(colorInput); + + colorInput.addEventListener('click', e => { + e.stopPropagation(); // prevent triggering drag + }); + + colorInput.addEventListener('input', async (e) => { + e.stopPropagation(); + + const newColor = e.target.value; + // note.style.background = newColor; + // note.style.setProperty('--memo-color', newColor); + this.setMemoColor(note, newColor); + memo.color = newColor; + + await fetch(this.param.interfaceUrl + '?action=update-color', { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({ + id: note.dataset.id, + color: memo.color, + token: this.param.token + }) + }); + }); + + // Append buttons based on permissions + if (this.param.userWriteRight) { + actions.appendChild(btnPrivate); + actions.appendChild(btnShare); + actions.appendChild(colorInput); + actions.appendChild(btnCreateModel); + } + + if (this.param.userDeleteRight) { + actions.appendChild(btnArchive); + } + + noteHeader.appendChild(actions); + note.appendChild(noteHeader); + + noteFooter.appendChild(meta); + + /* ================= TEXTAREA ================= */ + + const textarea = document.createElement('textarea'); + textarea.value = memo.note || ''; + if (!this.param.userWriteRight) { + textarea.readOnly = true; + } + + textarea.placeholder = await Dolibarr.tools.langs.transNoEntities('QuickMemoEnterNote'); + textarea.addEventListener('input', () => this.adjustFontSize(note)); + note.appendChild(textarea); + + + // MARKDOWN PREVIEW + const preview = document.createElement('div'); + preview.className = 'quickmemo-markdown-preview'; + note.appendChild(preview); + if (!textarea.value) { + // Dynamically retrieve the placeholder + const ph = textarea.getAttribute('placeholder') || ''; + await this.renderPreview(preview, `${ph}`, false); + } else { + await this.renderPreview(preview, textarea.value); + } + + + /** Toggles between edit mode (textarea) and view mode (markdown) */ + const setEditMode = (edit) => { + note.classList.toggle('--edit-mode', edit); + // set focus on textarea on edit mode + if (edit) textarea.focus(); + }; + + textarea.addEventListener('focus', () => setEditMode(true)); + textarea.addEventListener('blur', async (e) => { + + // Check if the focus is moving to a toolbar button + if (e.relatedTarget && e.relatedTarget.closest('.quickmemo-editor-toolbar')) { + return; // Do nothing, keep --edit-mode active + } + + // Otherwise, close edit mode + setTimeout(async () => { + // ... votre logique de preview ... + setEditMode(false); // This will automatically hide the toolbar via CSS + }, 150); + + if (!textarea.value) { + // Dynamically retrieve the placeholder + const ph = textarea.getAttribute('placeholder') || ''; + await this.renderPreview(preview, `${ph}`, false); + } else { + await this.renderPreview(preview, textarea.value); + } + + }); + + // Interaction with the preview (checkboxes and links) + preview.addEventListener('click', async (e) => { + const target = e.target; + + // If a link is clicked or inside a link + if (target.closest('a')) { + e.stopPropagation(); // Prevent setEditMode + return; + } else if (target.classList.contains('markdown-checkbox')) { + const lineNumber = target.closest('[data-line]').dataset.line; + const lines = textarea.value.split('\n'); + const line = lines[lineNumber]; + const todoMatch = line.match(/^\[([ xX])\] (.*)$/); + if (!todoMatch) return; + + const checked = todoMatch[1].toLowerCase() === 'x'; + lines[lineNumber] = `[${checked ? ' ' : 'x'}] ${todoMatch[2]}`; + textarea.value = lines.join('\n'); + + // Re-render preview + await this.renderPreview(preview, textarea.value); + + // trigger envent input for bindSave + const inputEvent = new Event('input', {bubbles: true}); + textarea.dispatchEvent(inputEvent); + + e.stopPropagation(); // Prevent setEditMode + } else { + setEditMode(true) + } + }); + + + const editorToolbar = document.createElement('div'); + editorToolbar.className = 'quickmemo-editor-toolbar'; + + + const btnBold = this.createToolbarButton(textarea,editorToolbar,'bold', 'fa-bold', Dolibarr.tools.langs.transNoEntities('Bold')); + const btnItalic = this.createToolbarButton(textarea,editorToolbar,'italic', 'fa-italic', Dolibarr.tools.langs.transNoEntities('Italic')); + const btnUnderline = this.createToolbarButton(textarea,editorToolbar,'underline', 'fa-underline', Dolibarr.tools.langs.transNoEntities('Underline')); + const btnH1 = this.createToolbarButton(textarea,editorToolbar,'h1', 'fa-heading', Dolibarr.tools.langs.transNoEntities('H1'), '1'); + const btnH2 = this.createToolbarButton(textarea,editorToolbar,'h2', 'fa-heading', Dolibarr.tools.langs.transNoEntities('H2'), '1'); + const btnH3 = this.createToolbarButton(textarea,editorToolbar,'h3', 'fa-heading', Dolibarr.tools.langs.transNoEntities('H3'), '1'); + const btnCheck = this.createToolbarButton(textarea,editorToolbar,'task', 'fa-check-square', Dolibarr.tools.langs.transNoEntities('Checkbox')); + + this.createToolbarSeparator(editorToolbar) + + const btnEditorHelp = document.createElement('button'); + btnEditorHelp.type = 'button'; + btnEditorHelp.className = 'quickmemo-toolbar-btn'; + btnEditorHelp.innerHTML = ``; + btnEditorHelp.title = Dolibarr.tools.langs.transNoEntities('Help'); + //
${this.getMarkDownHelp()}
+ editorToolbar.appendChild(btnEditorHelp); + + btnEditorHelp.addEventListener('click', () => { + const confirmOptions = { + title: Dolibarr.tools.langs.trans('QuickMemoEnterNoteMdCompabible'), + confirmLabel: Dolibarr.tools.langs.trans('CloseDialog'), + customClass: 'dialog-lg', + }; + this.openSimpleDialog(this.getMarkDownHelp(), confirmOptions); + }); + + + note.appendChild(editorToolbar); + + + textarea.addEventListener('keyup', () => this.updateToolbarState(textarea, editorToolbar)); + textarea.addEventListener('click', () => this.updateToolbarState(textarea, editorToolbar)); + textarea.addEventListener('select', () => this.updateToolbarState(textarea, editorToolbar)); + textarea.addEventListener('focus', () => this.updateToolbarState(textarea, editorToolbar)); + + // END MARKDOWN + + + note.appendChild(noteFooter); + + this.container.appendChild(note); + this.adjustFontSize(note); + + const state = {isResizing: false}; + + // Enable drag, resize and auto-save + this.makeDraggable(note, state); + this.makeResizable(note, memo, state); + this.bindSave(textarea, note); + + + return note; + } + + createToolbarSeparator(toolbar, autoAppend = true) { + const btn = document.createElement('hr'); + btn.className = 'quickmemo-toolbar-separator'; + + if(autoAppend) { + toolbar.appendChild(btn); + } + + return btn; + } + + createToolbarButton(textarea,toolbar, type, iconClass, title, autoAppend = true) { + const btn = document.createElement('button'); + btn.type = 'button'; + btn.className = 'quickmemo-toolbar-btn'; + btn.dataset.type = type; + let sub = ''; + if(type === 'h1') { + sub = '1'; + }else if(type === 'h2'){ + sub = '2'; + }else if(type === 'h3'){ + sub = '3'; + } + + btn.innerHTML = `${sub}`; + btn.title = title; + + // On empêche le bouton de voler le focus définitivement, + // mais on le laisse être le "relatedTarget" + btn.addEventListener('mousedown', (e) => { + e.preventDefault(); // Empêche le curseur de quitter le textarea + this.applyMarkdown(textarea, type, toolbar); + }); + + if(autoAppend) { + toolbar.appendChild(btn); + } + + return btn; + + } + + /** + * Converts raw text into Markdown HTML and updates the preview area. + * @async + * @param {HTMLElement} preview - The preview container. + * @param {string} txt - The source text. + * @param {boolean} convertMd - Whether to apply markdown conversion. + */ + async renderPreview(preview, txt, convertMd = true) { + // Re-render preview + preview.innerHTML = convertMd ? await this.simpleMarkdown(txt) : txt; + + const badge = document.createElement('span'); + badge.classList.add('quickmemo-markdown-preview__badge'); + const checkboxes = preview.querySelectorAll('input[type="checkbox"]'); + + const total = checkboxes.length; + + if (total === 0) { + return; + } + + const checked = preview.querySelectorAll('input[type="checkbox"]:checked').length; + + badge.textContent = checked + " / " + total; + + if (checked === total) { + badge.classList.add("success"); + } else { + badge.classList.remove("success"); + } + + preview.prepend(badge); + } + + /** + * Visual effect: note flies towards the archive button and disappears. + * @param {HTMLElement} note + */ + archiveWithAnimation(note) { + + const target = document.getElementById(this.param.menuDropDownId); + if (!target) { + note.remove(); + return; + } + + const noteRect = note.getBoundingClientRect(); + const targetRect = target.getBoundingClientRect(); + + const deltaX = targetRect.left - noteRect.left; + const deltaY = targetRect.top - noteRect.top; + + // Set current size to prevent jumps effect + note.style.width = noteRect.width + 'px'; + note.style.height = noteRect.height + 'px'; + + note.style.position = 'fixed'; + note.style.left = noteRect.left + 'px'; + note.style.top = noteRect.top + 'px'; + note.style.margin = 0; + note.style.zIndex = 99999; + + note.style.transition = 'transform 400ms ease, opacity 400ms ease'; + note.style.transformOrigin = 'top left'; + + requestAnimationFrame(() => { + note.style.transform = ` + translate(${deltaX}px, ${deltaY}px) + scale(0.2) + `; + note.style.opacity = '0'; + }); + + note.addEventListener('transitionend', () => { + note.remove(); + this.setArchivesNb(this.countedArchivedMemo + 1); + }, {once: true}); + } + + + /** + * Visual effect: note flies towards the template list when a model is created. + * @param {Object} memo + * @param {HTMLElement} note + */ + convertToModelWithAnimation(memo, note) { + + const dropDown = document.getElementById(this.param.menuDropDownId); + if (!dropDown) { + note.remove(); + return; + } + + + const modelListDiv = document.getElementById(this.param.menuDropDownModelListContainerId); + if (!modelListDiv) { + note.remove(); + return; + } + + if (!memo) { + note.remove(); + return; + } + + + setTimeout(async () => { + await this.fetchMenuDropDown(); + dropDown.classList.add('open'); + + const target = document.createElement('div'); + target.className = 'quickmemo-model-placeholder'; + modelListDiv.appendChild(target); + + + const noteRect = note.getBoundingClientRect(); + const targetRect = target.getBoundingClientRect(); + + const deltaX = targetRect.left - noteRect.left; + const deltaY = targetRect.top - noteRect.top; + + // Set current size to prevent jumps effect + note.style.width = noteRect.width + 'px'; + note.style.height = noteRect.height + 'px'; + + note.style.position = 'fixed'; + note.style.left = noteRect.left + 'px'; + note.style.top = noteRect.top + 'px'; + note.style.margin = 0; + note.style.zIndex = 99999; + + note.style.transition = 'transform 400ms ease, opacity 400ms ease'; + note.style.transformOrigin = 'top left'; + + requestAnimationFrame(() => { + note.style.transform = ` + translate(${deltaX}px, ${deltaY}px) + scale(0.2) + `; + note.style.opacity = '0'; + }); + + note.addEventListener('transitionend', () => { + note.remove(); + target.remove();// remove placeholder + + // Check if same btn already exists caused by menu open loading new model before animation ends + const existingBtn = modelListDiv.querySelector(`.quickmemo-model-btn[data-model-id="${memo.id}"]`); + if (!existingBtn) { + const newBtn = this.generateAddMemoBtn(memo); + this.attachDragEventsForModelReorder(newBtn); + modelListDiv.appendChild(newBtn); + } + + }, {once: true}); + }, 10); // hack to avoid close dropdown on click event + } + + /** + * Triggers the deletion animation. + * @param {HTMLElement} note + */ + deleteWithAnimation(note) { + note.classList.add('--note-delete-animation'); + note.addEventListener('animationend', () => { + note.remove(); + }, {once: true}); + } + + /** + * Applies background color and calculates brightness to set a dark/light font class. + * @param {HTMLElement} note + * @param {string} color - Hex color string. + */ + setMemoColor(note, color) { + // Default color if not valide + if (!color || typeof color !== 'string') color = '#fff8a6'; + + note.style.setProperty('--memo-color', color); + + // Check that it is a 6-character hex + let c = color.startsWith('#') ? color.substring(1) : color; + if (c.length !== 6 || !/^[0-9a-fA-F]{6}$/.test(c)) { + // invalide → considère clair par défaut + note.classList.remove('--memo-is-dark'); + return; + } + + // Conversion hex -> RGB + const r = parseInt(c.substr(0, 2), 16); + const g = parseInt(c.substr(2, 2), 16); + const b = parseInt(c.substr(4, 2), 16); + + // Calculate brightness + const brightness = (r * 299 + g * 587 + b * 114) / 1000; + + if (brightness < 128) { + note.classList.add('--memo-is-dark'); + } else { + note.classList.remove('--memo-is-dark'); + } + } + + /** + * Dynamically resizes the font based on the content density within the note's dimensions. + * @param {HTMLElement} noteEl + */ + async adjustFontSize(noteEl) { + if (!this.param.autoResizeFontSize) { + return; + } + + const textarea = noteEl.querySelector('textarea'); + const preview = noteEl.querySelector('.quickmemo-markdown-preview'); + + const footerHeight = noteEl.querySelector('.quickmemo-footer')?.offsetHeight || 0; + const headerHeight = noteEl.querySelector('.quickmemo-header')?.offsetHeight || 0; + + const contentHeight = noteEl.clientHeight - headerHeight - footerHeight; + const contentWidth = noteEl.clientWidth; + + const textLength = textarea.value.length; + + const btnArchive = noteEl.querySelector('.quickmemo-btn-archive'); + if (btnArchive) { + btnArchive.title = await Dolibarr.tools.langs.transNoEntities(textLength > 0 ? 'QuickMemoActionArchive' : 'QuickMemoActionDeleteEmpty'); + } + + // Calculate density + const density = textLength / (contentWidth * contentHeight); + + // Linearly map density to font-size + const densityMin = 0.0002; + const densityMax = 0.005; + const fontMin = 0.8; + const fontMax = 1.2; + + // Clamp density between min & max + const clampedDensity = Math.max(densityMin, Math.min(densityMax, density)); + + // Linear interpolation + let fontSize = fontMax - ((clampedDensity - densityMin) / (densityMax - densityMin)) * (fontMax - fontMin); + // Round to the nearest 0.1 em + fontSize = Math.round(fontSize * 10) / 10; + + textarea.style.fontSize = fontSize + 'em'; + preview.style.fontSize = fontSize + 'em'; + } + + + // /** + // * Brings the element to the foreground on mouse click. + // * @param {HTMLElement} el + // */ + // bindFocusZ(el) { + // el.addEventListener('mousedown', () => { + // el.style.zIndex = ++this.currentZ; + // }); + // } + + /* =============================== + DRAG + ================================= */ + + /** + * Makes a note element draggable. Handles selection vs drag logic on textareas. + * @param {HTMLElement} el + * @param {Object} state - Reference to shared resizing state. + */ + makeDraggable(el, state) { + + let offsetX, offsetY, dragging = false; + let hasMoved = false; + + + let startX, startY; + let dragTimeout = null; + const startDragDelay = 300; // ms : temps d'attente au click avant de passer en mode drag + const selectionThreshold = 5; // px : distance en pixels qui désactive le drag pour passer en mode selection + const textarea = el.querySelector('textarea'); + + // Auto-scroll configuration + const scrollSpeed = 15; + const scrollThreshold = 50; + let scrollInterval = null; + + const stopAutoScroll = () => { + if (scrollInterval) { + clearInterval(scrollInterval); + scrollInterval = null; + } + }; + + const onMouseMove = (ev) => { + if (!dragging) return; + + // 1. Calculate new positions + let newX = ev.clientX + window.scrollX - offsetX; + let newY = ev.clientY + window.scrollY - offsetY; + + // 2. Boundaries logic + const boundaryW = Math.max(document.documentElement.scrollWidth, window.innerWidth); + const boundaryH = Math.max(document.documentElement.scrollHeight, window.innerHeight); + + const maxX = boundaryW - el.offsetWidth; + const maxY = boundaryH - el.offsetHeight; + + newX = Math.max(0, Math.min(newX, maxX)); + newY = Math.max(0, Math.min(newY, maxY)); + + el.style.left = newX + 'px'; + el.style.top = newY + 'px'; + + hasMoved = true; + + // 3. Auto-scroll logic + const viewportY = ev.clientY; + const viewportHeight = window.innerHeight; + + stopAutoScroll(); + + // Scroll down if mouse is near bottom edge + if (viewportY > viewportHeight - scrollThreshold) { + scrollInterval = setInterval(() => { + window.scrollBy(0, scrollSpeed); + // Update position while scrolling even if mouse doesn't move + let currentY = parseInt(el.style.top) + scrollSpeed; + const currentMaxY = document.documentElement.scrollHeight - el.offsetHeight; + el.style.top = Math.min(currentY, currentMaxY) + 'px'; + }, 16); + } + // Scroll up if mouse is near top edge + else if (viewportY < scrollThreshold) { + scrollInterval = setInterval(() => { + window.scrollBy(0, -scrollSpeed); + let currentY = parseInt(el.style.top) - scrollSpeed; + el.style.top = Math.max(0, currentY) + 'px'; + }, 16); + } + }; + + const cancelDrag = () => { + if (dragTimeout) { + clearTimeout(dragTimeout); + dragTimeout = null; + } + dragging = false; + el.classList.remove('--dragging'); + }; + + const onMouseUp = () => { + cancelDrag(); + + document.removeEventListener('mousemove', onMouseMove); + document.removeEventListener('mouseup', onMouseUp); + + if (hasMoved) this.saveAllPositions() + hasMoved = false; + }; + + el.addEventListener('mousedown', e => { + + if (e.button !== 0) return; // Left click only + if (state.isResizing) return; + // if (el.style.cursor && el.style.cursor.includes('resize')) return; + + // DO NOT DRAG if mouse hover .quickmemo-actions + if (e.target.closest('.quickmemo-actions')) return; + + //if (e.target.tagName === 'TEXTAREA') return; + const isOnTextarea = e.target === textarea; + + this.bringToTop(el); + + hasMoved = false; + + const rect = el.getBoundingClientRect(); + startX = e.clientX + window.scrollX; + startY = e.clientY + window.scrollY; + offsetX = startX - (rect.left + window.scrollX); + offsetY = startY - (rect.top + window.scrollY); + + if (isOnTextarea && !textarea.disabled && !textarea.readOnly) { + + // Delayed drag to allow text selection + dragTimeout = setTimeout(() => { + // Check if there is no selection + const sel = window.getSelection(); + if (sel && sel.toString().length === 0) { + dragging = true; + el.classList.add('--dragging'); + + // Cancel selection when dragging + if (sel.rangeCount > 0) sel.removeAllRanges(); + // Remove focus so the cursor stops moving + if (document.activeElement === textarea) textarea.blur(); + } + }, startDragDelay); + + // Detect movement for text selection + const onTempMove = (ev) => { + const dx = ev.clientX - e.clientX; + const dy = ev.clientY - e.clientY; + if (Math.sqrt(dx * dx + dy * dy) > selectionThreshold) { + cancelDrag(); // Cancel selection when selected + cleanupTempMove(); + } + }; + + const cleanupTempMove = () => { + document.removeEventListener('mousemove', onTempMove); + dragTimeout = null; + }; + document.addEventListener('mousemove', onTempMove, {once: true}); + + } else { + dragging = true; + el.classList.add('--dragging'); + e.preventDefault(); + } + + document.addEventListener('mousemove', onMouseMove); + document.addEventListener('mouseup', onMouseUp); + + }); + } + + /* =============================== + RESIZE + ================================= */ + + /** + * Makes a note resizable from all edges and corners. + * @param {HTMLElement} el + * @param {Object} memo - Data object to update. + * @param {Object} state - Shared resizing state. + */ + makeResizable(el, memo, state) { + + const margin = 10; + let direction = null; + let startX, startY, startW, startH, startLeft, startTop; + + const onMouseMove = (e) => { + if (!state.isResizing) return; + + let dx = e.clientX - startX; + let dy = e.clientY - startY; + + let newW = startW; + let newH = startH; + let newLeft = startLeft; + let newTop = startTop; + + // Handle different directions + if (direction.includes('e')) { + newW = startW + dx; + newW = Math.min(newW, document.documentElement.scrollWidth - startLeft); + } + if (direction.includes('s')) { + newH = startH + dy; + newH = Math.min(newH, document.documentElement.scrollHeight - startTop); + } + if (direction.includes('w')) { + newW = startW - dx; + newLeft = startLeft + dx; + if (newLeft < 0) { + newW += newLeft; // Reduce width to avoid overflow + newLeft = 0; + } + } + if (direction.includes('n')) { + newH = startH - dy; + newTop = startTop + dy; + if (newTop < 0) { + newH += newTop; // Reduce height to avoid overflow + newTop = 0; + } + } + + // Minimum dimensions constraint + newW = Math.max(250, newW); + newH = Math.max(100, newH); + + el.style.width = newW + 'px'; + el.style.height = newH + 'px'; + el.style.left = newLeft + 'px'; + el.style.top = newTop + 'px'; + + this.adjustFontSize(el); + + memo.pos_w = newW; + memo.pos_h = newH; + memo.pos_x = newLeft; + memo.pos_y = newTop; + }; + + const onMouseUp = () => { + if (!state.isResizing) return; + + state.isResizing = false; + document.body.style.userSelect = ''; + + document.removeEventListener('mousemove', onMouseMove); + document.removeEventListener('mouseup', onMouseUp); + + this.savePosition(el); + }; + + // Mouse movement detection for cursor change + el.addEventListener('mousemove', (e) => { + + if (state.isResizing) return; + + const rect = el.getBoundingClientRect(); + const x = e.clientX; + const y = e.clientY; + + const onLeft = x >= rect.left - margin && x <= rect.left + margin; + const onRight = x >= rect.right - margin && x <= rect.right + margin; + const onTop = y >= rect.top - margin && y <= rect.top + margin; + const onBottom = y >= rect.bottom - margin && y <= rect.bottom + margin; + + direction = null; + + if (onRight && onBottom) direction = 'se'; + else if (onLeft && onBottom) direction = 'sw'; + else if (onRight && onTop) direction = 'ne'; + else if (onLeft && onTop) direction = 'nw'; + else if (onRight) direction = 'e'; + else if (onLeft) direction = 'w'; + else if (onBottom) direction = 's'; + else if (onTop) direction = 'n'; + + el.style.cursor = getCursor(direction); + }); + + el.addEventListener('mousedown', (e) => { + if (!direction) return; + + // DO NOT RESIZE if mouse hover .quickmemo-actions + if (e.target.closest('.quickmemo-actions')) return; + + this.bringToTop(el); + + state.isResizing = true; + + const rect = el.getBoundingClientRect(); + startX = e.clientX; + startY = e.clientY; + startW = rect.width; + startH = rect.height; + startLeft = rect.left + window.scrollX; + startTop = rect.top + window.scrollY; + + document.body.style.userSelect = 'none'; + + document.addEventListener('mousemove', onMouseMove); + document.addEventListener('mouseup', onMouseUp); + + e.preventDefault(); + }); + + /** Helper to return CSS cursor string */ + function getCursor(dir) { + switch (dir) { + case 'se': + case 'nw': + return 'nwse-resize'; + case 'ne': + case 'sw': + return 'nesw-resize'; + case 'e': + case 'w': + return 'ew-resize'; + case 'n': + case 's': + return 'ns-resize'; + default: + return 'default'; + } + } + } + + /* =============================== + SAVE + ================================= */ + + /** + * Binds auto-save with debounce logic on textarea input. + * @param {HTMLTextAreaElement} textarea + * @param {HTMLElement} noteEl + */ + bindSave(textarea, noteEl) { + + let timeout; + + let m = this.getMemoFromElement(noteEl); + + textarea.addEventListener('input', () => { + + clearTimeout(timeout); + + timeout = setTimeout(() => { + const id = noteEl.dataset.id; + + if (!id || id == 0) return; // Note not yet created in DB + m.memo.note = textarea.value; + this.saveNote(id, m.memo.note, noteEl); + + }, 600); + }); + } + + /** + * Persists note position and dimensions to the server. + * @async + * @param {HTMLElement} el + */ + async savePosition(el) { + const m = this.memos.find(x => x.el === el); + if (!m) return; + + if (!el.dataset.id || parseInt(el.dataset.id) === 0) return; // not created yet in database + + try { + + // TODO send all others memo pos_z for update + + const res = await fetch(this.param.interfaceUrl + '?action=update_position', { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({ + id: el.dataset.id, + x: parseInt(el.style.left), + y: parseInt(el.style.top), + w: parseInt(el.style.width), + h: parseInt(el.style.height), + z: parseInt(m.memo.pos_z) || 1, + token: this.param.token + }) + }); + + const json = await res.json(); + + if (!json.result) { + throw new Error(json.msg); + } + + Dolibarr.executeHook('QuickMemo:savePosition:saved', {el, json}); + + } catch (err) { + console.error('QuickMemo save position error', err); + Dolibarr.tools.setEventMessage(Dolibarr.tools.langs.trans('QuickMemoSavePositionError') + ' : ' + err, 'errors'); + } + } + + /** + * Saves the coordinates and Z-index of ALL memos on the page. + */ + saveAllPositions() { + const memosData = this.memos.map(m => ({ + id: m.el.dataset.id, + x: parseInt(m.el.style.left) || 0, + y: parseInt(m.el.style.top) || 0, + w: parseInt(m.el.style.width) || 0, + h: parseInt(m.el.style.height) || 0, + z: parseInt(m.memo.pos_z) || 1 + })); + + fetch(this.param.interfaceUrl + '?action=update_all_positions&token=' + this.param.token, { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({ + memos: memosData + }) + }) + .then(response => response.json()) + .then(data => { + if (!data.result) console.error("Error saving all positions:", data.msg); + }) + .catch(err => console.error("Fetch error:", err)); + } + + /** + * Persists note content to the server. + * @async + * @param {number|string} id + * @param {string} note + * @param {HTMLElement} noteEl + */ + async saveNote(id, note, noteEl) { + + let hookRes = await Dolibarr.executeHookAwait('QuickMemo:saveNote', {id, note}); + if (hookRes > 0) { + return; + } + + try { + const res = await fetch(this.param.interfaceUrl + '?action=update_note', { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({ + id: id, + note: note, + token: this.param.token + }) + }); + + const json = await res.json(); + + if (!json.result) { + throw new Error(json.msg); + } + + if (json.data && json.data.memo) { + await this.updateMemoTxt(json.data.memo, noteEl); + } + + Dolibarr.executeHook('QuickMemo:saveNote:saved', {id, note, json}); + + } catch (err) { + console.error('QuickMemo save note error', err); + Dolibarr.tools.setEventMessage(Dolibarr.tools.langs.trans('QuickMemoSaveError') + ' : ' + err, 'errors'); + } + } + + /* =============================== + VISIBILITY + ================================= */ + + /** + * Checks all notes and ensures they are visible in the current container. + */ + ensureAllVisible() { + this.memos.forEach(({el}) => this.ensureVisible(el)); + } + + /** + * Clamps a note's position to keep it within the horizontal boundaries. + * Vertical clamping is disabled to allow notes to be placed anywhere + * in long documents, as vertical scrolling is standard. + * @param {HTMLElement} el - The memo DOM element to check. + */ + ensureVisible(el) { + // Get current CSS positions and actual element dimensions + const posX = parseInt(el.style.left) || 0; + const posW = el.offsetWidth; + + /** + * We use the maximum between the container width and the window width + * to determine the right boundary. + */ + const boundaryW = Math.max(this.container.scrollWidth, window.innerWidth); + + // 1. Horizontal constraint (Right border) + // We only force the note back if it exceeds the right edge. + if (posX + posW > boundaryW) { + // Calculate a new position with a 32px safety margin + let newLeft = boundaryW - posW - 32; + + // Ensure we don't push the note into negative space on the left + el.style.left = Math.max(32, newLeft) + 'px'; + } + + // 2. Vertical constraint + // Disabled: Let the note stay where it is, even if it's below the current body height. + // The browser will naturally handle the scroll if needed. + } + + /** + * Updates the metadata text (User/Date) in the memo DOM element. + * @async + * @param {Object} memo + * @param {HTMLElement} note + */ + async updateMemoTxt(memo, note) { + // Sélectionne les éléments existants + const userCreateEl = note.querySelector('.quickmemo-info__user-create-name'); + const dateCreateEl = note.querySelector('.quickmemo-info__date_create'); + const dateUpdateEl = note.querySelector('.quickmemo-info__date_update'); + const userChangeEl = note.querySelector('.quickmemo-info__user-change-name'); + + // Mets à jour la création + if (userCreateEl) userCreateEl.textContent = memo.user_name || ''; + if (dateCreateEl) dateCreateEl.textContent = memo.date_creation || ''; + + // Détermine si des changements existent + const hasDateChange = memo.date_change && memo.date_change.trim() !== '' && memo.date_creation !== memo.date_change; + const hasUserChange = memo.user_change_name && memo.user_change_name.trim() !== '' && memo.user_name !== memo.user_change_name; + + // Mets à jour ou vide les infos de mise à jour + if (dateUpdateEl) { + dateUpdateEl.textContent = hasDateChange ? `${await Dolibarr.tools.langs.transNoEntities('QuickMemoModified')} : ${memo.date_change}` : ''; + } + if (userChangeEl) { + userChangeEl.textContent = hasUserChange ? `${await Dolibarr.tools.langs.transNoEntities('QuickMemoBy')} ${memo.user_change_name}` : ''; + } + } + + /** + * Generates a button for the template list based on a model object. + * @param {Object} model + * @returns {HTMLElement} The created button. + */ + generateAddMemoBtn(model) { + const dropdown = document.getElementById(this.param.menuDropDownId); + const defaultModel = { + id: false, + name: "", + color: null, + note: "", + pos_x: null, + pos_y: null, + pos_w: null, + pos_h: null, + pos_z: null, + rank_tpl: 0, + shared_on_element: "0", + private: 0, + date_creation: "", + fk_user_creat: "", + user_name: "", + date_change: "", + user_change_name: "" + }; + + model = {...defaultModel, ...model}; + + const btn = document.createElement('button'); + btn.className = 'quickmemo-model-btn'; + btn.style.background = model.color || '#fff8a6'; + btn.dataset.modelId = model.id; + btn.title = Dolibarr.tools.langs.transNoEntities('QuickMemoAdd') + + (model.name ? ` : ${model.name}` : ''); + + // if(model.name) { + // btn.title = `${model.name}` + // this.initTooltips(btn); + // } + + // ===== création du bouton delete ===== + const deleteBtn = document.createElement('span'); + deleteBtn.className = 'quickmemo-model-delete'; + deleteBtn.title = Dolibarr.tools.langs.transNoEntities('QuickMemoDeleteModel') + btn.dataset.rank = model.rank_tpl || 0; + + btn.appendChild(deleteBtn); + + // DELETE + if (this.param.userDeleteRight && model.id) { + // Hover delay + let hoverTimer = null; + + btn.addEventListener('mouseenter', (e) => { + // If shiftKey is pressed, direct show + if (e.shiftKey) { + clearTimeout(hoverTimer); // In case of a timer already active + deleteBtn.classList.add('--show'); + } else { + // instead run timer + hoverTimer = setTimeout(() => { + deleteBtn.classList.add('--show'); + }, 800); + } + }); + + btn.addEventListener('mouseleave', () => { + clearTimeout(hoverTimer); + deleteBtn.classList.remove('--show'); + }); + + // Delete model + deleteBtn.addEventListener('click', async (e) => { + e.stopPropagation(); + e.preventDefault(); + + // Fast delete if shiftKey is pressed, otherwise ask for confirmation + if (!e.shiftKey) { + const confirm = await this.openConfirmDialog( + await Dolibarr.tools.langs.trans('QuickMemoConfirmDeleteModel') + (model.name ? '
' + this.escapeHTML(model.name) + '' : ''), + { + dialogClass: '--dialog-danger', + btnConfirmClass: 'dialog-btn-destructive' + } + ); + + if (!confirm) return; + } + + try { + const res = await fetch(this.param.interfaceUrl + '?action=delete_model', { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({ + id: model.id, + token: this.param.token + }) + }); + + const json = await res.json(); + if (!json.result) throw new Error(json.msg); + + btn.remove(); + } catch (err) { + Dolibarr.tools.setEventMessage( + Dolibarr.tools.langs.trans('QuickMemoDeleteModelError') + ' : ' + err, + 'errors' + ); + } + }); + } + + + // Create memo on template click + btn.addEventListener('click', e => { + e.preventDefault(); + this.createMemoFromModel(model); + dropdown.classList.remove('open'); + }); + + return btn; + } + + /** + * Initialize standard tooltips. + * + * @param {HTMLElement|jQuery} root + */ + initTooltips(root) { + + if (!root) return; + + root.classList.add('dol-tooltip', '--dark-mode', '--tooltip-top'); + + // Convert title -> data-title au moment de l'init + const title = root.getAttribute('title'); + if (title) { + root.setAttribute('data-title', title); + root.setAttribute('aria-label', title); + root.removeAttribute('title'); + } + + // Mise à jour à chaque survol (si le title a été modifié dynamiquement) + const syncTitle = () => { + const currentTitle = root.getAttribute('title'); + if (currentTitle) { + root.setAttribute('data-title', currentTitle); + root.setAttribute('aria-label', currentTitle); + root.removeAttribute('title'); + } + }; + + root.addEventListener('mouseenter', syncTitle); + root.addEventListener('focus', syncTitle); + + // Stocker les handlers pour pouvoir les retirer proprement + root._quickmemoTooltipSync = syncTitle; + + // JQUERY STYLE + // const tooltipClass = 'quick-memo-tooltip' + // const $el = jQuery(root); + // if ($el.data("ui-tooltip")) { + // $el.tooltip("destroy"); + // } + // + // $el.tooltip({ + // tooltipClass: tooltipClass, + // show: { collision: "flipfit", effect: "toggle", delay: 50, duration: 20 }, + // hide: { delay: 250, duration: 20 }, + // content: function () { + // return $el.prop("title"); + // } + // }); + } + + + /** + * remove tooltips. + * + * @param {HTMLElement|jQuery} root + */ + removeTooltips(root) { + + if (!root) return; + + root.classList.remove('dol-tooltip', '--dark-mode', '--tooltip-top'); + + // Restaurer title si data-title existe + const dataTitle = root.getAttribute('data-title'); + if (dataTitle) { + root.setAttribute('title', dataTitle); + } + + root.removeAttribute('data-title'); + + // Remove listeners + if (root._quickmemoTooltipSync) { + root.removeEventListener('mouseenter', root._quickmemoTooltipSync); + root.removeEventListener('focus', root._quickmemoTooltipSync); + delete root._quickmemoTooltipSync; + } + + // JQUERY STYLE + // const $el = jQuery(root); + // if ($el.data("ui-tooltip")) { + // $el.tooltip("destroy"); + // } + } + + /** + * Initializes drag-and-drop reordering for the template list. + */ + initModelReorder() { + if (!this.param.userWriteRight) return; + + const container = document.getElementById(this.param.menuDropDownModelListContainerId); + if (!container) return; + + this._modelReorderContainer = container; + + // Placeholder unique pour tout le container + if (!this._modelReorderPlaceholder) { + this._modelReorderPlaceholder = document.createElement('div'); + this._modelReorderPlaceholder.className = 'quickmemo-model-placeholder'; + } + + container.querySelectorAll('.quickmemo-model-btn') + .forEach(btn => this.attachDragEventsForModelReorder(btn)); + } + + /** + * Attaches native drag events to a template button for sorting. + * @param {HTMLElement} btn + */ + attachDragEventsForModelReorder(btn) { + + if (btn.dataset.reorderInit) return; // évite double bind + btn.dataset.reorderInit = '1'; + + const container = this._modelReorderContainer; + const placeholder = this._modelReorderPlaceholder; // utiliser le placeholder unique + + btn.setAttribute('draggable', true); + + let dragged = null; + + btn.addEventListener('dragstart', (e) => { + dragged = btn; + btn.classList.add('--dragging'); + placeholder.style.height = btn.offsetHeight + 'px'; + container.insertBefore(placeholder, btn.nextSibling); + setTimeout(() => btn.style.display = 'none', 0); + }); + + btn.addEventListener('dragend', () => { + btn.classList.remove('--dragging'); + btn.style.display = ''; + + if (!placeholder.parentNode) return; + + container.insertBefore(dragged, placeholder); + placeholder.remove(); + + this.saveModelOrder(dragged.dataset.modelId); + }); + + btn.addEventListener('dragover', (e) => { + e.preventDefault(); + const rect = btn.getBoundingClientRect(); + const offset = e.clientY - rect.top; + + if (offset < rect.height / 2) { + container.insertBefore(placeholder, btn); + } else { + container.insertBefore(placeholder, btn.nextSibling); + } + }); + } + + /** + * Persists the new sorting order of templates to the server. + * @async + * @param {number|string|null} movedId - ID of the element that was just moved. + */ + async saveModelOrder(movedId = null) { + + const container = document.getElementById(this.param.menuDropDownModelListContainerId); + const buttons = [...container.querySelectorAll('.quickmemo-model-btn')]; + + // recalcul complet des positions à partir du DOM + const orderData = buttons.map((btn, index) => { + + const newRank = buttons.length - index; // cohérent avec ton ORDER BY rank DESC + + // on met à jour le dataset pour rester cohérent en mémoire + btn.dataset.rank = newRank; + + return { + id: btn.dataset.modelId, + rank: newRank + }; + }); + + const payload = {order: orderData}; + + // si on veut envoyer moved, on calcule sa vraie position + if (movedId !== null) { + + const newIndex = buttons.findIndex( + btn => btn.dataset.modelId == movedId + ); + + if (newIndex !== -1) { + payload.moved = { + id: movedId, + newPos: newIndex + 1 // position visuelle 1 based + }; + } + } + + try { + + const res = await fetch( + this.param.interfaceUrl + '?action=update_model_rank&token=' + this.param.token, + { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify(payload) + } + ); + + const json = await res.json(); + if (!json.result) throw new Error(json.msg); + + } catch (err) { + + console.error('QuickMemo save model order error', err); + + Dolibarr.tools.setEventMessage( + Dolibarr.tools.langs.trans('QuickMemoSaveModelOrderError') + ' : ' + err, + 'errors' + ); + } + } + + /** + * Builds and injects the top menu dropdown into the Dolibarr interface. + * @async + */ + async initMenuMemoDropdown() { + const DOL_VERSION = parseInt(Dolibarr.getContextVar('DOL_VERSION', false)); + const menuContainer = document.querySelector(DOL_VERSION > 20 || !DOL_VERSION ? '#id-top .login_block_tools .inline-block' : '#id-top .inline-block .login_block_elem'); + if (!menuContainer) return; + + const dropdown = document.createElement('div'); + dropdown.className = 'dropdown inline-block mod-quick-memo-menu'; + dropdown.id = 'quickmemo-create-dropdown' + + let textLoading = await Dolibarr.tools.langs.trans('Loading'); + let textNewNote = await Dolibarr.tools.langs.trans('NewNote'); + dropdown.innerHTML = ` + + + `; + + menuContainer.prepend(dropdown); + + const dropDownMenuToggleBtn = dropdown.querySelector('.dropdown-toggle'); + const presetListDiv = document.getElementById(this.param.menuDropDownPresetListContainerId); + presetListDiv.innerHTML = ''; + + const modelListDiv = document.getElementById(this.param.menuDropDownModelListContainerId); + modelListDiv.innerHTML = ''; + + + dropdown.setAttribute('data-loaded', 0); + + // Toggle ouverture / fermeture + dropDownMenuToggleBtn.addEventListener('click', e => { + e.preventDefault(); + e.stopPropagation(); + + // LOAD DATA IN DROPDOWN MENU + this.fetchMenuDropDown(); + + // OPEN DROP DOWN + dropdown.classList.toggle('open'); + }); + + document.addEventListener('click', e => { + if (!dropdown.contains(e.target)) { + dropdown.classList.remove('open'); + } + }); + + + const btnHelp = document.createElement('button'); + btnHelp.type = 'button'; + btnHelp.className = 'quickmemo-dropdown-btn btn-low-emphasis --btn-icon'; + btnHelp.innerHTML = ``; + btnHelp.title = Dolibarr.tools.langs.transNoEntities('Help'); + + const dropDownMenuHeader = dropdown.querySelector('.dropdown-quickmemo-create .dropdown-header .dropdown-header-actions'); + dropDownMenuHeader.appendChild(btnHelp); + + btnHelp.addEventListener('click', () => { + const confirmOptions = { + title: Dolibarr.tools.langs.trans('QuickMemoHelp_Title'), + confirmLabel: Dolibarr.tools.langs.trans('CloseDialog'), + customClass: 'dialog-lg', + }; + this.openSimpleDialog(this.getDropDownHelp(), confirmOptions); + }); + + + Dolibarr.executeHook('QuickMemo:initMenuMemoDropdown', {dropdown}); + } + + /** + * Fetches available presets and user-created models from the server for the dropdown menu. + * @async + * @param {boolean} force - Force refresh even if already loaded. + */ + async fetchMenuDropDown(force = false) { + + const dropDown = document.getElementById(this.param.menuDropDownId); + const dropDownMenuToggleBtn = dropDown.querySelector('.dropdown-toggle'); + const presetListDiv = document.getElementById(this.param.menuDropDownPresetListContainerId); + const modelListDiv = document.getElementById(this.param.menuDropDownModelListContainerId); + + // Check attribute flag, used to check if data already loaded ONCE + if (dropDown.getAttribute('data-loaded') === "1" && !force) { + return; + } + + // Fetch models + try { + const res = await fetch(this.param.interfaceUrl + '?action=list_models', { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({ + element_type: this.param.elementType, + context: this.param.context, + token: this.param.token + }) + }); + const json = await res.json(); + + if (!json.result) { + throw new Error(json.msg); + } + + if (!json.data) { + throw new Error('QuickMemo list models get empty data'); + } + + + let models = json.data.modelTemplate.length ? json.data.modelTemplate : []; + let presets = json.data.presetTemplate.length ? json.data.presetTemplate : []; + + // CREATE BTN TEMPLATE LIST + if (!models.length) { + modelListDiv.innerHTML = '
' + await Dolibarr.tools.langs.trans('NoTemplatesFound') + '
'; + } else { + models.forEach(model => { + const btn = this.generateAddMemoBtn(model); + modelListDiv.appendChild(btn); + }); + } + + this.initModelReorder(); + + // CREATE BTN FOR COLOR PRESETS LIST + if (!presets.length) { + modelListDiv.innerHTML = '
' + await Dolibarr.tools.langs.trans('NoPresetsFound') + '
'; + } else { + + presets.forEach(preset => { + const btn = this.generateAddMemoBtn(preset); + presetListDiv.appendChild(btn); + }); + + // Quick add default note on double click + dropDownMenuToggleBtn.addEventListener('dblclick', e => { + e.preventDefault(); + this.createMemoFromModel(presets[0]); + dropdown.classList.remove('open'); + }); + } + + // Set loaded data flag + dropDown.setAttribute('data-loaded', 1); + } catch (err) { + Dolibarr.tools.setEventMessage(Dolibarr.tools.langs.trans('QuickMemoLoadModelError') + ' : ' + err, 'errors'); + console.error('QuickMemo load models error', err); + } + } + + /* =============================== + CREATION MEMO DEPUIS MODELE + ================================= */ + /** + * Creates a new note based on a specific template (model). + * @async + * @param {Object} model - The template data. + */ + async createMemoFromModel(model) { + // 1. Trouver le z-index maximum actuel parmi les notes affichées + const allMemos = this.container.querySelectorAll('.quick-memo-note'); // Adaptez le sélecteur si besoin + let maxZ = 0; + allMemos.forEach(el => { + const z = parseInt(el.style.zIndex) || 0; + if (z > maxZ) maxZ = z; + }); + + // La nouvelle note doit être au-dessus de tout le monde + const newZ = maxZ + 1; + + + // Crée un objet memo minimal à partir du modèle + const memo = { + id: 0, // rowid temporaire avant sauvegarde + deleteBtn: false, + note: model.note || '', + pos_w: model.pos_w || 250, // largeur par défaut + pos_h: model.pos_h || 250, // hauteur par défaut + pos_x: model.pos_x || 0, + pos_y: model.pos_y || 0, + pos_z: newZ || 0, + color: model.color || '#fff8a6', + shared_on_element: model.shared_on_element !== undefined ? model.shared_on_element : 0, + private: model.private !== undefined ? parseInt(model.private) : 0 + }; + + // Center the new note in the current viewport + const containerWidth = this.container.clientWidth; + const containerHeight = this.container.clientHeight; + const viewportHeight = window.innerHeight; + const scrollY = window.scrollY || window.pageYOffset; + + memo.pos_x = Math.max(32, (containerWidth - memo.pos_w) / 2); + memo.pos_y = scrollY + Math.max(32, (viewportHeight - memo.pos_h) / 2); + + // Render le memo + const noteEl = await this.renderMemo(memo); + this.bringToTop(noteEl); + + // Focus sur le textarea + const textarea = noteEl.querySelector('textarea'); + if (textarea) { + textarea.focus(); + textarea.setSelectionRange(textarea.value.length, textarea.value.length); + } + + try { + const res = await fetch(this.param.interfaceUrl + '?action=create', { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({ + element_id: this.param.elementId, + element_type: this.param.elementType, + context: this.param.context, + note: memo.note, + color: memo.color, + private: memo.private, + shared_on_element: memo.shared_on_element, + token: this.param.token, + x: parseInt(noteEl.style.left), + y: parseInt(noteEl.style.top), + w: parseInt(noteEl.style.width), + h: parseInt(noteEl.style.height), + z: parseInt(memo.pos_z) + }) + }); + + const json = await res.json(); + + if (!json.result) { + throw new Error(json.msg); + return; + } + + if (json.data && json.data.id) { + memo.id = json.data.id; + noteEl.dataset.id = json.data.id; + } + + if (json.data && json.data.memo) { + await this.updateMemoTxt(json.data.memo, noteEl); + } + + Dolibarr.executeHook('QuickMemo:createMemoFromModel', {memo, noteEl, json}); + + } catch (err) { + Dolibarr.tools.setEventMessage(Dolibarr.tools.langs.trans('QuickMemoCreateError') + ' : ' + err, 'errors'); + console.error('QuickMemo create error', err); + } + } + + /** + * Escapes special HTML characters for safe rendering. + * @param {string} str + * @returns {string} + */ + escapeHTML(str) { + return str.replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + + + /** + * A basic markdown parser that handles titles, checkboxes, links, bold and italic. + * @async + * @param {string} md - The raw markdown text. + * @returns {string} The resulting HTML string. + */ + async simpleMarkdown(md) { + + /** + * Handles inline styles like Bold, Italic, Underline, and Links. + * Can be used inside headers and checkboxes. + */ + const parseInline = (text) => { + if (!text) return ''; + return this.escapeHTML(text) + .replace(/\*\*(.*?)\*\*/g, '$1') // **Bold** + .replace(/__(.*?)__/g, '$1') // __Underline__ + .replace(/\*(.*?)\*/g, '$1') // *Italique* + .replace(/\[(.*?)\]\((.*?)\)/g, (full, txt, url) => { // [Link](url) + const safeUrl = /^(https?:\/\/|#|\/)/.test(url) ? url : '#'; + return `${this.escapeHTML(txt)}`; + }); + }; + + const lines = md.split('\n'); + + // Use .map to ensure every input line creates exactly one .markdown-line output + let res = lines.map((line, idx) => { + let html = ''; + let isEmpty = false; + let match; + + const nextLine = (lines[idx + 1] || "").trim(); + const prevLine = (lines[idx - 1] || "").trim(); + const trimmedLine = line.trim(); + + // CASE 1: Setext H1 - Current line is text followed by "===" + if (trimmedLine !== "" && nextLine.match(/^={3,}$/)) { + html = `

${parseInline(line)}

`; + } + // CASE 2: Setext H2 - Current line is text followed by "---" + else if (trimmedLine !== "" && nextLine.match(/^-{3,}$/)) { + html = `

${parseInline(line)}

`; + } + // CASE 3: The Underline line itself (=== or ---) + // We check if the line above was a title to decide if we hide this line + else if (trimmedLine.match(/^={3,}$/) && prevLine !== "") { + html = ''; // Hide the syntax line + isEmpty = true; + } else if (trimmedLine.match(/^-{3,}$/) && prevLine !== "") { + html = ''; // Hide the syntax line + isEmpty = true; + } + // CASE 4: Standard ATX Titles (#, ##, ###) + else if (match = line.match(/^(#{1,3})\s+(.*)$/)) { + const level = match[1].length; + html = `${parseInline(match[2])}`; + } + // CASE 5: Checkboxes [ ] or [x] + else if (match = line.match(/^\[([ xX])\]\s+(.*)$/)) { + const checked = match[1].toLowerCase() === 'x' ? 'checked' : ''; + html = ` ${parseInline(match[2])}`; + } + // CASE 6: Regular Text or actually empty line + else { + if (trimmedLine === "") { + html = ' '; + isEmpty = true; + } else { + html = parseInline(line); + } + } + + // Maintain the div structure for scrolling/indexing consistency + const classes = `markdown-line ${isEmpty ? 'empty-line' : ''}`; + return `
${html}
`; + }).join(''); + + // Hook for external extensions + if (Dolibarr && Dolibarr.executeHookAwait) { + await Dolibarr.executeHookAwait('QuickMemo:simpleMarkdown', {md, res}); + } + + return res; + } + + /** + * Handles Toggle for Bold and Italic without infinite accumulation. + * @param {string} text - The selected text + * @param {string} type - 'bold' or 'italic' + * @returns {string} Processed text + */ + /** + * Toggles inline markdown with support for overlapping styles (***bold italic***) + */ + toggleInlineMarkdown(text, type) { + const patterns = { + bold: { tag: '**', regex: /^\*\*(.*)\*\*$/ }, + italic: { tag: '*', regex: /^(\*\*\*|(? 0) { + // Toggle existing formatting on selected text + replacementText = this.toggleInlineMarkdown(selectedText, type); + } else { + // No selection: create a pair of tags and place cursor inside + replacementText = tag + tag; + newCursorPos = start + tag.length; + } + + this.safeInsertText(textarea, replacementText, 'select'); + + // Adjust cursor position if we just inserted empty tags (e.g., **|**) + if (selectedText.length === 0) { + textarea.setSelectionRange(newCursorPos, newCursorPos); + } + } + // --- 2. Block/Line-Based Formatting Logic --- + else { + // Find line boundaries + const lineStart = val.lastIndexOf('\n', start - 1) + 1; + let lineEnd = val.indexOf('\n', end); + if (lineEnd === -1) lineEnd = val.length; + + const lineText = val.substring(lineStart, lineEnd); + const prefixes = { h1: '# ', h2: '## ', h3: '### ', task: '[ ] ' }; + const currentPrefix = prefixes[type]; + + // Regex to match existing headers or checkboxes to allow "swapping" styles + const prefixRegex = /^(\s*#{1,3}\s+|\[[ xX]\]\s+)/; + + let newLineText; + if (lineText.startsWith(currentPrefix)) { + // Toggle OFF: Remove the prefix + newLineText = lineText.replace(currentPrefix, ''); + } else { + // Toggle ON: Strip any existing block prefix and add the new one + const cleanLine = lineText.replace(prefixRegex, ''); + newLineText = currentPrefix + cleanLine; + } + + // Select the whole line and replace it via safeInsert to keep Undo history + textarea.setSelectionRange(lineStart, lineEnd); + this.safeInsertText(textarea, newLineText, 'end', (lineStart === lineEnd ? 'end' : 'start')); + + // Special UX: If it's a new empty task, put cursor after the checkbox + if (type === 'task' && lineText.trim() === "") { + const newCursorPos = lineStart + currentPrefix.length; + textarea.setSelectionRange(newCursorPos, newCursorPos); + } + } + + // Update Toolbar & UI + if (this.updateToolbarState) { + this.updateToolbarState(textarea, toolbar); + } + } + + /** + * Updates toolbar buttons' active state based on the current selection or cursor position. + * Optimized for Post-it notes with support for Setext and Underline. + */ + updateToolbarState(textarea, toolbar) { + const start = textarea.selectionStart; + const end = textarea.selectionEnd; + const text = textarea.value; + const selectedText = text.substring(start, end); + + /** + * Helper to detect if the current context is formatted. + * It checks both the selection and the immediate surrounding characters. + */ + const isFormatActive = (type) => { + // 1. Check if selection is wrapped + if (selectedText.length > 0) { + if (type === 'bold') return selectedText.startsWith('**') && selectedText.endsWith('**'); + if (type === 'underline') return selectedText.startsWith('__') && selectedText.endsWith('__'); + if (type === 'italic') { + return (selectedText.startsWith('***') && selectedText.endsWith('***')) || + (selectedText.startsWith('*') && !selectedText.startsWith('**')); + } + } + + // 2. Check cursor context (peek 3 chars around) + const before = text.substring(start - 3, start); + const after = text.substring(end, end + 3); + const context = before + "|" + after; + + if (type === 'bold') return context.includes('**|**') || context.includes('***|***'); + if (type === 'italic') return context.includes('*|*') || context.includes('***|***'); + if (type === 'underline') return context.includes('__|__'); + + return false; + }; + + // Update UI + const states = { + bold: isFormatActive('bold'), + italic: isFormatActive('italic'), + underline: isFormatActive('underline') + }; + + Object.keys(states).forEach(type => { + toolbar.querySelector(`[data-type="${type}"]`)?.classList.toggle('--active', states[type]); + }); + + // --- Line-based logic (H1, H2, Tasks) remains the same --- + const lineStart = text.substring(0, start).lastIndexOf('\n') + 1; + const currentLine = text.substring(lineStart, text.indexOf('\n', start) === -1 ? text.length : text.indexOf('\n', start)).trim(); + + toolbar.querySelector('[data-type="h1"]')?.classList.toggle('--active', currentLine.startsWith('# ')); + toolbar.querySelector('[data-type="h2"]')?.classList.toggle('--active', currentLine.startsWith('## ')); + toolbar.querySelector('[data-type="h3"]')?.classList.toggle('--active', currentLine.startsWith('### ')); + toolbar.querySelector('[data-type="task"]')?.classList.toggle('--active', /^\[[ xX]\] /.test(currentLine)); + } + + getDropDownHelp() { + return ` +
+ +
+

${Dolibarr.tools.langs.trans('QuickMemoHelp_Visibility')}

+

${Dolibarr.tools.langs.trans('QuickMemoHelp_EscKey')}

+
+ +
+

${Dolibarr.tools.langs.trans('QuickMemoHelp_Management')}

+
    +
  • ${Dolibarr.tools.langs.trans('QuickMemoHelp_DeleteHover')}
  • +
  • ${Dolibarr.tools.langs.trans('QuickMemoHelp_ShiftKeyDelete')}
  • +
+
+ +
+

${Dolibarr.tools.langs.trans('QuickMemoHelp_Organization')}

+

${Dolibarr.tools.langs.trans('QuickMemoHelp_DragDrop')}

+
+ + +
+ `; + } + + /** + * Returns a help string describing the supported markdown syntax. + * @returns {string} + */ + getMarkDownHelp() { + return ` +
+ +
+

${Dolibarr.tools.langs.trans('QuickMemoMd_SectionUniversal')}

+

${Dolibarr.tools.langs.trans('QuickMemoMd_UniversalDesc')}

+

${Dolibarr.tools.langs.trans('QuickMemoMd_HelpIntro')}

+
+ + +
+

${Dolibarr.tools.langs.trans('QuickMemoMd_SectionStyle')}

+ *${Dolibarr.tools.langs.trans('QuickMemoMd_Italic')}* => ${Dolibarr.tools.langs.trans('QuickMemoMd_Italic')}
+ **${Dolibarr.tools.langs.trans('QuickMemoMd_Bold')}** => ${Dolibarr.tools.langs.trans('QuickMemoMd_Bold')} +
+ +
+

${Dolibarr.tools.langs.trans('QuickMemoMd_SectionTitles')}

+ # ${Dolibarr.tools.langs.trans('QuickMemoMd_Title')} 1
+ ## ${Dolibarr.tools.langs.trans('QuickMemoMd_Title')} 2
+ ### ${Dolibarr.tools.langs.trans('QuickMemoMd_Title')} 3 +
+ +
+

${Dolibarr.tools.langs.trans('QuickMemoMd_SectionTasks')}

+ [ ] ${Dolibarr.tools.langs.trans('QuickMemoMd_TaskNotDone')} => ...
+ [x] ${Dolibarr.tools.langs.trans('QuickMemoMd_TaskDone')} => ... +
+ +
+

${Dolibarr.tools.langs.trans('QuickMemoMd_SectionLinks')}

+ [${Dolibarr.tools.langs.trans('QuickMemoMd_LinkText')}](url) => ${Dolibarr.tools.langs.trans('QuickMemoMd_LinkText')} +
+ + +
+ `; + } + + /** + * Opens a modal dialog to define parameters before creating a new template from a note. + * @param {Object} memo + * @param {HTMLElement} note + */ + openCreateModelDialog(memo, note) { + + const dialog = document.createElement('dialog'); + dialog.className = 'quickmemo-modal noselect'; + + dialog.innerHTML = ` +
+
+

${Dolibarr.tools.langs.trans('QuickMemoAskCreateAModelFromThisMemo')}

+
+ +
+
+ + +
+ + ${this.param.elementId > 0 ? ` +
+ +
+ ` : `` } + +
+ +
+
+ +
+ + +
+
+ `; + + document.body.appendChild(dialog); + + // Quand le dialog se ferme (Esc, cancel, close()), on le détruit + dialog.addEventListener('close', () => { + dialog.remove(); + }); + + // Empêche le close automatique + dialog.addEventListener('cancel', (e) => { + e.preventDefault(); // optionnel + dialog.close(); + }); + + // Bouton Annuler + dialog.querySelector('.quickmemo-modal-actions-cancel-btn') + .addEventListener('click', () => { + dialog.close(); + dialog.remove(); + }); + + // Confirmer + dialog.querySelector('.quickmemo-modal-actions-confirm-btn') + .addEventListener('click', async () => { + + const commonInput = dialog.querySelector('[name=commonElementType]'); + const TplCommon = commonInput + ? (commonInput.type === 'checkbox' ? commonInput.checked : commonInput.value === '1') + : false; + const TplPrivate = dialog.querySelector('[name=privateModel]').checked; + const TplModelName = dialog.querySelector('[name=modelName]').value || ''; + const elementType = TplCommon ? '' : this.param.elementType || ''; + + let hookRes = await Dolibarr.executeHookAwait('QuickMemo:openCreateModelDialog:confirm', { + dialog, + memo, + note, + TplCommon, + TplPrivate, + TplModelName, + elementType + }); + if (hookRes > 0) { + return; + } + + try { + const res = await fetch(this.param.interfaceUrl + '?action=create_model', { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({ + id: memo.id, + element_type: elementType, + token: this.param.token, + tpl_private: TplPrivate, + tpl_name: TplModelName + }) + }); + + const json = await res.json(); + + if (!json.result) { + throw new Error(json.msg); + } + + Dolibarr.executeHook('QuickMemo:openCreateModelDialog:ModelCreated', { + dialog, + memo, + note, + TplCommon, + TplPrivate, + TplModelName, + elementType, + json + }); + } catch (err) { + + Dolibarr.tools.setEventMessage( + Dolibarr.tools.langs.trans('QuickMemoCreateError') + ' : ' + err, + 'errors' + ); + + console.error('Erreur fetch création modèle', err); + + } finally { + dialog.close(); + this.convertToModelWithAnimation(memo, note); + } + }); + + + Dolibarr.executeHook('QuickMemo:openCreateModelDialog', {dialog, memo, note}); + + dialog.showModal(); + } + + /** + * Specific confirmation dialog wrapper. + * @param {string} message - HTML content. + * @param {Object} param - Overrides for the confirmation UI. + * @returns {Promise} + */ + openConfirmDialog(message, param = {}) { + // Map old param names to the new config names if necessary, + // or just set confirmation defaults. + const confirmOptions = { + title: param.dialogTitle || Dolibarr.tools.langs.trans('DialogAskConfirm'), + customClass: 'noselect' + ( param.dialogClass || ''), + confirmLabel: param.btnConfirmTxt || Dolibarr.tools.langs.trans('Confirm'), + confirmClass: param.btnConfirmClass || 'btn-primary', + btn: { + confirm: true, + cancel: true, + close: true + }, + }; + + return this.openSimpleDialog(message, confirmOptions); + } + + + + /** + * Generic dialog engine based on HTML5 . + * @param {string} message - HTML content to display. + * @param {Object} options - UI parameters. + * @returns {Promise} Resolves to true if confirmed, false otherwise. + */ + async openSimpleDialog(message, options = {}) { + const config = { + title: '', + customClass: '', + confirmLabel: Dolibarr.tools.langs.trans('Confirm'), + confirmClass: 'btn-primary', + cancelLabel: Dolibarr.tools.langs.trans('Cancel'), + ...options, + btn: { + close: true, + confirm: true, + cancel: false, + ...(options.btn || {}) // Merge seulement les boutons précisés dans options + } + }; + + return new Promise((resolve) => { + const dialog = document.createElement('dialog'); + dialog.className = `quickmemo-modal fade-dialog ${config.customClass}`; + + dialog.innerHTML = ` +
+
+

${config.title}

+
+ ${config.btn.close ? ` + ` : ''} +
+
+
+ ${message} +
+
+ ${config.btn.cancel ? ` + ` : ''} + + ${config.btn.confirm ? ` + ` : ''} +
+
+ `; + + document.body.appendChild(dialog); + dialog.showModal(); + + const handleClose = (result) => { + dialog.close(); + resolve(result); + }; + + // Unified event listener + dialog.addEventListener('click', (e) => { + const btn = e.target.closest('button[value]'); + if (btn) return handleClose(btn.value === 'confirm'); + if (e.target === dialog) handleClose(false); // Backdrop click + }); + + dialog.addEventListener('cancel', (e) => { + e.preventDefault(); + handleClose(false); + }); + + dialog.addEventListener('close', () => dialog.remove()); + }); + } +} diff --git a/htdocs/quickmemo/lib/quickmemo.lib.php b/htdocs/quickmemo/lib/quickmemo.lib.php new file mode 100644 index 00000000000..ca0b492176a --- /dev/null +++ b/htdocs/quickmemo/lib/quickmemo.lib.php @@ -0,0 +1,83 @@ + + * + * 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 3 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, see . + */ + +/** + * \file quickmemo/lib/quickmemo.lib.php + * \ingroup quickmemo + * \brief Library files with common functions for QuickMemo + */ + +/** + * Prepare admin pages header + * + * @return array + */ +function quickmemoAdminPrepareHead() +{ + global $langs, $conf; + + // global $db; + // $extrafields = new ExtraFields($db); + // $extrafields->fetch_name_optionals_label('myobject'); + + $langs->load("quickmemo@quickmemo"); + + $h = 0; + $head = array(); + + $head[$h][0] = dolBuildUrl(dol_buildpath("/quickmemo/admin/setup.php", 1)); + $head[$h][1] = $langs->trans("Settings"); + $head[$h][2] = 'settings'; + $h++; + + + // $head[$h][0] = dolBuildUrl(dol_buildpath("/quickmemo/admin/memo_extrafields.php", 1)); + // $head[$h][1] = $langs->trans("ExtraFields"); + // $nbExtrafields = (isset($extrafields->attributes['memo']['label']) && is_countable($extrafields->attributes['memo']['label'])) ? count($extrafields->attributes['memo']['label']) : 0; + // if ($nbExtrafields > 0) { + // $head[$h][1] .= '' . $nbExtrafields . ''; + // } + // $head[$h][2] = 'memo_extrafields'; + // $h++; + + /* + $head[$h][0] = dolBuildUrl(dol_buildpath("/quickmemo/admin/myobjectline_extrafields.php", 1)); + $head[$h][1] = $langs->trans("ExtraFieldsLines"); + $nbExtrafields = (isset($extrafields->attributes['myobjectline']['label']) && is_countable($extrafields->attributes['myobjectline']['label'])) ? count($extrafields->attributes['myobject']['label']) : 0; + if ($nbExtrafields > 0) { + $head[$h][1] .= '' . $nbExtrafields . ''; + } + $head[$h][2] = 'myobject_extrafieldsline'; + $h++; + */ + + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + //$this->tabs = array( + // 'entity:+tabname:Title:@quickmemo:/quickmemo/mypage.php?id=__ID__' + //); // to add new tab + //$this->tabs = array( + // 'entity:-tabname:Title:@quickmemo:/quickmemo/mypage.php?id=__ID__' + //); // to remove a tab + complete_head_from_modules($conf, $langs, null, $head, $h, 'quickmemo@quickmemo'); + + complete_head_from_modules($conf, $langs, null, $head, $h, 'quickmemo@quickmemo', 'remove'); + + return $head; +} diff --git a/htdocs/quickmemo/lib/quickmemo_memo.lib.php b/htdocs/quickmemo/lib/quickmemo_memo.lib.php new file mode 100644 index 00000000000..8ec08511b82 --- /dev/null +++ b/htdocs/quickmemo/lib/quickmemo_memo.lib.php @@ -0,0 +1,111 @@ + + * + * 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 3 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, see . + */ + +/** + * \file lib/quickmemo_memo.lib.php + * \ingroup quickmemo + * \brief Library files with common functions for Memo + */ + +/** + * Prepare array of tabs for Memo + * + * @param Memo $object Memo + * @return array Array of tabs + */ +function memoPrepareHead($object) +{ + global $db, $langs, $conf; + + $langs->load("quickmemo@quickmemo"); + + $showtabofpagecontact = getDolGlobalInt('MAIN_QUICKMEMO_SHOW_PAGE_OF_CONTACT'); + $showtabofpagenote = getDolGlobalInt('MAIN_QUICKMEMO_SHOW_PAGE_OF_NOTE'); + $showtabofpagedocument = getDolGlobalInt('MAIN_QUICKMEMO_SHOW_PAGE_OF_DOCUMENT'); + $showtabofpageagenda = getDolGlobalInt('MAIN_QUICKMEMO_SHOW_PAGE_OF_AGENDA'); + + $h = 0; + $head = array(); + + $head[$h][0] = dolBuildUrl(dol_buildpath("/quickmemo/memo_card.php", 1), ['id' => $object->id]); + $head[$h][1] = $langs->trans("Memo"); + $head[$h][2] = 'card'; + $h++; + + if ($showtabofpagecontact) { + $head[$h][0] = dolBuildUrl(dol_buildpath("/quickmemo/memo_contact.php", 1), ['id' => $object->id]); + $head[$h][1] = $langs->trans("Contacts"); + $head[$h][2] = 'contact'; + $h++; + } + + if ($showtabofpagenote) { + if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) { + $nbNote = 0; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } + $head[$h][0] = dolBuildUrl(dol_buildpath('/quickmemo/memo_note.php', 1), ['id' => $object->id]); + $head[$h][1] = $langs->trans('Notes'); + if ($nbNote > 0) { + $head[$h][1] .= (!getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') ? ''.$nbNote.'' : ''); + } + $head[$h][2] = 'note'; + $h++; + } + } + + if ($showtabofpagedocument) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->quickmemo->dir_output."/memo/".dol_sanitizeFileName($object->ref); + $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); + $nbLinks = Link::count($db, $object->element, $object->id); + $head[$h][0] = dolBuildUrl(dol_buildpath("/quickmemo/memo_document.php", 1), ['id' => $object->id]); + $head[$h][1] = $langs->trans('Documents'); + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } + $head[$h][2] = 'document'; + $h++; + } + + if ($showtabofpageagenda) { + $head[$h][0] = dolBuildUrl(dol_buildpath("/quickmemo/memo_agenda.php", 1), ['id' => $object->id]); + $head[$h][1] = $langs->trans("Events"); + $head[$h][2] = 'agenda'; + $h++; + } + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + //$this->tabs = array( + // 'entity:+tabname:Title:@quickmemo:/quickmemo/mypage.php?id=__ID__' + //); // to add new tab + //$this->tabs = array( + // 'entity:-tabname:Title:@quickmemo:/quickmemo/mypage.php?id=__ID__' + //); // to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'memo@quickmemo'); + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'memo@quickmemo', 'remove'); + + return $head; +} diff --git a/htdocs/quickmemo/memo_list.php b/htdocs/quickmemo/memo_list.php new file mode 100644 index 00000000000..bd4b73dd146 --- /dev/null +++ b/htdocs/quickmemo/memo_list.php @@ -0,0 +1,992 @@ + + * Copyright (C) 2024 Frédéric France + * Copyright (C) 2026 John BOTELLA + * + * 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 3 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, see . + */ + +/** + * \file memo_list.php + * \ingroup quickmemo + * \brief List page for memo + */ + +// General defined Options +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('MAIN_AUTHENTICATION_MODE')) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined('MAIN_LANG_DEFAULT')) define('MAIN_LANG_DEFAULT', 'auto'); // Force LANG (language) to a particular value +//if (! defined('MAIN_SECURITY_FORCECSP')) define('MAIN_SECURITY_FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined('NOLOGIN')) define('NOLOGIN', '1'); // Do not use login - if this page is public (can be called outside logged session). This includes the NOIPCHECK too. +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // Do not load html.form.class.php +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // Do not load and show top and left menu +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOSESSION')) define('NOSESSION', '1'); // On CLI mode, no need to use web sessions +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) + + +// Load Dolibarr environment +require '../main.inc.php'; + +/** + * The main.inc.php has been included so the following variable are now defined: + * @var Conf $conf + * @var DoliDB $db + * @var HookManager $hookmanager + * @var Translate $langs + * @var User $user + */ +include_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +// load module libraries +include_once __DIR__.'/class/memo.class.php'; +// for other modules +//dol_include_once('/othermodule/class/otherobject.class.php'); + +// Load translation files required by the page +$langs->loadLangs(array("quickmemo", "other")); + +// Get parameters +$action = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; // The action 'create'/'add', 'edit'/'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOSTINT('show_files'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$toselect = GETPOST('toselect', 'array:int'); // Array of ids of elements selected into a list +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : getDolDefaultContextPage(__FILE__); // To manage different context of search +$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page +$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') +$mode = GETPOST('mode', 'aZ'); // The display mode ('list', 'kanban', 'hierarchy', 'calendar', 'gantt', ...) +$groupby = GETPOST('groupby', 'aZ09'); // Example: $groupby = 'p.fk_opp_status' or $groupby = 'p.fk_statut' + +$id = GETPOSTINT('id'); +$ref = GETPOST('ref', 'alpha'); + +// Load variable for pagination +$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit; +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); +$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT('page'); +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + // If $page is not defined, or '' or -1 or if we click on clear filters + $page = 0; +} +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +// Initialize technical objects +$object = new Memo($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->quickmemo->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array($contextpage)); // Note that conf->hooks_modules contains array of activated contexes + +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); +//$extrafields->fetch_name_optionals_label($object->table_element_line); + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +// Default sort order (if not yet defined by previous GETPOST) +if (!$sortfield) { + reset($object->fields); // Reset is required to avoid key() to return null. + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} + +// Initialize array of search criteria +$search_all = trim(GETPOST('search_all', 'alphanohtml')); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } + if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + $search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOSTINT('search_'.$key.'_dtstartmonth'), GETPOSTINT('search_'.$key.'_dtstartday'), GETPOSTINT('search_'.$key.'_dtstartyear')); + $search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOSTINT('search_'.$key.'_dtendmonth'), GETPOSTINT('search_'.$key.'_dtendday'), GETPOSTINT('search_'.$key.'_dtendyear')); + } +} + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array(); +// foreach ($object->fields as $key => $val) { +// if (!empty($val['searchall'])) { +// $fieldstosearchall['t.'.$key] = $val['label']; +// } +// } +// $parameters = array('fieldstosearchall'=>$fieldstosearchall); +// $reshook = $hookmanager->executeHooks('completeFieldsToSearchAll', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +// if ($reshook > 0) { +// $fieldstosearchall = empty($hookmanager->resArray['fieldstosearchall']) ? array() : $hookmanager->resArray['fieldstosearchall']; +// } elseif ($reshook == 0) { +// $fieldstosearchall = array_merge($fieldstosearchall, empty($hookmanager->resArray['fieldstosearchall']) ? array() : $hookmanager->resArray['fieldstosearchall']); +// } + +// Definition of array of fields for columns from ->fields +$tableprefix = 't'; +$arrayfields = array(); +foreach ($object->fields as $key => $val) { + // If $val['visible']==0, then we never show the field + if (!empty($val['visible'])) { + $visible = (int) dol_eval((string) $val['visible'], 1); + $arrayfields[$tableprefix.'.'.$key] = array( + 'label' => $val['label'], + 'checked' => (($visible < 0) ? '0' : '1'), + 'enabled' => (string) (int) (abs($visible) != 3 && (bool) dol_eval((string) $val['enabled'], 1)), + 'position' => $val['position'], + 'help' => isset($val['help']) ? $val['help'] : '' + ); + } +} + +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + +// Complete arrayfields with special fields +/*$arrayfields = array_merge($arrayfields, array( + 'anotherfield' => array('type'=>'integer', 'label'=>'AnotherField', 'checked'=>'1', 'enabled'=>'1', 'position'=>'90', 'csslist'=>'right'), +));*/ + +$object->fields = dol_sort_array($object->fields, 'position'); +$arrayfields = dol_sort_array($arrayfields, 'position'); + +// There is several ways to check permission. +$permissiontoread = $user->hasRight('quickmemo', 'memo', 'read'); +$permissiontoadd = $user->hasRight('quickmemo', 'memo', 'write'); +$permissiontodelete = $user->hasRight('quickmemo', 'memo', 'delete'); + + +// Security check (enable the most restrictive one) +if ($user->socid > 0) { + accessforbidden(); +} +//if ($user->socid > 0) accessforbidden(); +//$socid = 0; if ($user->socid > 0) $socid = $user->socid; +//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0); +//restrictedArea($user, $object->module, 0, $object->table_element, $object->element, 'fk_soc', 'rowid', $isdraft); +if (!isModEnabled("quickmemo")) { + accessforbidden('Module quickmemo not enabled'); +} +if (!$permissiontoread) { + accessforbidden(); +} + + +/* + * Actions + */ + +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; + $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} + +$parameters = array('arrayfields' => &$arrayfields); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} + +if (empty($reshook)) { + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers + foreach ($object->fields as $key => $val) { + $search[$key] = ''; + if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + $search[$key.'_dtstart'] = ''; + $search[$key.'_dtend'] = ''; + } + } + $search_all = ''; + $toselect = array(); + $search_array_options = array(); + } + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } + + // Mass actions + $objectclass = 'Memo'; + $objectlabel = 'Memo'; + $uploaddir = $conf->quickmemo->dir_output; + + global $error; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + + // You can add more action here + // if ($action == 'xxx' && $permissiontoxxx) ... + + if ($massaction === 'unarchive') { + if (!empty($toselect)) { + $countUnarchived = 0; + foreach ($toselect as $idMemo) { + // TODO Récupérer le mémo attention à ne pas récupérer un model ils ne peuvent pas étre rcupr c'est des models + $selectdModel = new Memo($db); + if ($selectdModel->fetch($idMemo) <= 0) { + $idMemo = (int) $idMemo; // sanitize + setEventMessage($langs->trans('QuickMemoLoadMemosError').' : '. (int) $idMemo, 'errors'); + continue; + } + + if ($selectdModel->status !== Memo::STATUS_ARCHIVED) { + setEventMessage($langs->trans('QuickMemoCantChangeThisPrivateNote').' : '. (int) $idMemo, 'errors'); + continue; + } + + if ($user->id != $selectdModel->fk_user_creat && $selectdModel->private_tpl) { + setEventMessage($langs->trans('QuickMemoCantChangeThisPrivateNote').' : '. (int) $idMemo, 'errors'); + continue; + } + + if ($selectdModel->setUnArchived($user) <= 0) { + setEventMessage($langs->trans('QuickMemoUnArchiveError').' : '. (int) $idMemo, 'errors'); + continue; + } + + $countUnarchived++; + } + + if ($countUnarchived>0) { + setEventMessage($langs->trans($countUnarchived > 1 ? 'QuickMemoUnArchiveCount' : 'QuickMemoUnArchived', $countUnarchived)); + } + } else { + setEventMessage($langs->trans('PleaseSelectAtLeastOneRow'), 'warnings'); + } + } +} + + + +/* + * View + */ + +$form = new Form($db); + +$now = dol_now(); + +$title = $langs->trans("Memos"); +//$help_url = "EN:Module_Memo|FR:Module_Memo_FR|ES:Módulo_Memo"; +$help_url = ''; +$morejs = array(); +$morecss = array( + 'quickmemo/css/memo.css' +); + + +// Build and execute select +// -------------------------------------------------------------------- +$sql = "SELECT"; +$sql .= " ".$object->getFieldList('t'); +// Add fields from extrafields +if (!empty($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : ""); + } +} +// Add fields from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql = preg_replace('/,\s*$/', '', $sql); + +$sqlfields = $sql; // $sql fields to remove for count total + +$sql .= " FROM ".$db->prefix().$object->table_element." as t"; +//$sql .= " LEFT JOIN ".$db->prefix()."anothertable as rc ON rc.parent = t.rowid"; +if (isset($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".$db->prefix().$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +// Add table from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; + +if (!empty($object->ismultientitymanaged) && (int) $object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element, (GETPOSTINT('search_current_entity') ? 0 : 1)).")"; +} elseif (preg_match('/^\w+@\w+$/', (string) $object->ismultientitymanaged)) { + $tmparray = explode('@', (string) $object->ismultientitymanaged); + $sql .= " LEFT JOIN ".$object->db->prefix().$tmparray[1]." as pt ON t.".$db->sanitize($tmparray[0])." = pt.rowid"; + $sql .= " WHERE pt.entity IN (".getEntity($object->element, (GETPOSTINT('search_current_entity') ? 0 : 1)).")"; +} else { + $sql .= " WHERE 1 = 1"; +} + +$sql .= ' AND ('.implode(' OR ', [ + '( t.status = '.Memo::STATUS_ARCHIVED.' AND t.private = 0 OR t.fk_user_creat = '.(int) $user->id.' )', + '( t.status = '.Memo::STATUS_VALIDATED.' AND t.private = 0 OR t.fk_user_creat = '.(int) $user->id.' )', + '( t.status = '.Memo::STATUS_TPL.' AND t.private_tpl = 0 OR t.fk_user_creat = '.(int) $user->id.' )', +]).') '; + + + + +foreach ($search as $key => $val) { + if (array_key_exists($key, $object->fields)) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } + + if (empty($object->fields[$key])) { + continue; + } + + $field_spec = $object->fields[$key]; + $mode_search = (($object->isInt($field_spec) || $object->isFloat($field_spec)) ? 1 : 0); + if ((strpos($field_spec['type'], 'integer:') === 0) || (strpos($field_spec['type'], 'sellist:') === 0) || !empty($field_spec['arrayofkeyval'])) { + if ($search[$key] == '-1' || ($search[$key] === '0' && (empty($field_spec['arrayofkeyval']) || !array_key_exists('0', $field_spec['arrayofkeyval'])))) { + $search[$key] = ''; + } + $mode_search = 2; + } + if ($field_spec['type'] === 'boolean') { + $mode_search = 1; + if ($search[$key] == '-1') { + $search[$key] = ''; + } + } + if (empty($field_spec['searchmulti'])) { + if (!is_array($search[$key]) && $search[$key] != '') { + $sql .= natural_search("t.".$db->escape($key), $search[$key], (($key == 'status') ? 2 : $mode_search)); + } + } else { + if (is_array($search[$key]) && !empty($search[$key])) { + $sql .= natural_search("t.".$db->escape($key), implode(',', $search[$key]), (($key == 'status') ? 2 : $mode_search)); + } + } + } else { + if (preg_match('/(_dtstart|_dtend)$/', $key) && $search[$key] != '') { + $columnName = preg_replace('/(_dtstart|_dtend)$/', '', $key); + if (preg_match('/^(date|timestamp|datetime)/', $object->fields[$columnName]['type'])) { + if (preg_match('/_dtstart$/', $key)) { + $sql .= " AND t.".$db->sanitize($columnName)." >= '".$db->idate($search[$key])."'"; + } + if (preg_match('/_dtend$/', $key)) { + $sql .= " AND t.".$db->sanitize($columnName)." <= '".$db->idate($search[$key])."'"; + } + } + } + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} +/* +// If the internal user must only see his customers, force searching by him +$search_sale = 0; +if (!$user->hasRight('societe', 'client', 'voir')) { + $search_sale = $user->id; +} +// Search on sale representative +if ($search_sale && $search_sale != '-1') { + if ($search_sale == -2) { + $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".$db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)"; + } elseif ($search_sale > 0) { + $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".$db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")"; + } +} +// Search on socid +if ($socid) { + $sql .= " AND t.fk_soc = ".((int) $socid); +} +*/ +//$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); +// Add where from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; +// Add where from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; + +/* If a group by is required +$sql .= " GROUP BY "; +foreach($object->fields as $key => $val) { + $sql .= "t.".$db->sanitize($key).", "; +} +// Add fields from extrafields +if (!empty($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : ''); + } +} +// Add groupby from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +if (empty($reshook)) { + $sql .= $hookmanager->resPrint; +} else { + $sql = $hookmanager->resPrint; +} + +$sql = preg_replace('/,\s*$/', '', $sql); +*/ + +// Add HAVING from hooks +/* +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListHaving', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +if (empty($reshook)) { + $sql .= empty($hookmanager->resPrint) ? "" : " HAVING 1=1 ".$hookmanager->resPrint; +} else { + $sql = $hookmanager->resPrint; +} +*/ + +// Count total nb of records +$nbtotalofrecords = ''; +if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) { + /* The fast and low memory method to get and count full list converts the sql into a sql count */ + $sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql); + $sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount); + + $resql = $db->query($sqlforcount); + if ($resql) { + $objforcount = $db->fetch_object($resql); + $nbtotalofrecords = $objforcount->nbtotalofrecords; + } else { + dol_print_error($db); + } + + if (($page * $limit) > (int) $nbtotalofrecords) { // if total resultset is smaller than the paging size (filtering), goto and load page 0 + $page = 0; + $offset = 0; + } + $db->free($resql); +} + +// Complete request and execute it with limit +$sql .= $db->order($sortfield, $sortorder); +if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); +} + +$resql = $db->query($sql); +if (!$resql) { + dol_print_error($db); + exit; +} + +$num = $db->num_rows($resql); + + +// Direct jump if only one record found +if ($num == 1 && getDolGlobalInt('MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE') && $search_all && !$page) { + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".dol_buildpath('/quickmemo/memo_card.php', 1).'?id='.((int) $id)); + exit; +} + + +// Output page +// -------------------------------------------------------------------- + +llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', 'mod-quickmemo page-list bodyforlist'); // Can use also classforhorizontalscrolloftabs instead of bodyforlist for a horizontal scroll in the table instead of page + +// Example : Adding jquery code +// print ''; + +$arrayofselected = is_array($toselect) ? $toselect : array(); + +$param = ''; +if (!empty($mode)) { + $param .= '&mode='.urlencode($mode); +} +if (!empty($contextpage) && $contextpage != getDolDefaultContextPage(__FILE__)) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.((int) $limit); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} +if ($groupby != '') { + $param .= '&groupby='.urlencode($groupby); +} +foreach ($search as $key => $val) { + if (is_array($search[$key])) { + foreach ($search[$key] as $skey) { + if ($skey != '') { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } + } elseif (preg_match('/(_dtstart|_dtend)$/', $key) && !empty($val)) { + $param .= '&search_'.$key.'month='.GETPOSTINT('search_'.$key.'month'); + $param .= '&search_'.$key.'day='.GETPOSTINT('search_'.$key.'day'); + $param .= '&search_'.$key.'year='.GETPOSTINT('search_'.$key.'year'); + } elseif ($search[$key] != '') { + $param .= '&search_'.$key.'='.urlencode((string) $search[$key]); + } +} +// Add $param from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; +// Add $param from hooks +$parameters = array('param' => &$param); +$reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +$param .= $hookmanager->resPrint; + +// List of mass actions available +$arrayofmassactions = array( + 'unarchive'=> $langs->trans("UnarchiveMemo"), + //'generate_doc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"), + //'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"), + //'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"), +); +if (!empty($permissiontodelete)) { + $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete"); +} +if (GETPOSTINT('nomassaction') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); + +print '
'."\n"; +if ($optioncss != '') { + print ''; +} +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + + +$newcardbutton = ''; +$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', $_SERVER["PHP_SELF"].'?mode=common'.preg_replace('/(&|\?)*(mode|groupby)=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss' => 'reposition')); +$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/(&|\?)*(mode|groupby)=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss' => 'reposition')); +//$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanbanGroupBy'), '', 'fa fa-grip-vertical imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanbangroupby&groupby=p.fk_opp_status'.preg_replace('/(&|\?)*(mode|groupby)=[^&]+/', '', $param), '', ($mode == 'kanbangroupby' ? 2 : 1), array('morecss' => 'reposition')); +//$newcardbutton .= dolGetButtonTitle($langs->trans('HierarchicView'), '', 'fa fa-stream paddingleft imgforviewmode', $_SERVER["PHP_SELF"].'?mode=hierarchy'.preg_replace('/(&|\?)*(mode|groupby)=[^&]+/', '', $param), '', (($mode == 'hierarchy') ? 2 : 1), array('morecss' => 'reposition')); +//$newcardbutton .= dolGetButtonTitleSeparator(); +//$newcardbutton .= dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/quickmemo/memo_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd); + +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1); + +// Add code for pre mass action (confirmation or email presend form) +$topicmail = "SendMemoRef"; +$modelmail = "memo"; +$objecttmp = new Memo($db); +$trackid = 'xxxx'.$object->id; +include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; + +if ($search_all) { + $setupstring = ''; + // @phan-suppress-next-line PhanEmptyForeach + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + $setupstring .= $key."=".$val.";"; + } + print ''."\n"; + print '
'.$langs->trans("FilterOnInto", $search_all).implode(', ', $fieldstosearchall).'
'."\n"; +} + +$moreforfilter = ''; +/*$moreforfilter.='
'; +$moreforfilter.= $langs->trans('MyFilter') . ': '; +$moreforfilter.= '
';*/ + +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +if (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; +} else { + $moreforfilter = $hookmanager->resPrint; +} +$parameters = array( + 'arrayfields' => &$arrayfields, +); + +if (!empty($moreforfilter)) { + print '
'; + print $moreforfilter; + print '
'; +} + +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$htmlofselectarray = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, $conf->main_checkbox_left_column); // This also change content of $arrayfields with user setup +$selectedfields = (($mode != 'kanban' && $mode != 'kanbangroupby') ? $htmlofselectarray : ''); +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); + +print '
'; // You can use div-table-responsive-no-min if you don't need reserved height for your table +print ''."\n"; + +// Fields title search +// -------------------------------------------------------------------- +print ''; +// Action column +if ($conf->main_checkbox_left_column) { + print ''; +} +foreach ($object->fields as $key => $val) { + //$searchkey = empty($search[$key]) ? '' : $search[$key]; + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('id', 'rowid', 'ref', 'status')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { + print ''; + } +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + +// Fields from hook +$parameters = array('arrayfields' => $arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +/*if (!empty($arrayfields['anotherfield']['checked'])) { + print ''; +}*/ +// Action column +if (!$conf->main_checkbox_left_column) { + print ''; +} +print ''."\n"; + +$totalarray = array(); +$totalarray['nbfield'] = 0; + +// Fields title label +// -------------------------------------------------------------------- +print ''; +// Action column +if ($conf->main_checkbox_left_column) { + print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; + $totalarray['nbfield']++; +} +foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('id', 'rowid', 'ref', 'status')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + $cssforfield = preg_replace('/small\s*/', '', $cssforfield); // the 'small' css must not be used for the title label + if (!empty($arrayfields['t.'.$key]['checked'])) { + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''), 0, (empty($val['helplist']) ? '' : $val['helplist']))."\n"; + $totalarray['nbfield']++; + } +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; +// Hook fields +$parameters = array('arrayfields' => $arrayfields, 'param' => $param, 'sortfield' => $sortfield, 'sortorder' => $sortorder, 'totalarray' => &$totalarray); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +/*if (!empty($arrayfields['anotherfield']['checked'])) { + print ''; + $totalarray['nbfield']++; +}*/ +// Action column +if (!$conf->main_checkbox_left_column) { + print getTitleFieldOfList(($mode != 'kanban' ? $selectedfields : ''), 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; + $totalarray['nbfield']++; +} +print ''."\n"; + +// Detect if we need a fetch on each output line +$needToFetchEachLine = 0; +if (isset($extrafields->attributes[$object->table_element]['computed']) && is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (!is_null($val) && preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } + } +} + + +// Loop on record +// -------------------------------------------------------------------- +$i = 0; +$savnbfield = $totalarray['nbfield']; +$totalarray = array(); +$totalarray['nbfield'] = 0; +$imaxinloop = ($limit ? min($num, $limit) : $num); +while ($i < $imaxinloop) { + $obj = $db->fetch_object($resql); + if (empty($obj)) { + break; // Should not happen + } + + // Store properties in $object + $object->setVarsFromFetchObj($obj); + + /* + $object->thirdparty = null; + if ($obj->fk_soc > 0) { + if (!empty($conf->cache['thirdparty'][$obj->fk_soc])) { + $companyobj = $conf->cache['thirdparty'][$obj->fk_soc]; + } else { + $companyobj = new Societe($db); + $companyobj->fetch($obj->fk_soc); + $conf->cache['thirdparty'][$obj->fk_soc] = $companyobj; + } + + $object->thirdparty = $companyobj; + }*/ + + if ($mode == 'kanban' || $mode == 'kanbangroupby') { + if ($i == 0) { + print ''; + } + } else { + // Show line of result + $j = 0; + print ''; + + // Action column + if ($conf->main_checkbox_left_column) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } + // Fields + foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } + + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowraponall'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowraponall'; + } + + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('id', 'rowid', 'ref', 'status')) && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; + + if (!empty($arrayfields['t.'.$key]['checked'])) { + print '$key) && !in_array($key, array('ref'))) { + print ' title="'.dol_escape_htmltag((string) $object->$key).'"'; + } + print '>'; + if ($key == 'status') { + print $object->getLibStatut(5); + } elseif ($key == 'rowid') { + print $object->showOutputField($val, $key, (string) $object->id, ''); + } else { + if ($val['type'] == 'html') { + print '
'; + } + print $object->showOutputField($val, $key, (string) $object->$key, ''); + if ($val['type'] == 'html') { + print '
'; + } + } + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure']) && $val['isameasure'] == 1) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } + if (!isset($totalarray['val'])) { + $totalarray['val'] = array(); + } + if (!isset($totalarray['val']['t.'.$key])) { + $totalarray['val']['t.'.$key] = 0; + } + $totalarray['val']['t.'.$key] += $object->$key; + } + } + } + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + // Fields from hook + $parameters = array('arrayfields' => $arrayfields, 'object' => $object, 'obj' => $obj, 'i' => $i, 'totalarray' => &$totalarray); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + + /*if (!empty($arrayfields['anotherfield']['checked'])) { + print '
'; + }*/ + + // Action column + if (empty($conf->main_checkbox_left_column)) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } + + print ''."\n"; + } + + $i++; +} + +// Show total line +include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; + +// If no record found +if ($num == 0) { + $colspan = 1; + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } + print ''; +} + + +$db->free($resql); + +$parameters = array('arrayfields' => $arrayfields, 'sql' => $sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print '
'; + $searchpicto = $form->showFilterButtons('left'); + print $searchpicto; + print ''; + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + if (empty($val['searchmulti'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], (isset($search[$key]) ? $search[$key] : ''), 1, 0, 0, '', 1, 0, 0, '', 'maxwidth100'.($key == 'status' ? ' search_status width100 onrightofpage' : ''), 1); + } else { + print $form->multiselectarray('search_'.$key, $val['arrayofkeyval'], (isset($search[$key]) ? $search[$key] : ''), 0, 0, 'maxwidth100'.($key == 'status' ? ' search_status width100 onrightofpage' : ''), 1); + } + } elseif ((strpos($val['type'], 'integer:') === 0) || (strpos($val['type'], 'sellist:') === 0)) { + print $object->showInputField($val, $key, (isset($search[$key]) ? $search[$key] : ''), '', '', 'search_', $cssforfield.' maxwidth250', 1); + } elseif (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + print '
'; + print $form->selectDate($search[$key.'_dtstart'] ? $search[$key.'_dtstart'] : '', "search_".$key."_dtstart", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); + print '
'; + print '
'; + print $form->selectDate($search[$key.'_dtend'] ? $search[$key.'_dtend'] : '', "search_".$key."_dtend", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); + print '
'; + } elseif ($key == 'lang') { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; + $formadmin = new FormAdmin($db); + print $formadmin->select_language((isset($search[$key]) ? $search[$key] : ''), 'search_lang', 0, array(), 1, 0, 0, 'minwidth100imp maxwidth125', 2); + } elseif ($val['type'] === 'boolean') { + print $form->selectyesno('search_' . $key, $search[$key] ?? '', 1, false, 1); + } else { + print ''; + } + print '
'; + $searchpicto = $form->showFilterButtons(); + print $searchpicto; + print '
'.$langs->trans("AnotherField").'
'; + print '
'; + } + // Output Kanban + $selected = -1; + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + $selected = 0; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } + } + //print $object->getKanbanView('', array('thirdparty'=>$object->thirdparty, 'selected' => $selected)); + print $object->getKanbanView('', array('selected' => $selected)); + if ($i == ($imaxinloop - 1)) { + print '
'; + print '
'; + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + $selected = 0; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } + print ''; + } + print ''.$obj->anotherfield.''; + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + $selected = 0; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } + print ''; + } + print '
'.$langs->trans("NoRecordFound").'
'."\n"; +print '
'."\n"; + +print '
'."\n"; + +if (in_array('builddoc', array_keys($arrayofmassactions)) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { + $hidegeneratedfilelistifempty = 1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } + + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; + $formfile = new FormFile($db); + + // Show list of available documents + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); + + $filedir = $diroutputmassaction; + $genallowed = $permissiontoread; + $delallowed = $permissiontoadd; + + print $formfile->showdocuments('massfilesarea_'.$object->module, '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/test/phpunit/CommonClassTest.class.php b/test/phpunit/CommonClassTest.class.php index 0229bedb94c..7e9a3118f7b 100644 --- a/test/phpunit/CommonClassTest.class.php +++ b/test/phpunit/CommonClassTest.class.php @@ -486,6 +486,7 @@ abstract class CommonClassTest extends TestCase 'productsupplierprice' => null, 'project' => 'Projet', 'propal' => 'Propale', + 'quickmemo' => 'QuickMemo', 'receiptprinter' => 'ReceiptPrinter', 'reception' => 'Reception', 'recruitment' => 'Recruitment',