mirror of
https://github.com/Kingsrook/qqq-frontend-material-dashboard.git
synced 2025-07-21 14:48:43 +00:00
Compare commits
106 Commits
snapshot-i
...
snapshot-f
Author | SHA1 | Date | |
---|---|---|---|
71a1bfaa6b | |||
d9e9a0be08 | |||
aefb282a0e | |||
fb57718c1c | |||
ba213b038b | |||
69daf47021 | |||
1d24b9b40c | |||
f44ba8d6d3 | |||
dc131d5189 | |||
2b5cc1610f | |||
a36bdb1474 | |||
c2926d26e8 | |||
eb42a86655 | |||
b7f715f832 | |||
16a08cfd42 | |||
f5919c66ab | |||
0831a87674 | |||
dd5cd459ce | |||
c200cc9fab | |||
17f378131d | |||
376a7a342e | |||
fcadea3192 | |||
086ab775fc | |||
5693661d20 | |||
8c9224aceb | |||
d750ef0930 | |||
267ead925b | |||
f925ad9116 | |||
1859dd603d | |||
74f8f11737 | |||
0629172270 | |||
1bf1f09e9d | |||
e0f689544d | |||
f3d08ef683 | |||
1aff749f72 | |||
ccc622e0e9 | |||
a6662eeb07 | |||
c8b673fb46 | |||
f19e36a6bf | |||
c708ec3b9a | |||
7e40fa90e9 | |||
680d185eb5 | |||
4f37488d37 | |||
d20700edb1 | |||
d17c7f6990 | |||
0d7849b7dc | |||
57098b5f05 | |||
7316b6141b | |||
8bc2479716 | |||
010f80def3 | |||
13d7cc6825 | |||
ca715af84a | |||
65aaf4fce1 | |||
8dc8ae0b6d | |||
8707aa8a94 | |||
e7d870a7fa | |||
38b8f47409 | |||
de8594bfe1 | |||
3c8180cf51 | |||
2e48aa3eba | |||
feb1cc5c86 | |||
c2ad1c34be | |||
7b364a1e09 | |||
6ef4dd8fbe | |||
17893a0cfd | |||
33056963a4 | |||
ef8eecd6cb | |||
4c6955b6ed | |||
11f1250d73 | |||
387aad8087 | |||
47cf625c7c | |||
8459263762 | |||
8fe8fd41eb | |||
7bda54b4a6 | |||
362c528514 | |||
727990ed4b | |||
a84b0a0243 | |||
6faca42b3b | |||
cb3162f084 | |||
73c907a3e1 | |||
48e3eeabd4 | |||
04932030df | |||
eafd8d98cd | |||
2c0725852e | |||
53c3e4d078 | |||
5e0e4c37bb | |||
cb7fa641eb | |||
cdec98afd8 | |||
7e2a46b362 | |||
803725b8f1 | |||
6b8049d4ce | |||
d5381e23bf | |||
87ffd821f8 | |||
703868a725 | |||
dee4b91a96 | |||
f47924787a | |||
37b854baf0 | |||
fb2e392dcb | |||
034264eaa1 | |||
3558a91e7b | |||
e5e49a6db8 | |||
4c9c9ab80e | |||
30991cb34e | |||
2fd6272ea3 | |||
b63d74f785 | |||
ff946df461 |
@ -1,12 +0,0 @@
|
||||
import {defineConfig} from "cypress";
|
||||
|
||||
export default defineConfig({
|
||||
e2e: {
|
||||
viewportHeight: 1000,
|
||||
viewportWidth: 1200,
|
||||
setupNodeEvents(on, config)
|
||||
{
|
||||
// implement node event listeners here
|
||||
},
|
||||
},
|
||||
});
|
2985
package-lock.json
generated
2985
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -6,7 +6,7 @@
|
||||
"@auth0/auth0-react": "1.10.2",
|
||||
"@emotion/react": "11.7.1",
|
||||
"@emotion/styled": "11.6.0",
|
||||
"@kingsrook/qqq-frontend-core": "1.0.96",
|
||||
"@kingsrook/qqq-frontend-core": "1.0.102",
|
||||
"@mui/icons-material": "5.4.1",
|
||||
"@mui/material": "5.11.1",
|
||||
"@mui/styles": "5.11.1",
|
||||
@ -41,6 +41,8 @@
|
||||
"react-ace": "10.1.0",
|
||||
"react-chartjs-2": "3.0.4",
|
||||
"react-cookie": "4.1.1",
|
||||
"react-dnd": "16.0.1",
|
||||
"react-dnd-html5-backend": "16.0.1",
|
||||
"react-dom": "18.0.0",
|
||||
"react-ga4": "2.1.0",
|
||||
"react-github-btn": "1.2.1",
|
||||
|
17
src/App.tsx
17
src/App.tsx
@ -49,6 +49,7 @@ import EntityEdit from "qqq/pages/records/edit/RecordEdit";
|
||||
import RecordQuery from "qqq/pages/records/query/RecordQuery";
|
||||
import RecordDeveloperView from "qqq/pages/records/view/RecordDeveloperView";
|
||||
import RecordView from "qqq/pages/records/view/RecordView";
|
||||
import RecordViewByUniqueKey from "qqq/pages/records/view/RecordViewByUniqueKey";
|
||||
import GoogleAnalyticsUtils, {AnalyticsModel} from "qqq/utils/GoogleAnalyticsUtils";
|
||||
import Client from "qqq/utils/qqq/Client";
|
||||
import ProcessUtils from "qqq/utils/qqq/ProcessUtils";
|
||||
@ -392,6 +393,13 @@ export default function App()
|
||||
component: <RecordView table={table} />,
|
||||
});
|
||||
|
||||
routeList.push({
|
||||
name: `${app.label} View`,
|
||||
key: `${app.name}.view`,
|
||||
route: `${path}/key`,
|
||||
component: <RecordViewByUniqueKey table={table} />,
|
||||
});
|
||||
|
||||
routeList.push({
|
||||
name: `${app.label}`,
|
||||
key: `${app.name}.edit`,
|
||||
@ -664,10 +672,16 @@ export default function App()
|
||||
const [dotMenuOpen, setDotMenuOpen] = useState(false);
|
||||
const [keyboardHelpOpen, setKeyboardHelpOpen] = useState(false);
|
||||
const [helpHelpActive] = useState(queryParams.has("helpHelp"));
|
||||
const [userId, setUserId] = useState(user?.email);
|
||||
|
||||
useEffect(() =>
|
||||
{
|
||||
setUserId(user?.email)
|
||||
}, [user]);
|
||||
|
||||
|
||||
const [googleAnalyticsUtils] = useState(new GoogleAnalyticsUtils());
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@ -689,6 +703,7 @@ export default function App()
|
||||
dotMenuOpen: dotMenuOpen,
|
||||
keyboardHelpOpen: keyboardHelpOpen,
|
||||
helpHelpActive: helpHelpActive,
|
||||
userId: userId,
|
||||
setPageHeader: (header: string | JSX.Element) => setPageHeader(header),
|
||||
setAccentColor: (accentColor: string) => setAccentColor(accentColor),
|
||||
setAccentColorLight: (accentColorLight: string) => setAccentColorLight(accentColorLight),
|
||||
|
@ -59,6 +59,7 @@ interface QContext
|
||||
pathToLabelMap?: {[path: string]: string};
|
||||
branding?: QBrandingMetaData;
|
||||
helpHelpActive?: boolean;
|
||||
userId?: string;
|
||||
}
|
||||
|
||||
const defaultState = {
|
||||
|
@ -22,6 +22,7 @@
|
||||
package com.kingsrook.qqq.frontend.materialdashboard.model.metadata;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
@ -30,6 +31,8 @@ import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QSupplementalTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.model.metadata.fieldrules.FieldRule;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@ -37,8 +40,11 @@ import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
|
||||
*******************************************************************************/
|
||||
public class MaterialDashboardTableMetaData extends QSupplementalTableMetaData
|
||||
{
|
||||
public static final String TYPE = "materialDashboard";
|
||||
|
||||
private List<List<String>> gotoFieldNames;
|
||||
private List<String> defaultQuickFilterFieldNames;
|
||||
private List<String> defaultQuickFilterFieldNames;
|
||||
private List<FieldRule> fieldRules;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@ -58,10 +64,25 @@ public class MaterialDashboardTableMetaData extends QSupplementalTableMetaData
|
||||
@Override
|
||||
public String getType()
|
||||
{
|
||||
return ("materialDashboard");
|
||||
return (TYPE);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
public static MaterialDashboardTableMetaData ofOrWithNew(QTableMetaData table)
|
||||
{
|
||||
MaterialDashboardTableMetaData supplementalMetaData = (MaterialDashboardTableMetaData) table.getSupplementalMetaData(TYPE);
|
||||
if(supplementalMetaData == null)
|
||||
{
|
||||
supplementalMetaData = new MaterialDashboardTableMetaData();
|
||||
table.withSupplementalMetaData(supplementalMetaData);
|
||||
}
|
||||
|
||||
return (supplementalMetaData);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for gotoFieldNames
|
||||
@ -110,6 +131,41 @@ public class MaterialDashboardTableMetaData extends QSupplementalTableMetaData
|
||||
validateListOfFieldNames(tableMetaData, gotoFieldNameSubList, qInstanceValidator, prefix + "gotoFieldNames: ");
|
||||
}
|
||||
validateListOfFieldNames(tableMetaData, defaultQuickFilterFieldNames, qInstanceValidator, prefix + "defaultQuickFilterFieldNames: ");
|
||||
|
||||
for(FieldRule fieldRule : CollectionUtils.nonNullList(fieldRules))
|
||||
{
|
||||
validateFieldRule(qInstance, tableMetaData, qInstanceValidator, fieldRule, prefix);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
static void validateFieldRule(QInstance qInstance, QTableMetaData tableMetaData, QInstanceValidator qInstanceValidator, FieldRule fieldRule, String prefix)
|
||||
{
|
||||
qInstanceValidator.assertCondition(fieldRule.getTrigger() != null, prefix + "has a fieldRule without a trigger");
|
||||
qInstanceValidator.assertCondition(fieldRule.getAction() != null, prefix + "has a fieldRule without an action");
|
||||
|
||||
if(qInstanceValidator.assertCondition(StringUtils.hasContent(fieldRule.getSourceField()), prefix + "has a fieldRule without a sourceField"))
|
||||
{
|
||||
qInstanceValidator.assertNoException(() -> tableMetaData.getField(fieldRule.getSourceField()), prefix + "has a fieldRule with an unrecognized sourceField: " + fieldRule.getSourceField());
|
||||
}
|
||||
|
||||
if(StringUtils.hasContent(fieldRule.getTargetField()))
|
||||
{
|
||||
qInstanceValidator.assertNoException(() -> tableMetaData.getField(fieldRule.getTargetField()), prefix + "has a fieldRule with an unrecognized targetField: " + fieldRule.getTargetField());
|
||||
}
|
||||
|
||||
if(StringUtils.hasContent(fieldRule.getTargetWidget()))
|
||||
{
|
||||
if(qInstanceValidator.assertCondition(qInstance.getWidget(fieldRule.getTargetWidget()) != null, prefix + "has a widgetRule with an unrecognized targetWidget: " + fieldRule.getTargetWidget()))
|
||||
{
|
||||
qInstanceValidator.assertCondition(CollectionUtils.nonNullList(tableMetaData.getSections()).stream().anyMatch(s -> fieldRule.getTargetWidget().equals(s.getWidgetName())),
|
||||
prefix + "has a widgetRule with a targetWidget which is not used in any sections on the table");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -124,7 +180,7 @@ public class MaterialDashboardTableMetaData extends QSupplementalTableMetaData
|
||||
{
|
||||
if(qInstanceValidator.assertNoException(() -> tableMetaData.getField(fieldName), prefix + " unrecognized field name: " + fieldName))
|
||||
{
|
||||
qInstanceValidator.assertCondition(!usedNames.contains(fieldName), prefix + " has a duplicated field name: " + fieldName);
|
||||
qInstanceValidator.assertCondition(!usedNames.contains(fieldName), prefix + "has a duplicated field name: " + fieldName);
|
||||
usedNames.add(fieldName);
|
||||
}
|
||||
}
|
||||
@ -161,4 +217,51 @@ public class MaterialDashboardTableMetaData extends QSupplementalTableMetaData
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for fieldRules
|
||||
*******************************************************************************/
|
||||
public List<FieldRule> getFieldRules()
|
||||
{
|
||||
return (this.fieldRules);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for fieldRules
|
||||
*******************************************************************************/
|
||||
public void setFieldRules(List<FieldRule> fieldRules)
|
||||
{
|
||||
this.fieldRules = fieldRules;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for fieldRules
|
||||
*******************************************************************************/
|
||||
public MaterialDashboardTableMetaData withFieldRules(List<FieldRule> fieldRules)
|
||||
{
|
||||
this.fieldRules = fieldRules;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for fieldRules
|
||||
*******************************************************************************/
|
||||
public MaterialDashboardTableMetaData withFieldRule(FieldRule fieldRule)
|
||||
{
|
||||
if(this.fieldRules == null)
|
||||
{
|
||||
this.fieldRules = new ArrayList<>();
|
||||
}
|
||||
|
||||
this.fieldRules.add(fieldRule);
|
||||
|
||||
return (this);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,198 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qqq.frontend.materialdashboard.model.metadata.fieldrules;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** definition of rules for how UI fields should behave.
|
||||
**
|
||||
** e.g., one field being changed causing different things to be needed in another
|
||||
** field.
|
||||
*******************************************************************************/
|
||||
public class FieldRule implements Serializable
|
||||
{
|
||||
private FieldRuleTrigger trigger;
|
||||
private String sourceField;
|
||||
private FieldRuleAction action;
|
||||
private String targetField;
|
||||
|
||||
private String targetWidget;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for trigger
|
||||
*******************************************************************************/
|
||||
public FieldRuleTrigger getTrigger()
|
||||
{
|
||||
return (this.trigger);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for trigger
|
||||
*******************************************************************************/
|
||||
public void setTrigger(FieldRuleTrigger trigger)
|
||||
{
|
||||
this.trigger = trigger;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for trigger
|
||||
*******************************************************************************/
|
||||
public FieldRule withTrigger(FieldRuleTrigger trigger)
|
||||
{
|
||||
this.trigger = trigger;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for sourceField
|
||||
*******************************************************************************/
|
||||
public String getSourceField()
|
||||
{
|
||||
return (this.sourceField);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for sourceField
|
||||
*******************************************************************************/
|
||||
public void setSourceField(String sourceField)
|
||||
{
|
||||
this.sourceField = sourceField;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for sourceField
|
||||
*******************************************************************************/
|
||||
public FieldRule withSourceField(String sourceField)
|
||||
{
|
||||
this.sourceField = sourceField;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for action
|
||||
*******************************************************************************/
|
||||
public FieldRuleAction getAction()
|
||||
{
|
||||
return (this.action);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for action
|
||||
*******************************************************************************/
|
||||
public void setAction(FieldRuleAction action)
|
||||
{
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for action
|
||||
*******************************************************************************/
|
||||
public FieldRule withAction(FieldRuleAction action)
|
||||
{
|
||||
this.action = action;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for targetField
|
||||
*******************************************************************************/
|
||||
public String getTargetField()
|
||||
{
|
||||
return (this.targetField);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for targetField
|
||||
*******************************************************************************/
|
||||
public void setTargetField(String targetField)
|
||||
{
|
||||
this.targetField = targetField;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for targetField
|
||||
*******************************************************************************/
|
||||
public FieldRule withTargetField(String targetField)
|
||||
{
|
||||
this.targetField = targetField;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for targetWidget
|
||||
*******************************************************************************/
|
||||
public String getTargetWidget()
|
||||
{
|
||||
return (this.targetWidget);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for targetWidget
|
||||
*******************************************************************************/
|
||||
public void setTargetWidget(String targetWidget)
|
||||
{
|
||||
this.targetWidget = targetWidget;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for targetWidget
|
||||
*******************************************************************************/
|
||||
public FieldRule withTargetWidget(String targetWidget)
|
||||
{
|
||||
this.targetWidget = targetWidget;
|
||||
return (this);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qqq.frontend.materialdashboard.model.metadata.fieldrules;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** possible actions associated with field rules
|
||||
*******************************************************************************/
|
||||
public enum FieldRuleAction
|
||||
{
|
||||
CLEAR_TARGET_FIELD,
|
||||
RELOAD_WIDGET
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qqq.frontend.materialdashboard.model.metadata.fieldrules;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** possible triggers associated with field rules
|
||||
*******************************************************************************/
|
||||
public enum FieldRuleTrigger
|
||||
{
|
||||
ON_CHANGE
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qqq.frontend.materialdashboard.savedreports;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.model.metadata.MaterialDashboardTableMetaData;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.model.metadata.fieldrules.FieldRule;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.model.metadata.fieldrules.FieldRuleAction;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.model.metadata.fieldrules.FieldRuleTrigger;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Add frontend material dashboard enhacements to saved report table
|
||||
*******************************************************************************/
|
||||
public class SavedReportTableFrontendMaterialDashboardEnricher
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
public static void enrich(QTableMetaData tableMetaData)
|
||||
{
|
||||
MaterialDashboardTableMetaData materialDashboardTableMetaData = MaterialDashboardTableMetaData.ofOrWithNew(tableMetaData);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
// make changes to the tableName field clear the value in these fields //
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
for(String targetField : List.of("queryFilterJson", "columnsJson", "pivotTableJson"))
|
||||
{
|
||||
materialDashboardTableMetaData.withFieldRule(new FieldRule()
|
||||
.withSourceField("tableName")
|
||||
.withTrigger(FieldRuleTrigger.ON_CHANGE)
|
||||
.withAction(FieldRuleAction.CLEAR_TARGET_FIELD)
|
||||
.withTargetField(targetField));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -174,7 +174,8 @@ function QDynamicForm({formData, formLabel, bulkEditMode, bulkEditSwitchChangeHa
|
||||
<DynamicSelect
|
||||
tableName={field.possibleValueProps.tableName}
|
||||
processName={field.possibleValueProps.processName}
|
||||
fieldName={fieldName}
|
||||
possibleValueSourceName={field.possibleValueProps.possibleValueSourceName}
|
||||
fieldName={field.possibleValueProps.fieldName}
|
||||
isEditable={field.isEditable}
|
||||
fieldLabel=""
|
||||
initialValue={values[fieldName]}
|
||||
|
@ -172,6 +172,17 @@ class DynamicFormUtils
|
||||
{
|
||||
isPossibleValue: true,
|
||||
tableName: tableName,
|
||||
fieldName: field.name,
|
||||
initialDisplayValue: initialDisplayValue,
|
||||
};
|
||||
}
|
||||
else if(processName)
|
||||
{
|
||||
dynamicFormFields[field.name].possibleValueProps =
|
||||
{
|
||||
isPossibleValue: true,
|
||||
processName: processName,
|
||||
fieldName: field.name,
|
||||
initialDisplayValue: initialDisplayValue,
|
||||
};
|
||||
}
|
||||
@ -180,8 +191,9 @@ class DynamicFormUtils
|
||||
dynamicFormFields[field.name].possibleValueProps =
|
||||
{
|
||||
isPossibleValue: true,
|
||||
processName: processName,
|
||||
initialDisplayValue: initialDisplayValue,
|
||||
fieldName: field.name,
|
||||
possibleValueSourceName: field.possibleValueSourceName
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -28,16 +28,17 @@ import Box from "@mui/material/Box";
|
||||
import Switch from "@mui/material/Switch";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import {ErrorMessage, useFormikContext} from "formik";
|
||||
import React, {useEffect, useState} from "react";
|
||||
import colors from "qqq/assets/theme/base/colors";
|
||||
import MDTypography from "qqq/components/legacy/MDTypography";
|
||||
import Client from "qqq/utils/qqq/Client";
|
||||
import React, {useEffect, useState} from "react";
|
||||
|
||||
interface Props
|
||||
{
|
||||
tableName?: string;
|
||||
processName?: string;
|
||||
fieldName: string;
|
||||
fieldName?: string;
|
||||
possibleValueSourceName?: string;
|
||||
overrideId?: string;
|
||||
fieldLabel: string;
|
||||
inForm: boolean;
|
||||
@ -57,6 +58,8 @@ interface Props
|
||||
DynamicSelect.defaultProps = {
|
||||
tableName: null,
|
||||
processName: null,
|
||||
fieldName: null,
|
||||
possibleValueSourceName: null,
|
||||
inForm: true,
|
||||
initialValue: null,
|
||||
initialDisplayValue: null,
|
||||
@ -73,16 +76,74 @@ DynamicSelect.defaultProps = {
|
||||
},
|
||||
};
|
||||
|
||||
const {inputBorderColor} = colors;
|
||||
|
||||
|
||||
export const getAutocompleteOutlinedStyle = (isDisabled: boolean) =>
|
||||
{
|
||||
return ({
|
||||
"& .MuiOutlinedInput-root": {
|
||||
borderRadius: "0.75rem",
|
||||
},
|
||||
"& .MuiInputBase-root": {
|
||||
padding: "0.5rem",
|
||||
background: isDisabled ? "#f0f2f5!important" : "initial",
|
||||
},
|
||||
"& .MuiOutlinedInput-root .MuiAutocomplete-input": {
|
||||
padding: "0",
|
||||
fontSize: "1rem"
|
||||
},
|
||||
"& .Mui-disabled .MuiOutlinedInput-notchedOutline": {
|
||||
borderColor: inputBorderColor
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
const qController = Client.getInstance();
|
||||
|
||||
function DynamicSelect({tableName, processName, fieldName, overrideId, fieldLabel, inForm, initialValue, initialDisplayValue, initialValues, onChange, isEditable, isMultiple, bulkEditMode, bulkEditSwitchChangeHandler, otherValues, variant, initiallyOpen}: Props)
|
||||
function DynamicSelect({tableName, processName, fieldName, possibleValueSourceName, overrideId, fieldLabel, inForm, initialValue, initialDisplayValue, initialValues, onChange, isEditable, isMultiple, bulkEditMode, bulkEditSwitchChangeHandler, otherValues, variant, initiallyOpen}: Props)
|
||||
{
|
||||
const [open, setOpen] = useState(initiallyOpen);
|
||||
const [options, setOptions] = useState<readonly QPossibleValue[]>([]);
|
||||
const [searchTerm, setSearchTerm] = useState(null);
|
||||
const [firstRender, setFirstRender] = useState(true);
|
||||
const [otherValuesWhenResultsWereLoaded, setOtherValuesWhenResultsWereLoaded] = useState(JSON.stringify(Object.fromEntries((otherValues))))
|
||||
const {inputBorderColor} = colors;
|
||||
|
||||
useEffect(() =>
|
||||
{
|
||||
if(tableName && processName)
|
||||
{
|
||||
console.log("DynamicSelect - you may not provide both a tableName and a processName")
|
||||
}
|
||||
if(tableName && !fieldName)
|
||||
{
|
||||
console.log("DynamicSelect - if you provide a tableName, you must also provide a fieldName");
|
||||
}
|
||||
if(processName && !fieldName)
|
||||
{
|
||||
console.log("DynamicSelect - if you provide a processName, you must also provide a fieldName");
|
||||
}
|
||||
if(!fieldName && !possibleValueSourceName)
|
||||
{
|
||||
console.log("DynamicSelect - you must provide either a fieldName (and a tableName or processName) or a possibleValueSourceName");
|
||||
}
|
||||
if(fieldName && !possibleValueSourceName)
|
||||
{
|
||||
if(!tableName || !processName)
|
||||
{
|
||||
console.log("DynamicSelect - if you provide a fieldName and not a possibleValueSourceName, then you must also provide a tableName or processName");
|
||||
}
|
||||
}
|
||||
if(possibleValueSourceName)
|
||||
{
|
||||
if(tableName || processName)
|
||||
{
|
||||
console.log("DynamicSelect - if you provide a possibleValueSourceName, you should not also provide a tableName or processName");
|
||||
}
|
||||
}
|
||||
|
||||
}, [tableName, processName, fieldName, possibleValueSourceName]);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// default value - needs to be an array (from initialValues (array) prop) for multiple mode - //
|
||||
@ -133,7 +194,7 @@ function DynamicSelect({tableName, processName, fieldName, overrideId, fieldLabe
|
||||
(async () =>
|
||||
{
|
||||
// console.log(`doing a search with ${searchTerm}`);
|
||||
const results: QPossibleValue[] = await qController.possibleValues(tableName, processName, fieldName, searchTerm ?? "", null, otherValues);
|
||||
const results: QPossibleValue[] = await qController.possibleValues(tableName, processName, possibleValueSourceName ?? fieldName, searchTerm ?? "", null, otherValues);
|
||||
|
||||
if(tableMetaData == null && tableName)
|
||||
{
|
||||
@ -166,7 +227,7 @@ function DynamicSelect({tableName, processName, fieldName, overrideId, fieldLabe
|
||||
setLoading(true);
|
||||
setOptions([]);
|
||||
console.log("Refreshing possible values...");
|
||||
const results: QPossibleValue[] = await qController.possibleValues(tableName, processName, fieldName, searchTerm ?? "", null, otherValues);
|
||||
const results: QPossibleValue[] = await qController.possibleValues(tableName, processName, possibleValueSourceName ?? fieldName, searchTerm ?? "", null, otherValues);
|
||||
setLoading(false);
|
||||
setOptions([ ...results ]);
|
||||
setOtherValuesWhenResultsWereLoaded(JSON.stringify(Object.fromEntries(otherValues)));
|
||||
@ -206,7 +267,7 @@ function DynamicSelect({tableName, processName, fieldName, overrideId, fieldLabe
|
||||
onChange(value ? new QPossibleValue(value) : null);
|
||||
}
|
||||
}
|
||||
else if(setFieldValueRef)
|
||||
else if(setFieldValueRef && fieldName)
|
||||
{
|
||||
setFieldValueRef(fieldName, value ? value.id : null);
|
||||
}
|
||||
@ -282,28 +343,13 @@ function DynamicSelect({tableName, processName, fieldName, overrideId, fieldLabe
|
||||
let autocompleteSX = {};
|
||||
if (variant == "outlined")
|
||||
{
|
||||
autocompleteSX = {
|
||||
"& .MuiOutlinedInput-root": {
|
||||
borderRadius: "0.75rem",
|
||||
},
|
||||
"& .MuiInputBase-root": {
|
||||
padding: "0.5rem",
|
||||
background: isDisabled ? "#f0f2f5!important" : "initial",
|
||||
},
|
||||
"& .MuiOutlinedInput-root .MuiAutocomplete-input": {
|
||||
padding: "0",
|
||||
fontSize: "1rem"
|
||||
},
|
||||
"& .Mui-disabled .MuiOutlinedInput-notchedOutline": {
|
||||
borderColor: inputBorderColor
|
||||
}
|
||||
}
|
||||
autocompleteSX = getAutocompleteOutlinedStyle(isDisabled);
|
||||
}
|
||||
|
||||
const autocomplete = (
|
||||
<Box>
|
||||
<Autocomplete
|
||||
id={overrideId ?? fieldName}
|
||||
id={overrideId ?? fieldName ?? possibleValueSourceName}
|
||||
sx={autocompleteSX}
|
||||
open={open}
|
||||
fullWidth
|
||||
@ -383,7 +429,7 @@ function DynamicSelect({tableName, processName, fieldName, overrideId, fieldLabe
|
||||
inForm &&
|
||||
<Box mt={0.75}>
|
||||
<MDTypography component="div" variant="caption" color="error" fontWeight="regular">
|
||||
{!isDisabled && <div className="fieldErrorMessage"><ErrorMessage name={fieldName} render={msg => <span data-field-error="true">{msg}</span>} /></div>}
|
||||
{!isDisabled && <div className="fieldErrorMessage"><ErrorMessage name={fieldName ?? possibleValueSourceName} render={msg => <span data-field-error="true">{msg}</span>} /></div>}
|
||||
</MDTypography>
|
||||
</Box>
|
||||
}
|
||||
|
@ -43,7 +43,11 @@ import DynamicFormUtils from "qqq/components/forms/DynamicFormUtils";
|
||||
import MDTypography from "qqq/components/legacy/MDTypography";
|
||||
import HelpContent from "qqq/components/misc/HelpContent";
|
||||
import QRecordSidebar from "qqq/components/misc/RecordSidebar";
|
||||
import DynamicFormWidget from "qqq/components/widgets/misc/DynamicFormWidget";
|
||||
import FilterAndColumnsSetupWidget from "qqq/components/widgets/misc/FilterAndColumnsSetupWidget";
|
||||
import PivotTableSetupWidget from "qqq/components/widgets/misc/PivotTableSetupWidget";
|
||||
import RecordGridWidget, {ChildRecordListData} from "qqq/components/widgets/misc/RecordGridWidget";
|
||||
import {FieldRule, FieldRuleAction, FieldRuleTrigger} from "qqq/models/fields/FieldRules";
|
||||
import HtmlUtils from "qqq/utils/HtmlUtils";
|
||||
import Client from "qqq/utils/qqq/Client";
|
||||
import TableUtils from "qqq/utils/qqq/TableUtils";
|
||||
@ -63,7 +67,7 @@ interface Props
|
||||
disabledFields: { [key: string]: boolean } | string[];
|
||||
isCopy?: boolean;
|
||||
onSubmitCallback?: (values: any) => void;
|
||||
overrideHeading?: string
|
||||
overrideHeading?: string;
|
||||
}
|
||||
|
||||
EntityForm.defaultProps = {
|
||||
@ -77,6 +81,15 @@ EntityForm.defaultProps = {
|
||||
onSubmitCallback: null,
|
||||
};
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// define a function that we can make referenes to, which we'll overwrite //
|
||||
// with formik's setFieldValue function, once we're inside formik. //
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
let formikSetFieldValueFunction = (field: string, value: any, shouldValidate?: boolean): void =>
|
||||
{
|
||||
};
|
||||
|
||||
function EntityForm(props: Props): JSX.Element
|
||||
{
|
||||
const qController = Client.getInstance();
|
||||
@ -97,17 +110,22 @@ function EntityForm(props: Props): JSX.Element
|
||||
|
||||
const [asyncLoadInited, setAsyncLoadInited] = useState(false);
|
||||
const [tableMetaData, setTableMetaData] = useState(null as QTableMetaData);
|
||||
const [fieldRules, setFieldRules] = useState([] as FieldRule[]);
|
||||
const [metaData, setMetaData] = useState(null as QInstance);
|
||||
const [record, setRecord] = useState(null as QRecord);
|
||||
const [tableSections, setTableSections] = useState(null as QTableSection[]);
|
||||
const [renderedWidgetSections, setRenderedWidgetSections] = useState({} as {[name: string]: JSX.Element});
|
||||
const [childListWidgetData, setChildListWidgetData] = useState({} as {[name: string]: ChildRecordListData});
|
||||
const [renderedWidgetSections, setRenderedWidgetSections] = useState({} as { [name: string]: JSX.Element });
|
||||
const [childListWidgetData, setChildListWidgetData] = useState({} as { [name: string]: ChildRecordListData });
|
||||
const [, forceUpdate] = useReducer((x) => x + 1, 0);
|
||||
|
||||
const [showEditChildForm, setShowEditChildForm] = useState(null as any);
|
||||
const [modalDataChangedCounter, setModalDataChangedCount] = useState(0);
|
||||
|
||||
const [notAllowedError, setNotAllowedError] = useState(null as string);
|
||||
|
||||
const [formValuesJSON, setFormValuesJSON] = useState("");
|
||||
const [formValues, setFormValues] = useState({} as { [name: string]: any });
|
||||
|
||||
const {pageHeader, setPageHeader} = useContext(QContext);
|
||||
|
||||
const navigate = useNavigate();
|
||||
@ -128,23 +146,28 @@ function EntityForm(props: Props): JSX.Element
|
||||
{
|
||||
try
|
||||
{
|
||||
const parts = hashParts[i].split("=")
|
||||
if (parts.length > 1 && parts[0] == "defaultValues")
|
||||
const parts = hashParts[i].split("=");
|
||||
if (parts.length > 1)
|
||||
{
|
||||
defaultValues = JSON.parse(decodeURIComponent(parts[1])) as { [key: string]: any };
|
||||
}
|
||||
const name = parts[0].replace(/^#/, "");
|
||||
const value = parts[1];
|
||||
if (name == "defaultValues")
|
||||
{
|
||||
defaultValues = JSON.parse(decodeURIComponent(value)) as { [key: string]: any };
|
||||
}
|
||||
|
||||
if (parts.length > 1 && parts[0] == "disabledFields")
|
||||
{
|
||||
disabledFields = JSON.parse(decodeURIComponent(parts[1])) as { [key: string]: any };
|
||||
if (name == "disabledFields")
|
||||
{
|
||||
disabledFields = JSON.parse(decodeURIComponent(value)) as { [key: string]: any };
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (e)
|
||||
{}
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@ -153,7 +176,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
let defaultValues = widgetData.defaultValuesForNewChildRecords;
|
||||
|
||||
let disabledFields = widgetData.disabledFieldsForNewChildRecords;
|
||||
if(!disabledFields)
|
||||
if (!disabledFields)
|
||||
{
|
||||
disabledFields = widgetData.defaultValuesForNewChildRecords;
|
||||
}
|
||||
@ -170,7 +193,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
let defaultValues = widgetData.queryOutput.records[rowIndex].values;
|
||||
|
||||
let disabledFields = widgetData.disabledFieldsForNewChildRecords;
|
||||
if(!disabledFields)
|
||||
if (!disabledFields)
|
||||
{
|
||||
disabledFields = widgetData.defaultValuesForNewChildRecords;
|
||||
}
|
||||
@ -234,16 +257,16 @@ function EntityForm(props: Props): JSX.Element
|
||||
const metaData = await qController.loadMetaData();
|
||||
const widgetMetaData = metaData.widgets.get(widgetName);
|
||||
|
||||
const newChildListWidgetData: {[name: string]: ChildRecordListData} = Object.assign({}, childListWidgetData)
|
||||
if(!newChildListWidgetData[widgetName].queryOutput.records)
|
||||
const newChildListWidgetData: { [name: string]: ChildRecordListData } = Object.assign({}, childListWidgetData);
|
||||
if (!newChildListWidgetData[widgetName].queryOutput.records)
|
||||
{
|
||||
newChildListWidgetData[widgetName].queryOutput.records = [];
|
||||
}
|
||||
|
||||
switch(action)
|
||||
switch (action)
|
||||
{
|
||||
case "insert":
|
||||
newChildListWidgetData[widgetName].queryOutput.records.push({values: values})
|
||||
newChildListWidgetData[widgetName].queryOutput.records.push({values: values});
|
||||
break;
|
||||
case "edit":
|
||||
newChildListWidgetData[widgetName].queryOutput.records[rowIndex] = {values: values};
|
||||
@ -255,15 +278,32 @@ function EntityForm(props: Props): JSX.Element
|
||||
newChildListWidgetData[widgetName].totalRows = newChildListWidgetData[widgetName].queryOutput.records.length;
|
||||
setChildListWidgetData(newChildListWidgetData);
|
||||
|
||||
const newRenderedWidgetSections = Object.assign({}, renderedWidgetSections)
|
||||
const newRenderedWidgetSections = Object.assign({}, renderedWidgetSections);
|
||||
newRenderedWidgetSections[widgetName] = getWidgetSection(widgetMetaData, newChildListWidgetData[widgetName]);
|
||||
setRenderedWidgetSections(newRenderedWidgetSections);
|
||||
forceUpdate();
|
||||
|
||||
setModalDataChangedCount(modalDataChangedCounter + 1);
|
||||
|
||||
setShowEditChildForm(null);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Watch the record values - if they change, re-render widgets
|
||||
*******************************************************************************/
|
||||
useEffect(() =>
|
||||
{
|
||||
const newRenderedWidgetSections: { [name: string]: JSX.Element } = {};
|
||||
for (let widgetName in renderedWidgetSections)
|
||||
{
|
||||
const widgetMetaData = metaData.widgets.get(widgetName);
|
||||
newRenderedWidgetSections[widgetName] = getWidgetSection(widgetMetaData, childListWidgetData[widgetName]);
|
||||
}
|
||||
setRenderedWidgetSections(newRenderedWidgetSections);
|
||||
}, [formValuesJSON]);
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** render a section (full of fields) as a form
|
||||
*******************************************************************************/
|
||||
@ -290,14 +330,14 @@ function EntityForm(props: Props): JSX.Element
|
||||
|
||||
if (!Object.keys(formFields).length)
|
||||
{
|
||||
return <div>Error: No form fields in section {section.name}</div>;
|
||||
return <div>Error: No form fields in section {section.name}</div>;
|
||||
}
|
||||
|
||||
const helpRoles = [props.id ? "EDIT_SCREEN" : "INSERT_SCREEN", "WRITE_SCREENS", "ALL_SCREENS"]
|
||||
const helpRoles = [props.id ? "EDIT_SCREEN" : "INSERT_SCREEN", "WRITE_SCREENS", "ALL_SCREENS"];
|
||||
|
||||
if(omitWrapper)
|
||||
if (omitWrapper)
|
||||
{
|
||||
return <QDynamicForm formData={formData} record={record} helpRoles={helpRoles} helpContentKeyPrefix={`table:${tableName};`} />
|
||||
return <QDynamicForm formData={formData} record={record} helpRoles={helpRoles} helpContentKeyPrefix={`table:${tableName};`} />;
|
||||
}
|
||||
|
||||
return <Card id={section.name} sx={{overflow: "visible", scrollMarginTop: "100px"}} elevation={cardElevation}>
|
||||
@ -310,7 +350,20 @@ function EntityForm(props: Props): JSX.Element
|
||||
<QDynamicForm formData={formData} record={record} helpRoles={helpRoles} helpContentKeyPrefix={`table:${tableName};`} />
|
||||
</Box>
|
||||
</Box>
|
||||
</Card>
|
||||
</Card>;
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** if we have a widget that wants to set form-field values, they can take this
|
||||
** function in as a callback, and then call it with their values.
|
||||
*******************************************************************************/
|
||||
function setFormFieldValuesFromWidget(values: { [name: string]: any })
|
||||
{
|
||||
for (let key in values)
|
||||
{
|
||||
formikSetFieldValueFunction(key, values[key]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -319,20 +372,69 @@ function EntityForm(props: Props): JSX.Element
|
||||
*******************************************************************************/
|
||||
function getWidgetSection(widgetMetaData: QWidgetMetaData, widgetData: any): JSX.Element
|
||||
{
|
||||
widgetData.viewAllLink = null;
|
||||
widgetMetaData.showExportButton = false;
|
||||
if (widgetMetaData.type == "childRecordList")
|
||||
{
|
||||
widgetData.viewAllLink = null;
|
||||
widgetMetaData.showExportButton = false;
|
||||
|
||||
return <RecordGridWidget
|
||||
key={new Date().getTime()} // added so that editing values actually re-renders...
|
||||
widgetMetaData={widgetMetaData}
|
||||
data={widgetData}
|
||||
disableRowClick
|
||||
allowRecordEdit
|
||||
allowRecordDelete
|
||||
addNewRecordCallback={() => openAddChildRecord(widgetMetaData.name, widgetData)}
|
||||
editRecordCallback={(rowIndex) => openEditChildRecord(widgetMetaData.name, widgetData, rowIndex)}
|
||||
deleteRecordCallback={(rowIndex) => deleteChildRecord(widgetMetaData.name, widgetData, rowIndex)}
|
||||
/>
|
||||
return <RecordGridWidget
|
||||
key={`${formValues["tableName"]}-${modalDataChangedCounter}`}
|
||||
widgetMetaData={widgetMetaData}
|
||||
data={widgetData}
|
||||
disableRowClick
|
||||
allowRecordEdit
|
||||
allowRecordDelete
|
||||
addNewRecordCallback={() => openAddChildRecord(widgetMetaData.name, widgetData)}
|
||||
editRecordCallback={(rowIndex) => openEditChildRecord(widgetMetaData.name, widgetData, rowIndex)}
|
||||
deleteRecordCallback={(rowIndex) => deleteChildRecord(widgetMetaData.name, widgetData, rowIndex)}
|
||||
/>;
|
||||
}
|
||||
|
||||
if (widgetMetaData.type == "filterAndColumnsSetup")
|
||||
{
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// if the widget metadata specifies a table name, set form values to that so widget knows which to use //
|
||||
// (for the case when it is not being specified by a separate field in the record) //
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
if (widgetMetaData?.defaultValues?.has("tableName"))
|
||||
{
|
||||
formValues["tableName"] = widgetMetaData?.defaultValues.get("tableName");
|
||||
}
|
||||
|
||||
return <FilterAndColumnsSetupWidget
|
||||
key={formValues["tableName"]} // todo, is this good? it was added so that editing values actually re-renders...
|
||||
isEditable={true}
|
||||
widgetMetaData={widgetMetaData}
|
||||
recordValues={formValues}
|
||||
onSaveCallback={setFormFieldValuesFromWidget}
|
||||
/>;
|
||||
}
|
||||
|
||||
if (widgetMetaData.type == "pivotTableSetup")
|
||||
{
|
||||
return <PivotTableSetupWidget
|
||||
key={formValues["tableName"]} // todo, is this good? it was added so that editing values actually re-renders...
|
||||
isEditable={true}
|
||||
widgetMetaData={widgetMetaData}
|
||||
recordValues={formValues}
|
||||
onSaveCallback={setFormFieldValuesFromWidget}
|
||||
/>;
|
||||
}
|
||||
|
||||
if (widgetMetaData.type == "dynamicForm")
|
||||
{
|
||||
return <DynamicFormWidget
|
||||
key={formValues["savedReportId"]} // todo - pull this from the metaData (could do so above too...)
|
||||
isEditable={true}
|
||||
widgetMetaData={widgetMetaData}
|
||||
widgetData={widgetData}
|
||||
recordValues={formValues}
|
||||
record={record}
|
||||
onSaveCallback={setFormFieldValuesFromWidget}
|
||||
/>;
|
||||
}
|
||||
|
||||
return (<Box>Unsupported widget type: {widgetMetaData.type}</Box>);
|
||||
}
|
||||
|
||||
|
||||
@ -341,17 +443,43 @@ function EntityForm(props: Props): JSX.Element
|
||||
*******************************************************************************/
|
||||
function renderSection(section: QTableSection, values: FormikValues | Value, touched: FormikTouched<FormikValues> | Value, formFields: Map<string, any>, errors: FormikErrors<FormikValues> | Value)
|
||||
{
|
||||
if(section.fieldNames && section.fieldNames.length > 0)
|
||||
if (section.fieldNames && section.fieldNames.length > 0)
|
||||
{
|
||||
return getFormSection(section, values, touched, formFields.get(section.name), errors);
|
||||
}
|
||||
else
|
||||
{
|
||||
return renderedWidgetSections[section.widgetName] ?? <Box>Loading {section.label}...</Box>
|
||||
return renderedWidgetSections[section.widgetName] ?? <Box>Loading {section.label}...</Box>;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function setupFieldRules(tableMetaData: QTableMetaData)
|
||||
{
|
||||
const mdbMetaData = tableMetaData?.supplementalTableMetaData?.get("materialDashboard");
|
||||
if (!mdbMetaData)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (mdbMetaData.fieldRules)
|
||||
{
|
||||
const newFieldRules: FieldRule[] = [];
|
||||
for (let i = 0; i < mdbMetaData.fieldRules.length; i++)
|
||||
{
|
||||
newFieldRules.push(mdbMetaData.fieldRules[i]);
|
||||
}
|
||||
setFieldRules(newFieldRules);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//////////////////
|
||||
// initial load //
|
||||
//////////////////
|
||||
if (!asyncLoadInited)
|
||||
{
|
||||
setAsyncLoadInited(true);
|
||||
@ -361,6 +489,8 @@ function EntityForm(props: Props): JSX.Element
|
||||
setTableMetaData(tableMetaData);
|
||||
recordAnalytics({location: window.location, title: (props.isCopy ? "Copy" : props.id ? "Edit" : "New") + ": " + tableMetaData.label});
|
||||
|
||||
setupFieldRules(tableMetaData);
|
||||
|
||||
const metaData = await qController.loadMetaData();
|
||||
setMetaData(metaData);
|
||||
|
||||
@ -369,7 +499,21 @@ function EntityForm(props: Props): JSX.Element
|
||||
/////////////////////////////////////////////////
|
||||
const tableSections = TableUtils.getSectionsForRecordSidebar(tableMetaData, [...tableMetaData.fields.keys()], (section: QTableSection) =>
|
||||
{
|
||||
return section.widgetName && metaData.widgets.get(section.widgetName)?.type == "childRecordList" && metaData.widgets.get(section.widgetName)?.defaultValues?.has("manageAssociationName")
|
||||
const widget = metaData?.widgets.get(section.widgetName);
|
||||
if (widget)
|
||||
{
|
||||
if (widget.type == "childRecordList" && widget.defaultValues?.has("manageAssociationName"))
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
|
||||
if (widget.type == "filterAndColumnsSetup" || widget.type == "pivotTableSetup" || widget.type == "dynamicForm")
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
}
|
||||
|
||||
return (false);
|
||||
});
|
||||
setTableSections(tableSections);
|
||||
|
||||
@ -412,7 +556,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// these checks are only for updating records, if copying, it is actually an insert, which is checked after this block //
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
if(! props.isCopy)
|
||||
if (!props.isCopy)
|
||||
{
|
||||
if (!tableMetaData.capabilities.has(Capability.TABLE_UPDATE))
|
||||
{
|
||||
@ -468,7 +612,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
///////////////////////////////////////////////////
|
||||
// if an override heading was passed in, use it. //
|
||||
///////////////////////////////////////////////////
|
||||
if(props.overrideHeading)
|
||||
if (props.overrideHeading)
|
||||
{
|
||||
setFormTitle(props.overrideHeading);
|
||||
if (!props.isModal)
|
||||
@ -533,8 +677,8 @@ function EntityForm(props: Props): JSX.Element
|
||||
let t1sectionName;
|
||||
let t1section;
|
||||
const nonT1Sections: QTableSection[] = [];
|
||||
const newRenderedWidgetSections: {[name: string]: JSX.Element} = {};
|
||||
const newChildListWidgetData: {[name: string]: ChildRecordListData} = {};
|
||||
const newRenderedWidgetSections: { [name: string]: JSX.Element } = {};
|
||||
const newChildListWidgetData: { [name: string]: ChildRecordListData } = {};
|
||||
|
||||
for (let i = 0; i < tableSections.length; i++)
|
||||
{
|
||||
@ -547,13 +691,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
}
|
||||
|
||||
const hasFields = section.fieldNames && section.fieldNames.length > 0;
|
||||
const hasChildRecordListWidget = section.widgetName && metaData.widgets.get(section.widgetName)?.type == "childRecordList"
|
||||
if(!hasFields && !hasChildRecordListWidget)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if(hasFields)
|
||||
if (hasFields)
|
||||
{
|
||||
for (let j = 0; j < section.fieldNames.length; j++)
|
||||
{
|
||||
@ -592,11 +730,13 @@ function EntityForm(props: Props): JSX.Element
|
||||
}
|
||||
else
|
||||
{
|
||||
const widgetMetaData = metaData.widgets.get(section.widgetName);
|
||||
const widgetData = await qController.widget(widgetMetaData.name, props.id ? `${tableMetaData.primaryKeyField}=${props.id}` : "");
|
||||
const widgetMetaData = metaData?.widgets.get(section.widgetName);
|
||||
const widgetData = await qController.widget(widgetMetaData.name, makeQueryStringWithIdAndObject(tableMetaData, defaultValues));
|
||||
|
||||
newRenderedWidgetSections[section.widgetName] = getWidgetSection(widgetMetaData, widgetData);
|
||||
newChildListWidgetData[section.widgetName] = widgetData;
|
||||
}
|
||||
|
||||
//////////////////////////////////////
|
||||
// capture the tier1 section's name //
|
||||
//////////////////////////////////////
|
||||
@ -629,10 +769,10 @@ function EntityForm(props: Props): JSX.Element
|
||||
//////////////////////////////////////////////////////////////////
|
||||
useEffect(() =>
|
||||
{
|
||||
if(childListWidgetData)
|
||||
if (childListWidgetData)
|
||||
{
|
||||
const newRenderedWidgetSections: {[name: string]: JSX.Element} = {};
|
||||
for(let name in childListWidgetData)
|
||||
const newRenderedWidgetSections: { [name: string]: JSX.Element } = {};
|
||||
for (let name in childListWidgetData)
|
||||
{
|
||||
const widgetMetaData = metaData.widgets.get(name);
|
||||
newRenderedWidgetSections[name] = getWidgetSection(widgetMetaData, childListWidgetData[name]);
|
||||
@ -677,7 +817,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// if there's a callback (e.g., for a modal nested on another create/edit screen), then just pass our data back there anre return. //
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
if(props.onSubmitCallback)
|
||||
if (props.onSubmitCallback)
|
||||
{
|
||||
props.onSubmitCallback(values);
|
||||
return;
|
||||
@ -690,7 +830,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
const valuesToPost = JSON.parse(JSON.stringify(values));
|
||||
|
||||
for(let fieldName of tableMetaData.fields.keys())
|
||||
for (let fieldName of tableMetaData.fields.keys())
|
||||
{
|
||||
const fieldMetaData = tableMetaData.fields.get(fieldName);
|
||||
|
||||
@ -702,9 +842,9 @@ function EntityForm(props: Props): JSX.Element
|
||||
// changing from, say, 12:15:30 to just 12:15:00... this seems to get around that, for cases when the //
|
||||
// user didn't change the value in the field (but if the user did change the value, then we will submit it) //
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
if(fieldMetaData.type === QFieldType.DATE_TIME && valuesToPost[fieldName])
|
||||
if (fieldMetaData.type === QFieldType.DATE_TIME && valuesToPost[fieldName])
|
||||
{
|
||||
console.log(`DateTime ${fieldName}: Initial value: [${initialValues[fieldName]}] -> [${valuesToPost[fieldName]}]`)
|
||||
console.log(`DateTime ${fieldName}: Initial value: [${initialValues[fieldName]}] -> [${valuesToPost[fieldName]}]`);
|
||||
if (initialValues[fieldName] == valuesToPost[fieldName])
|
||||
{
|
||||
console.log(" - Is the same, so, deleting from the post");
|
||||
@ -723,12 +863,12 @@ function EntityForm(props: Props): JSX.Element
|
||||
// 3) they are a String, which is their URL path to download them... in that case, don't submit them to //
|
||||
// the backend at all, so they'll stay what they were. do that by deleting them from the values object here. //
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
if(fieldMetaData.type === QFieldType.BLOB)
|
||||
if (fieldMetaData.type === QFieldType.BLOB)
|
||||
{
|
||||
if(typeof valuesToPost[fieldName] === "string")
|
||||
if (typeof valuesToPost[fieldName] === "string")
|
||||
{
|
||||
console.log(`${fieldName} value was a string, so, we're deleting it from the values array, to not submit it to the backend, to not change it.`);
|
||||
delete(valuesToPost[fieldName]);
|
||||
delete (valuesToPost[fieldName]);
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -737,23 +877,23 @@ function EntityForm(props: Props): JSX.Element
|
||||
}
|
||||
}
|
||||
|
||||
const associationsToPost: any = {}
|
||||
const associationsToPost: any = {};
|
||||
let haveAssociationsToPost = false;
|
||||
for (let name of Object.keys(childListWidgetData))
|
||||
{
|
||||
const manageAssociationName = metaData.widgets.get(name)?.defaultValues?.get("manageAssociationName")
|
||||
if(!manageAssociationName)
|
||||
const manageAssociationName = metaData.widgets.get(name)?.defaultValues?.get("manageAssociationName");
|
||||
if (!manageAssociationName)
|
||||
{
|
||||
console.log(`Cannot send association data to backend - missing a manageAssociationName defaultValue in widget meta data for widget name ${name}`);
|
||||
}
|
||||
associationsToPost[manageAssociationName] = [];
|
||||
haveAssociationsToPost = true;
|
||||
for(let i=0; i<childListWidgetData[name].queryOutput?.records?.length; i++)
|
||||
for (let i = 0; i < childListWidgetData[name].queryOutput?.records?.length; i++)
|
||||
{
|
||||
associationsToPost[manageAssociationName].push(childListWidgetData[name].queryOutput.records[i].values);
|
||||
}
|
||||
}
|
||||
if(haveAssociationsToPost)
|
||||
if (haveAssociationsToPost)
|
||||
{
|
||||
valuesToPost["associations"] = JSON.stringify(associationsToPost);
|
||||
}
|
||||
@ -776,7 +916,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
else
|
||||
{
|
||||
let warningMessage = null;
|
||||
if(record.warnings && record.warnings.length && record.warnings.length > 0)
|
||||
if (record.warnings && record.warnings.length && record.warnings.length > 0)
|
||||
{
|
||||
warningMessage = record.warnings[0];
|
||||
}
|
||||
@ -790,7 +930,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
console.log("Caught:");
|
||||
console.log(error);
|
||||
|
||||
if(error.message.toLowerCase().startsWith("warning"))
|
||||
if (error.message.toLowerCase().startsWith("warning"))
|
||||
{
|
||||
const path = location.pathname.replace(/\/edit$/, "");
|
||||
navigate(path, {state: {updateSuccess: true, warning: error.message}});
|
||||
@ -798,7 +938,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
else
|
||||
{
|
||||
setAlertContent(error.message);
|
||||
HtmlUtils.autoScroll(0);
|
||||
scrollToTopToShowAlert();
|
||||
}
|
||||
});
|
||||
}
|
||||
@ -821,7 +961,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
else
|
||||
{
|
||||
let warningMessage = null;
|
||||
if(record.warnings && record.warnings.length && record.warnings.length > 0)
|
||||
if (record.warnings && record.warnings.length && record.warnings.length > 0)
|
||||
{
|
||||
warningMessage = record.warnings[0];
|
||||
}
|
||||
@ -834,7 +974,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
})
|
||||
.catch((error) =>
|
||||
{
|
||||
if(error.message.toLowerCase().startsWith("warning"))
|
||||
if (error.message.toLowerCase().startsWith("warning"))
|
||||
{
|
||||
const path = props.isCopy ?
|
||||
location.pathname.replace(new RegExp(`/${props.id}/copy$`), "/" + record.values.get(tableMetaData.primaryKeyField))
|
||||
@ -844,28 +984,114 @@ function EntityForm(props: Props): JSX.Element
|
||||
else
|
||||
{
|
||||
setAlertContent(error.message);
|
||||
HtmlUtils.autoScroll(0);
|
||||
scrollToTopToShowAlert();
|
||||
}
|
||||
});
|
||||
}
|
||||
})();
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function scrollToTopToShowAlert()
|
||||
{
|
||||
if (props.isModal)
|
||||
{
|
||||
document.getElementById("modalTopReference")?.scrollIntoView();
|
||||
}
|
||||
else
|
||||
{
|
||||
HtmlUtils.autoScroll(0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function makeQueryStringWithIdAndObject(tableMetaData: QTableMetaData, object: { [key: string]: any })
|
||||
{
|
||||
const queryParamsArray: string[] = [];
|
||||
if (props.id)
|
||||
{
|
||||
queryParamsArray.push(`${tableMetaData.primaryKeyField}=${encodeURIComponent(props.id)}`);
|
||||
}
|
||||
|
||||
if (object)
|
||||
{
|
||||
for (let key in object)
|
||||
{
|
||||
queryParamsArray.push(`${key}=${encodeURIComponent(object[key])}`);
|
||||
}
|
||||
}
|
||||
|
||||
return (queryParamsArray.join("&"));
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
async function reloadWidget(widgetName: string, additionalQueryParamsForWidget: { [key: string]: any })
|
||||
{
|
||||
const widgetData = await qController.widget(widgetName, makeQueryStringWithIdAndObject(tableMetaData, additionalQueryParamsForWidget));
|
||||
const widgetMetaData = metaData.widgets.get(widgetName);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// todo - rename this - it holds all widget dta, not just child-lists. also, the type is wrong... //
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
const newChildListWidgetData: { [name: string]: ChildRecordListData } = Object.assign({}, childListWidgetData);
|
||||
newChildListWidgetData[widgetName] = widgetData;
|
||||
setChildListWidgetData(newChildListWidgetData);
|
||||
|
||||
const newRenderedWidgetSections = Object.assign({}, renderedWidgetSections);
|
||||
newRenderedWidgetSections[widgetName] = getWidgetSection(widgetMetaData, widgetData);
|
||||
setRenderedWidgetSections(newRenderedWidgetSections);
|
||||
forceUpdate();
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** process a form-field having a changed value (e.g., apply field rules).
|
||||
*******************************************************************************/
|
||||
function handleChangedFieldValue(fieldName: string, oldValue: any, newValue: any, valueChangesToMake: { [fieldName: string]: any })
|
||||
{
|
||||
for (let fieldRule of fieldRules)
|
||||
{
|
||||
if (fieldRule.trigger == FieldRuleTrigger.ON_CHANGE && fieldRule.sourceField == fieldName)
|
||||
{
|
||||
switch (fieldRule.action)
|
||||
{
|
||||
case FieldRuleAction.CLEAR_TARGET_FIELD:
|
||||
console.log(`Clearing value from [${fieldRule.targetField}] due to change in [${fieldName}]`);
|
||||
valueChangesToMake[fieldRule.targetField] = null;
|
||||
break;
|
||||
case FieldRuleAction.RELOAD_WIDGET:
|
||||
const additionalQueryParamsForWidget: { [key: string]: any } = {};
|
||||
additionalQueryParamsForWidget[fieldRule.sourceField] = newValue;
|
||||
reloadWidget(fieldRule.targetWidget, additionalQueryParamsForWidget);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const formId = props.id != null ? `edit-${tableMetaData?.name}-form` : `create-${tableMetaData?.name}-form`;
|
||||
|
||||
let body;
|
||||
|
||||
const getSectionHelp = (section: QTableSection) =>
|
||||
{
|
||||
const helpRoles = [props.id ? "EDIT_SCREEN" : "INSERT_SCREEN", "WRITE_SCREENS", "ALL_SCREENS"]
|
||||
const helpRoles = [props.id ? "EDIT_SCREEN" : "INSERT_SCREEN", "WRITE_SCREENS", "ALL_SCREENS"];
|
||||
const formattedHelpContent = <HelpContent helpContents={section.helpContents} roles={helpRoles} helpContentKey={`table:${tableMetaData.name};section:${section.name}`} />;
|
||||
|
||||
return formattedHelpContent && (
|
||||
<Box px={"1.5rem"} fontSize={"0.875rem"}>
|
||||
{formattedHelpContent}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
if (notAllowedError)
|
||||
{
|
||||
@ -889,7 +1115,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
else
|
||||
{
|
||||
body = (
|
||||
<Box mb={3}>
|
||||
<Box mb={3} className="entityForm">
|
||||
{
|
||||
(alertContent || warningContent) &&
|
||||
<Grid container spacing={3}>
|
||||
@ -926,51 +1152,116 @@ function EntityForm(props: Props): JSX.Element
|
||||
errors,
|
||||
touched,
|
||||
isSubmitting,
|
||||
}) => (
|
||||
<Form id={formId} autoComplete="off">
|
||||
<ScrollToFirstError />
|
||||
setFieldValue,
|
||||
dirty
|
||||
}) =>
|
||||
{
|
||||
/////////////////////////////////////////////////
|
||||
// if we have values from formik, look at them //
|
||||
/////////////////////////////////////////////////
|
||||
if (values)
|
||||
{
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
// use stringified values as cheap/easy way to see if any are changed //
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
const newFormValuesJSON = JSON.stringify(values);
|
||||
if (formValuesJSON != newFormValuesJSON)
|
||||
{
|
||||
const valueChangesToMake: { [fieldName: string]: any } = {};
|
||||
|
||||
<Box pb={3} pt={0}>
|
||||
<Card id={`${t1sectionName}`} sx={{overflow: "visible", pb: 2, scrollMarginTop: "100px"}} elevation={cardElevation}>
|
||||
<Box display="flex" p={3} pb={1}>
|
||||
<Box mr={1.5}>
|
||||
<Avatar sx={{bgcolor: accentColor}}>
|
||||
<Icon>
|
||||
{tableMetaData?.iconName}
|
||||
</Icon>
|
||||
</Avatar>
|
||||
</Box>
|
||||
<Box display="flex" alignItems="center">
|
||||
<MDTypography variant="h5">{formTitle}</MDTypography>
|
||||
</Box>
|
||||
</Box>
|
||||
{t1section && getSectionHelp(t1section)}
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// if the form is dirty (e.g., we're not doing the initial load), //
|
||||
// then process rules for any changed fields //
|
||||
////////////////////////////////////////////////////////////////////
|
||||
if (dirty)
|
||||
{
|
||||
for (let fieldName in values)
|
||||
{
|
||||
t1sectionName && formFields ? (
|
||||
<Box px={3}>
|
||||
<Box pb={"0.25rem"} width="100%">
|
||||
{getFormSection(t1section, values, touched, formFields.get(t1sectionName), errors, true)}
|
||||
</Box>
|
||||
</Box>
|
||||
) : null
|
||||
if (formValues[fieldName] != values[fieldName])
|
||||
{
|
||||
handleChangedFieldValue(fieldName, formValues[fieldName], values[fieldName], valueChangesToMake);
|
||||
}
|
||||
formValues[fieldName] = values[fieldName];
|
||||
}
|
||||
</Card>
|
||||
</Box>
|
||||
{formFields && nonT1Sections.length ? nonT1Sections.map((section: QTableSection) => (
|
||||
<Box key={`edit-card-${section.name}`} pb={3}>
|
||||
{renderSection(section, values, touched, formFields, errors)}
|
||||
}
|
||||
else
|
||||
{
|
||||
/////////////////////////////////////////////////////////////////////////////////////
|
||||
// if the form is clean, make sure the formValues object has all form values in it //
|
||||
/////////////////////////////////////////////////////////////////////////////////////
|
||||
for (let fieldName in values)
|
||||
{
|
||||
formValues[fieldName] = values[fieldName];
|
||||
}
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// if there were any changes to be made from the rule evaluation, //
|
||||
// make those changes in the formValues map, and in formik (setFieldValue) //
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
for (let fieldName in valueChangesToMake)
|
||||
{
|
||||
formValues[fieldName] = valueChangesToMake[fieldName];
|
||||
setFieldValue(fieldName, valueChangesToMake[fieldName], false);
|
||||
}
|
||||
|
||||
setFormValues(formValues);
|
||||
setFormValuesJSON(JSON.stringify(values));
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////
|
||||
// once we're in the formik form, use its setFieldValue function //
|
||||
// over top of the default one we created globally //
|
||||
///////////////////////////////////////////////////////////////////
|
||||
formikSetFieldValueFunction = setFieldValue;
|
||||
|
||||
return (
|
||||
<Form id={formId} autoComplete="off">
|
||||
<ScrollToFirstError />
|
||||
|
||||
<Box pb={3} pt={0}>
|
||||
<Card id={`${t1sectionName}`} sx={{overflow: "visible", pb: 2, scrollMarginTop: "100px"}} elevation={cardElevation}>
|
||||
<Box display="flex" p={3} pb={1}>
|
||||
<Box mr={1.5}>
|
||||
<Avatar sx={{bgcolor: accentColor}}>
|
||||
<Icon>
|
||||
{tableMetaData?.iconName}
|
||||
</Icon>
|
||||
</Avatar>
|
||||
</Box>
|
||||
<Box display="flex" alignItems="center">
|
||||
<MDTypography variant="h5">{formTitle}</MDTypography>
|
||||
</Box>
|
||||
</Box>
|
||||
{t1section && getSectionHelp(t1section)}
|
||||
{
|
||||
t1sectionName && formFields ? (
|
||||
<Box px={3}>
|
||||
<Box pb={"0.25rem"} width="100%">
|
||||
{getFormSection(t1section, values, touched, formFields.get(t1sectionName), errors, true)}
|
||||
</Box>
|
||||
</Box>
|
||||
) : null
|
||||
}
|
||||
</Card>
|
||||
</Box>
|
||||
)) : null}
|
||||
{formFields && nonT1Sections.length ? nonT1Sections.map((section: QTableSection) => (
|
||||
<Box key={`edit-card-${section.name}`} pb={3}>
|
||||
{renderSection(section, values, touched, formFields, errors)}
|
||||
</Box>
|
||||
)) : null}
|
||||
|
||||
<Box component="div" p={3}>
|
||||
<Grid container justifyContent="flex-end" spacing={3}>
|
||||
<QCancelButton onClickHandler={props.isModal ? props.closeModalHandler : handleCancelClicked} disabled={isSubmitting} />
|
||||
<QSaveButton disabled={isSubmitting} />
|
||||
</Grid>
|
||||
</Box>
|
||||
<Box component="div" p={3}>
|
||||
<Grid container justifyContent="flex-end" spacing={3}>
|
||||
<QCancelButton onClickHandler={props.isModal ? props.closeModalHandler : handleCancelClicked} disabled={isSubmitting} />
|
||||
<QSaveButton disabled={isSubmitting} />
|
||||
</Grid>
|
||||
</Box>
|
||||
|
||||
</Form>
|
||||
)}
|
||||
</Form>
|
||||
);
|
||||
}}
|
||||
</Formik>
|
||||
|
||||
{
|
||||
@ -1001,6 +1292,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
return (
|
||||
<Box sx={{position: "absolute", overflowY: "auto", maxHeight: "100%", width: "100%"}}>
|
||||
<Card sx={{my: 5, mx: "auto", p: 6, pb: 0, maxWidth: "1024px"}}>
|
||||
<span id="modalTopReference"></span>
|
||||
{body}
|
||||
</Card>
|
||||
</Box>
|
||||
@ -1014,7 +1306,7 @@ function EntityForm(props: Props): JSX.Element
|
||||
|
||||
function ScrollToFirstError(): JSX.Element
|
||||
{
|
||||
const {submitCount, isValid} = useFormikContext()
|
||||
const {submitCount, isValid} = useFormikContext();
|
||||
|
||||
useEffect(() =>
|
||||
{
|
||||
@ -1044,8 +1336,8 @@ function ScrollToFirstError(): JSX.Element
|
||||
}
|
||||
firstErrorMessage.scrollIntoView({block: "center"});
|
||||
|
||||
}, 100)
|
||||
}, [submitCount, isValid])
|
||||
}, 100);
|
||||
}, [submitCount, isValid]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
@ -94,16 +94,19 @@ function QBreadcrumbs({icon, title, route, light}: Props): JSX.Element
|
||||
{
|
||||
////////////////////////////////////////////////////////
|
||||
// avoid showing "saved view" as a breadcrumb element //
|
||||
// e.g., if at /app/table/savedView/1 (so where i==2) //
|
||||
////////////////////////////////////////////////////////
|
||||
if(routes[i] === "savedView")
|
||||
if(routes[i] === "savedView" && i == 2)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
// avoid showing the table name if it's the element before savedView //
|
||||
// e.g., when at /app/table/savedView/1 (so where i==1) //
|
||||
// we want to just be showing "App" //
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
if(i < routes.length - 1 && routes[i+1] == "savedView")
|
||||
if(i < routes.length - 1 && routes[i+1] == "savedView" && i == 1)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
@ -23,9 +23,11 @@
|
||||
import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData";
|
||||
import {QInstance} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QInstance";
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import {Box} from "@mui/material";
|
||||
import Autocomplete, {AutocompleteRenderOptionState} from "@mui/material/Autocomplete";
|
||||
import Icon from "@mui/material/Icon";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import React, {ReactNode} from "react";
|
||||
import React, {ReactNode, useState} from "react";
|
||||
|
||||
interface FieldAutoCompleteProps
|
||||
{
|
||||
@ -33,10 +35,17 @@ interface FieldAutoCompleteProps
|
||||
metaData: QInstance;
|
||||
tableMetaData: QTableMetaData;
|
||||
handleFieldChange: (event: any, newValue: any, reason: string) => void;
|
||||
defaultValue?: {field: QFieldMetaData, table: QTableMetaData, fieldName: string};
|
||||
defaultValue?: { field: QFieldMetaData, table: QTableMetaData, fieldName: string };
|
||||
autoFocus?: boolean;
|
||||
forceOpen?: boolean;
|
||||
hiddenFieldNames?: string[];
|
||||
availableFieldNames?: string[];
|
||||
variant?: "standard" | "filled" | "outlined";
|
||||
label?: string;
|
||||
textFieldSX?: any;
|
||||
autocompleteSlotProps?: any;
|
||||
hasError?: boolean;
|
||||
noOptionsText?: string;
|
||||
}
|
||||
|
||||
FieldAutoComplete.defaultProps =
|
||||
@ -44,17 +53,29 @@ FieldAutoComplete.defaultProps =
|
||||
defaultValue: null,
|
||||
autoFocus: false,
|
||||
forceOpen: null,
|
||||
hiddenFieldNames: []
|
||||
hiddenFieldNames: [],
|
||||
availableFieldNames: [],
|
||||
variant: "standard",
|
||||
label: "Field",
|
||||
textFieldSX: null,
|
||||
autocompleteSlotProps: null,
|
||||
hasError: false,
|
||||
noOptionsText: "No options",
|
||||
};
|
||||
|
||||
function makeFieldOptionsForTable(tableMetaData: QTableMetaData, fieldOptions: any[], isJoinTable: boolean, hiddenFieldNames: string[])
|
||||
function makeFieldOptionsForTable(tableMetaData: QTableMetaData, fieldOptions: any[], isJoinTable: boolean, hiddenFieldNames: string[], availableFieldNames: string[], selectedFieldName: string)
|
||||
{
|
||||
const sortedFields = [...tableMetaData.fields.values()].sort((a, b) => a.label.localeCompare(b.label));
|
||||
for (let i = 0; i < sortedFields.length; i++)
|
||||
{
|
||||
const fieldName = isJoinTable ? `${tableMetaData.name}.${sortedFields[i].name}` : sortedFields[i].name;
|
||||
|
||||
if(hiddenFieldNames && hiddenFieldNames.indexOf(fieldName) > -1)
|
||||
if (hiddenFieldNames && hiddenFieldNames.indexOf(fieldName) > -1 && fieldName != selectedFieldName)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (availableFieldNames?.length && availableFieldNames.indexOf(fieldName) == -1)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@ -63,10 +84,16 @@ function makeFieldOptionsForTable(tableMetaData: QTableMetaData, fieldOptions: a
|
||||
}
|
||||
}
|
||||
|
||||
export default function FieldAutoComplete({id, metaData, tableMetaData, handleFieldChange, defaultValue, autoFocus, forceOpen, hiddenFieldNames}: FieldAutoCompleteProps): JSX.Element
|
||||
|
||||
/*******************************************************************************
|
||||
** Component for rendering a list of field names from a table as an auto-complete.
|
||||
*******************************************************************************/
|
||||
export default function FieldAutoComplete({id, metaData, tableMetaData, handleFieldChange, defaultValue, autoFocus, forceOpen, hiddenFieldNames, availableFieldNames, variant, label, textFieldSX, autocompleteSlotProps, hasError, noOptionsText}: FieldAutoCompleteProps): JSX.Element
|
||||
{
|
||||
const [selectedFieldName, setSelectedFieldName] = useState(defaultValue ? defaultValue.fieldName : null);
|
||||
|
||||
const fieldOptions: any[] = [];
|
||||
makeFieldOptionsForTable(tableMetaData, fieldOptions, false, hiddenFieldNames);
|
||||
makeFieldOptionsForTable(tableMetaData, fieldOptions, false, hiddenFieldNames, availableFieldNames, selectedFieldName);
|
||||
let fieldsGroupBy = null;
|
||||
|
||||
if (tableMetaData.exposedJoins && tableMetaData.exposedJoins.length > 0)
|
||||
@ -77,7 +104,7 @@ export default function FieldAutoComplete({id, metaData, tableMetaData, handleFi
|
||||
if (metaData.tables.has(exposedJoin.joinTable.name))
|
||||
{
|
||||
fieldsGroupBy = (option: any) => `${option.table.label} fields`;
|
||||
makeFieldOptionsForTable(exposedJoin.joinTable, fieldOptions, true, hiddenFieldNames);
|
||||
makeFieldOptionsForTable(exposedJoin.joinTable, fieldOptions, true, hiddenFieldNames, availableFieldNames, selectedFieldName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -130,27 +157,48 @@ export default function FieldAutoComplete({id, metaData, tableMetaData, handleFi
|
||||
// seems like, if we always add the open attribute, then if its false or null, then the autocomplete //
|
||||
// doesn't open at all... so, only add the attribute at all, if forceOpen is true //
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
const alsoOpen: {[key: string]: any} = {}
|
||||
if(forceOpen)
|
||||
const alsoOpen: { [key: string]: any } = {};
|
||||
if (forceOpen)
|
||||
{
|
||||
alsoOpen["open"] = forceOpen;
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function onChange(event: any, newValue: any, reason: string)
|
||||
{
|
||||
setSelectedFieldName(newValue ? newValue.fieldName : null);
|
||||
handleFieldChange(event, newValue, reason);
|
||||
}
|
||||
|
||||
return (
|
||||
<Autocomplete
|
||||
id={id}
|
||||
renderInput={(params) => (<TextField {...params} autoFocus={autoFocus} label={"Field"} variant="standard" autoComplete="off" type="search" InputProps={{...params.InputProps}} />)}
|
||||
renderInput={(params) =>
|
||||
{
|
||||
const inputProps = params.InputProps;
|
||||
const originalEndAdornment = inputProps.endAdornment;
|
||||
inputProps.endAdornment = <Box>
|
||||
{hasError && <Icon color="error">error_outline</Icon>}
|
||||
{originalEndAdornment}
|
||||
</Box>;
|
||||
|
||||
return (<TextField {...params} autoFocus={autoFocus} label={label} variant={variant} sx={textFieldSX} autoComplete="off" type="search" InputProps={inputProps} />)
|
||||
}}
|
||||
// @ts-ignore
|
||||
defaultValue={defaultValue}
|
||||
options={fieldOptions}
|
||||
onChange={handleFieldChange}
|
||||
onChange={onChange}
|
||||
isOptionEqualToValue={(option, value) => isFieldOptionEqual(option, value)}
|
||||
groupBy={fieldsGroupBy}
|
||||
getOptionLabel={(option) => getFieldOptionLabel(option)}
|
||||
renderOption={(props, option, state) => renderFieldOption(props, option, state)}
|
||||
autoSelect={true}
|
||||
autoHighlight={true}
|
||||
slotProps={{popper: {className: "filterCriteriaRowColumnPopper", style: {padding: 0, width: "250px"}}}}
|
||||
slotProps={autocompleteSlotProps ?? {}}
|
||||
noOptionsText={noOptionsText}
|
||||
{...alsoOpen}
|
||||
/>
|
||||
|
||||
|
@ -35,6 +35,7 @@ import DialogTitle from "@mui/material/DialogTitle";
|
||||
import Grid from "@mui/material/Grid";
|
||||
import Icon from "@mui/material/Icon";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import {any} from "prop-types";
|
||||
import React, {useState} from "react";
|
||||
import {useNavigate} from "react-router-dom";
|
||||
import {QCancelButton} from "qqq/components/buttons/DefaultButtons";
|
||||
@ -71,7 +72,12 @@ function hasGotoFieldNames(tableMetaData: QTableMetaData): boolean
|
||||
|
||||
function GotoRecordDialog(props: Props): JSX.Element
|
||||
{
|
||||
const fields: QFieldMetaData[] = [];
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// this is an array of array of fields. //
|
||||
// that is - each entry in the top-level array is a set of fields that can be used together to goto a record //
|
||||
// such as (pkey), (ukey-field1,ukey-field2). //
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
const options: QFieldMetaData[][] = [];
|
||||
|
||||
let pkey = props?.tableMetaData?.fields.get(props?.tableMetaData?.primaryKeyField);
|
||||
let addedPkey = false;
|
||||
@ -82,31 +88,38 @@ function GotoRecordDialog(props: Props): JSX.Element
|
||||
{
|
||||
for (let i = 0; i < mdbMetaData.gotoFieldNames.length; i++)
|
||||
{
|
||||
// todo - multi-field keys!!
|
||||
let fieldName = mdbMetaData.gotoFieldNames[i][0];
|
||||
let field = props.tableMetaData.fields.get(fieldName);
|
||||
if (field)
|
||||
const option: QFieldMetaData[] = [];
|
||||
options.push(option);
|
||||
for (let j = 0; j < mdbMetaData.gotoFieldNames[i].length; j++)
|
||||
{
|
||||
fields.push(field);
|
||||
|
||||
if (field.name == pkey.name)
|
||||
let fieldName = mdbMetaData.gotoFieldNames[i][j];
|
||||
let field = props.tableMetaData.fields.get(fieldName);
|
||||
if (field)
|
||||
{
|
||||
addedPkey = true;
|
||||
option.push(field);
|
||||
|
||||
if (pkey != null && field.name == pkey.name)
|
||||
{
|
||||
addedPkey = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// if pkey wasn't in the gotoField options meta-data, go ahead add it as an option here //
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
if (pkey && !addedPkey)
|
||||
{
|
||||
fields.unshift(pkey);
|
||||
options.unshift([pkey]);
|
||||
}
|
||||
|
||||
const makeInitialValues = () =>
|
||||
{
|
||||
const rs = {} as { [field: string]: string };
|
||||
fields.forEach((field) => rs[field.name] = "");
|
||||
options.forEach((option) => option.forEach((field) => rs[field.name] = ""));
|
||||
return (rs);
|
||||
};
|
||||
|
||||
@ -141,11 +154,16 @@ function GotoRecordDialog(props: Props): JSX.Element
|
||||
}
|
||||
else if (e.key == "Enter" && targetId?.startsWith("gotoInput-"))
|
||||
{
|
||||
const index = targetId?.replaceAll("gotoInput-", "");
|
||||
const parts = targetId?.split(/-/);
|
||||
const index = parts[1];
|
||||
document.getElementById("gotoButton-" + index).click();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/***************************************************************************
|
||||
** event handler for close button
|
||||
***************************************************************************/
|
||||
const closeRequested = () =>
|
||||
{
|
||||
if (props.mayClose)
|
||||
@ -154,10 +172,47 @@ function GotoRecordDialog(props: Props): JSX.Element
|
||||
}
|
||||
};
|
||||
|
||||
const goClicked = async (fieldName: string) =>
|
||||
|
||||
/*******************************************************************************
|
||||
** function to say if an option's submit button should be disabled
|
||||
*******************************************************************************/
|
||||
const isOptionSubmitButtonDisabled = (optionIndex: number) =>
|
||||
{
|
||||
let anyFieldsInThisOptionHaveAValue = false;
|
||||
|
||||
options[optionIndex].forEach((field) =>
|
||||
{
|
||||
if(values[field.name])
|
||||
{
|
||||
anyFieldsInThisOptionHaveAValue = true;
|
||||
}
|
||||
})
|
||||
|
||||
if(!anyFieldsInThisOptionHaveAValue)
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
return (false);
|
||||
}
|
||||
|
||||
|
||||
/***************************************************************************
|
||||
** event handler for clicking an 'option's go/submit button
|
||||
***************************************************************************/
|
||||
const optionGoClicked = async (optionIndex: number) =>
|
||||
{
|
||||
setError("");
|
||||
const filter = new QQueryFilter([new QFilterCriteria(fieldName, QCriteriaOperator.EQUALS, [values[fieldName]])], null, null, "AND", null, 10);
|
||||
|
||||
const criteria: QFilterCriteria[] = [];
|
||||
const queryStringParts: string[] = [];
|
||||
options[optionIndex].forEach((field) =>
|
||||
{
|
||||
criteria.push(new QFilterCriteria(field.name, QCriteriaOperator.EQUALS, [values[field.name]]))
|
||||
queryStringParts.push(`${field.name}=${encodeURIComponent(values[field.name])}`)
|
||||
})
|
||||
|
||||
const filter = new QQueryFilter(criteria, null, null, "AND", null, 10);
|
||||
|
||||
try
|
||||
{
|
||||
const queryResult = await qController.query(props.tableMetaData.name, filter, null, props.tableVariant);
|
||||
@ -168,12 +223,26 @@ function GotoRecordDialog(props: Props): JSX.Element
|
||||
}
|
||||
else if (queryResult.length == 1)
|
||||
{
|
||||
navigate(`${props.metaData.getTablePathByName(props.tableMetaData.name)}/${encodeURIComponent(queryResult[0].values.get(props.tableMetaData.primaryKeyField))}`);
|
||||
if(options[optionIndex].length == 1 && options[optionIndex][0].name == pkey?.name)
|
||||
{
|
||||
/////////////////////////////////////////////////
|
||||
// navigate by pkey, if that's how we searched //
|
||||
/////////////////////////////////////////////////
|
||||
navigate(`${props.metaData.getTablePathByName(props.tableMetaData.name)}/${encodeURIComponent(queryResult[0].values.get(props.tableMetaData.primaryKeyField))}`);
|
||||
}
|
||||
else
|
||||
{
|
||||
/////////////////////////////////
|
||||
// else navigate by unique-key //
|
||||
/////////////////////////////////
|
||||
navigate(`${props.metaData.getTablePathByName(props.tableMetaData.name)}/key/?${queryStringParts.join("&")}`);
|
||||
}
|
||||
|
||||
close();
|
||||
}
|
||||
else
|
||||
{
|
||||
setError("More than 1 record found...");
|
||||
setError("More than 1 record was found...");
|
||||
setTimeout(() => setError(""), 3000);
|
||||
}
|
||||
}
|
||||
@ -187,7 +256,7 @@ function GotoRecordDialog(props: Props): JSX.Element
|
||||
|
||||
if (props.tableMetaData)
|
||||
{
|
||||
if (fields.length == 0 && !error)
|
||||
if (options.length == 0 && !error)
|
||||
{
|
||||
setError("This table is not configured for this feature.");
|
||||
}
|
||||
@ -200,31 +269,38 @@ function GotoRecordDialog(props: Props): JSX.Element
|
||||
<DialogContent>
|
||||
{props.subHeader}
|
||||
{
|
||||
fields.map((field, index) =>
|
||||
(
|
||||
<Grid key={field.name} container alignItems="center" py={1}>
|
||||
<Grid item xs={3} textAlign="right" pr={2}>
|
||||
{field.label}
|
||||
</Grid>
|
||||
<Grid item xs={6}>
|
||||
<TextField
|
||||
id={`gotoInput-${index}`}
|
||||
autoFocus={index == 0}
|
||||
autoComplete="off"
|
||||
inputProps={{width: "100%"}}
|
||||
onChange={(e) => handleChange(field.name, e.target.value)}
|
||||
value={values[field.name]}
|
||||
sx={{width: "100%"}}
|
||||
onFocus={event => event.target.select()}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid item xs={1} pl={2}>
|
||||
<MDButton id={`gotoButton-${index}`} type="submit" variant="gradient" color="info" size="small" onClick={() => goClicked(field.name)} fullWidth startIcon={<Icon>double_arrow</Icon>} disabled={`${values[field.name]}`.length == 0}>
|
||||
Go
|
||||
</MDButton>
|
||||
</Grid>
|
||||
</Grid>
|
||||
))
|
||||
options.map((option, optionIndex) =>
|
||||
<Box key={optionIndex}>
|
||||
{
|
||||
option.map((field, index) =>
|
||||
(
|
||||
<Grid key={field.name} container alignItems="center" py={1}>
|
||||
<Grid item xs={3} textAlign="right" pr={2}>
|
||||
{field.label}
|
||||
</Grid>
|
||||
<Grid item xs={6}>
|
||||
<TextField
|
||||
id={`gotoInput-${optionIndex}-${index}`}
|
||||
autoFocus={optionIndex == 0 && index == 0}
|
||||
autoComplete="off"
|
||||
inputProps={{width: "100%"}}
|
||||
onChange={(e) => handleChange(field.name, e.target.value)}
|
||||
value={values[field.name]}
|
||||
sx={{width: "100%"}}
|
||||
onFocus={event => event.target.select()}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid item xs={1} pl={2}>
|
||||
{
|
||||
(index == option.length - 1) &&
|
||||
<MDButton id={`gotoButton-${optionIndex}`} type="submit" variant="gradient" color="info" size="small" onClick={() => optionGoClicked(optionIndex)} fullWidth startIcon={<Icon>double_arrow</Icon>} disabled={isOptionSubmitButtonDisabled(optionIndex)}>Go</MDButton>
|
||||
}
|
||||
</Grid>
|
||||
</Grid>
|
||||
))
|
||||
}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
{
|
||||
error &&
|
||||
@ -282,7 +358,7 @@ export function GotoRecordButton(props: GotoRecordButtonProps): JSX.Element
|
||||
return (
|
||||
<React.Fragment>
|
||||
{
|
||||
props.buttonVisible && hasGotoFieldNames(props.tableMetaData) && <Button onClick={openGoto}>Go To...</Button>
|
||||
props.buttonVisible && hasGotoFieldNames(props.tableMetaData) && <Button onClick={openGoto} sx={{whiteSpace: "nowrap"}}>Go To...</Button>
|
||||
}
|
||||
<GotoRecordDialog metaData={props.metaData} tableMetaData={props.tableMetaData} tableVariant={props.tableVariant} isOpen={gotoIsOpen} closeHandler={closeGoto} mayClose={props.mayClose} subHeader={props.subHeader} />
|
||||
</React.Fragment>
|
||||
|
@ -22,7 +22,7 @@
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import {QTableSection} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableSection";
|
||||
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
|
||||
import Box from "@mui/material/Box";
|
||||
import {Box} from "@mui/material";
|
||||
import Card from "@mui/material/Card";
|
||||
import Icon from "@mui/material/Icon";
|
||||
import {Theme} from "@mui/material/styles";
|
||||
@ -76,12 +76,12 @@ function QRecordSidebar({tableSections, widgetMetaDataList, light, stickyTop}: P
|
||||
|
||||
|
||||
return (
|
||||
<Card sx={{borderRadius: "0.75rem", position: "sticky", top: stickyTop, overflow: "auto", maxHeight: "calc(100vh - 2rem)"}}>
|
||||
<Box component="ul" display="flex" flexDirection="column" p={2} m={0} sx={{listStyle: "none"}}>
|
||||
<Card sx={{borderRadius: "0.75rem", position: "sticky", top: stickyTop, overflow: "hidden", maxHeight: "calc(100vh - 2rem)"}}>
|
||||
<Box component="ul" display="flex" flexDirection="column" p={2} m={0} sx={{listStyle: "none", overflow: "auto", height: "100%"}}>
|
||||
{
|
||||
sidebarEntries ? sidebarEntries.map((entry: SidebarEntry, key: number) => (
|
||||
|
||||
<HashLink key={`section-link-${entry.name}`} to={`#${entry.name}`}>
|
||||
<Box key={`section-link-${entry.name}`} onClick={() => document.getElementById(entry.name).scrollIntoView()} sx={{cursor: "pointer"}}>
|
||||
<Box key={`section-${entry.name}`} component="li" pt={key === 0 ? 0 : 1}>
|
||||
<MDTypography
|
||||
variant="button"
|
||||
@ -112,7 +112,7 @@ function QRecordSidebar({tableSections, widgetMetaDataList, light, stickyTop}: P
|
||||
|
||||
</MDTypography>
|
||||
</Box>
|
||||
</HashLink>
|
||||
</Box>
|
||||
)) : null
|
||||
}
|
||||
</Box>
|
||||
|
@ -44,6 +44,7 @@ import QContext from "QContext";
|
||||
import colors from "qqq/assets/theme/base/colors";
|
||||
import {QCancelButton, QDeleteButton, QSaveButton} from "qqq/components/buttons/DefaultButtons";
|
||||
import RecordQueryView from "qqq/models/query/RecordQueryView";
|
||||
import {QueryScreenUsage} from "qqq/pages/records/query/RecordQuery";
|
||||
import FilterUtils from "qqq/utils/qqq/FilterUtils";
|
||||
import {SavedViewUtils} from "qqq/utils/qqq/SavedViewUtils";
|
||||
import React, {useContext, useEffect, useRef, useState} from "react";
|
||||
@ -59,14 +60,17 @@ interface Props
|
||||
view?: RecordQueryView;
|
||||
viewAsJson?: string;
|
||||
viewOnChangeCallback?: (selectedSavedViewId: number) => void;
|
||||
loadingSavedView: boolean
|
||||
loadingSavedView: boolean;
|
||||
queryScreenUsage: QueryScreenUsage;
|
||||
}
|
||||
|
||||
function SavedViews({qController, metaData, tableMetaData, currentSavedView, tableDefaultView, view, viewAsJson, viewOnChangeCallback, loadingSavedView}: Props): JSX.Element
|
||||
function SavedViews({qController, metaData, tableMetaData, currentSavedView, tableDefaultView, view, viewAsJson, viewOnChangeCallback, loadingSavedView, queryScreenUsage}: Props): JSX.Element
|
||||
{
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [savedViews, setSavedViews] = useState([] as QRecord[]);
|
||||
const [yourSavedViews, setYourSavedViews] = useState([] as QRecord[]);
|
||||
const [viewsSharedWithYou, setViewsSharedWithYou] = useState([] as QRecord[]);
|
||||
const [savedViewsMenu, setSavedViewsMenu] = useState(null);
|
||||
const [savedViewsHaveLoaded, setSavedViewsHaveLoaded] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
@ -87,9 +91,17 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
const RENAME_OPTION = "Rename...";
|
||||
const DELETE_OPTION = "Delete...";
|
||||
const CLEAR_OPTION = "New View";
|
||||
const dropdownOptions = [DUPLICATE_OPTION, RENAME_OPTION, DELETE_OPTION, CLEAR_OPTION];
|
||||
const NEW_REPORT_OPTION = "Create Report from Current View";
|
||||
|
||||
const {accentColor, accentColorLight} = useContext(QContext);
|
||||
const {accentColor, accentColorLight, userId: currentUserId} = useContext(QContext);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// this component is used by <RecordQuery> - but that component has different usages - //
|
||||
// e.g., the full-fledged query screen, but also, within other screens (e.g., a modal //
|
||||
// under the FilterAndColumnsSetupWidget). So, there are some behaviors we only want when //
|
||||
// we're on the full-fledged query screen, such as changing the URL with saved view ids. //
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////
|
||||
const isQueryScreen = queryScreenUsage == "queryScreen";
|
||||
|
||||
const openSavedViewsMenu = (event: any) => setSavedViewsMenu(event.currentTarget);
|
||||
const closeSavedViewsMenu = () => setSavedViewsMenu(null);
|
||||
@ -104,13 +116,13 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
{
|
||||
setSavedViewsHaveLoaded(true);
|
||||
});
|
||||
}, [location, tableMetaData])
|
||||
}, [location, tableMetaData]);
|
||||
|
||||
|
||||
const baseView = currentSavedView ? JSON.parse(currentSavedView.values.get("viewJson")) as RecordQueryView : tableDefaultView;
|
||||
const viewDiffs = SavedViewUtils.diffViews(tableMetaData, baseView, view);
|
||||
let viewIsModified = false;
|
||||
if(viewDiffs.length > 0)
|
||||
if (viewDiffs.length > 0)
|
||||
{
|
||||
viewIsModified = true;
|
||||
}
|
||||
@ -120,7 +132,7 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
*******************************************************************************/
|
||||
async function loadSavedViews()
|
||||
{
|
||||
if (! tableMetaData)
|
||||
if (!tableMetaData)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@ -130,8 +142,24 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
|
||||
let savedViews = await makeSavedViewRequest("querySavedView", formData);
|
||||
setSavedViews(savedViews);
|
||||
}
|
||||
|
||||
const yourSavedViews: QRecord[] = [];
|
||||
const viewsSharedWithYou: QRecord[] = [];
|
||||
for (let i = 0; i < savedViews.length; i++)
|
||||
{
|
||||
const record = savedViews[i];
|
||||
if (record.values.get("userId") == currentUserId)
|
||||
{
|
||||
yourSavedViews.push(record);
|
||||
}
|
||||
else
|
||||
{
|
||||
viewsSharedWithYou.push(record);
|
||||
}
|
||||
}
|
||||
setYourSavedViews(yourSavedViews);
|
||||
setViewsSharedWithYou(viewsSharedWithYou);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@ -142,11 +170,13 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
setSaveFilterPopupOpen(false);
|
||||
closeSavedViewsMenu();
|
||||
viewOnChangeCallback(record.values.get("id"));
|
||||
navigate(`${metaData.getTablePathByName(tableMetaData.name)}/savedView/${record.values.get("id")}`);
|
||||
if (isQueryScreen)
|
||||
{
|
||||
navigate(`${metaData.getTablePathByName(tableMetaData.name)}/savedView/${record.values.get("id")}`);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** fired when a save option is selected from the save... button/dropdown combo
|
||||
*******************************************************************************/
|
||||
@ -158,12 +188,12 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
setSaveFilterPopupOpen(true);
|
||||
setIsSaveFilterAs(false);
|
||||
setIsRenameFilter(false);
|
||||
setIsDeleteFilter(false)
|
||||
setIsDeleteFilter(false);
|
||||
|
||||
switch(optionName)
|
||||
switch (optionName)
|
||||
{
|
||||
case SAVE_OPTION:
|
||||
if(currentSavedView == null)
|
||||
if (currentSavedView == null)
|
||||
{
|
||||
setSavedViewNameInputValue("");
|
||||
}
|
||||
@ -173,24 +203,46 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
setIsSaveFilterAs(true);
|
||||
break;
|
||||
case CLEAR_OPTION:
|
||||
setSaveFilterPopupOpen(false)
|
||||
setSaveFilterPopupOpen(false);
|
||||
viewOnChangeCallback(null);
|
||||
navigate(metaData.getTablePathByName(tableMetaData.name));
|
||||
if (isQueryScreen)
|
||||
{
|
||||
navigate(metaData.getTablePathByName(tableMetaData.name));
|
||||
}
|
||||
break;
|
||||
case RENAME_OPTION:
|
||||
if(currentSavedView != null)
|
||||
if (currentSavedView != null)
|
||||
{
|
||||
setSavedViewNameInputValue(currentSavedView.values.get("label"));
|
||||
}
|
||||
setIsRenameFilter(true);
|
||||
break;
|
||||
case DELETE_OPTION:
|
||||
setIsDeleteFilter(true)
|
||||
setIsDeleteFilter(true);
|
||||
break;
|
||||
case NEW_REPORT_OPTION:
|
||||
createNewReport();
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function createNewReport()
|
||||
{
|
||||
const defaultValues: { [key: string]: any } = {};
|
||||
defaultValues.tableName = tableMetaData.name;
|
||||
|
||||
let filterForBackend = JSON.parse(JSON.stringify(view.queryFilter));
|
||||
filterForBackend = FilterUtils.prepQueryFilterForBackend(tableMetaData, filterForBackend);
|
||||
|
||||
defaultValues.queryFilterJson = JSON.stringify(filterForBackend);
|
||||
defaultValues.columnsJson = JSON.stringify(view.queryColumns);
|
||||
navigate(`${metaData.getTablePathByName("savedReport")}/create#defaultValues=${encodeURIComponent(JSON.stringify(defaultValues))}`);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** fired when save or delete button saved on confirmation dialogs
|
||||
@ -211,7 +263,7 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
setSaveFilterPopupOpen(false);
|
||||
setSaveOptionsOpen(false);
|
||||
|
||||
await(async() =>
|
||||
await (async () =>
|
||||
{
|
||||
handleDropdownOptionClick(CLEAR_OPTION);
|
||||
})();
|
||||
@ -231,14 +283,14 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// strip away incomplete filters too, just for cleaner saved view filters //
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
FilterUtils.stripAwayIncompleteCriteria(viewObject.queryFilter)
|
||||
FilterUtils.stripAwayIncompleteCriteria(viewObject.queryFilter);
|
||||
|
||||
formData.append("viewJson", JSON.stringify(viewObject));
|
||||
|
||||
if (isSaveFilterAs || isRenameFilter || currentSavedView == null)
|
||||
{
|
||||
formData.append("label", savedViewNameInputValue);
|
||||
if(currentSavedView != null && isRenameFilter)
|
||||
if (currentSavedView != null && isRenameFilter)
|
||||
{
|
||||
formData.append("id", currentSavedView.values.get("id"));
|
||||
}
|
||||
@ -249,7 +301,7 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
formData.append("label", currentSavedView?.values.get("label"));
|
||||
}
|
||||
const recordList = await makeSavedViewRequest("storeSavedView", formData);
|
||||
await(async() =>
|
||||
await (async () =>
|
||||
{
|
||||
if (recordList && recordList.length > 0)
|
||||
{
|
||||
@ -266,11 +318,11 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
catch (e: any)
|
||||
{
|
||||
let message = JSON.stringify(e);
|
||||
if(typeof e == "string")
|
||||
if (typeof e == "string")
|
||||
{
|
||||
message = e;
|
||||
}
|
||||
else if(typeof e == "object" && e.message)
|
||||
else if (typeof e == "object" && e.message)
|
||||
{
|
||||
message = e.message;
|
||||
}
|
||||
@ -285,7 +337,6 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** hides/shows the save options
|
||||
*******************************************************************************/
|
||||
@ -295,7 +346,6 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
};
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** closes save options menu (on clickaway)
|
||||
*******************************************************************************/
|
||||
@ -310,7 +360,6 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
};
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** stores the current dialog input text to state
|
||||
*******************************************************************************/
|
||||
@ -320,7 +369,6 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
};
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** closes current dialog
|
||||
*******************************************************************************/
|
||||
@ -330,7 +378,6 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
};
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** make a request to the backend for various savedView processes
|
||||
*******************************************************************************/
|
||||
@ -339,7 +386,7 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
/////////////////////////
|
||||
// fetch saved filters //
|
||||
/////////////////////////
|
||||
let savedViews = [] as QRecord[]
|
||||
let savedViews = [] as QRecord[];
|
||||
try
|
||||
{
|
||||
//////////////////////////////////////////////////////////////////
|
||||
@ -350,12 +397,12 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
if (processResult instanceof QJobError)
|
||||
{
|
||||
const jobError = processResult as QJobError;
|
||||
throw(jobError.error);
|
||||
throw (jobError.error);
|
||||
}
|
||||
else
|
||||
{
|
||||
const result = processResult as QJobComplete;
|
||||
if(result.values.savedViewList)
|
||||
if (result.values.savedViewList)
|
||||
{
|
||||
for (let i = 0; i < result.values.savedViewList.length; i++)
|
||||
{
|
||||
@ -367,7 +414,7 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
}
|
||||
catch (e)
|
||||
{
|
||||
throw(e);
|
||||
throw (e);
|
||||
}
|
||||
|
||||
return (savedViews);
|
||||
@ -376,20 +423,31 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
const hasStorePermission = metaData?.processes.has("storeSavedView");
|
||||
const hasDeletePermission = metaData?.processes.has("deleteSavedView");
|
||||
const hasQueryPermission = metaData?.processes.has("querySavedView");
|
||||
const hasSavedReportsPermission = metaData?.tables.has("savedReport");
|
||||
|
||||
const tooltipMaxWidth = (maxWidth: string) =>
|
||||
{
|
||||
return ({slotProps: {
|
||||
tooltip: {
|
||||
sx: {
|
||||
maxWidth: maxWidth
|
||||
return ({
|
||||
slotProps: {
|
||||
tooltip: {
|
||||
sx: {
|
||||
maxWidth: maxWidth
|
||||
}
|
||||
}
|
||||
}
|
||||
}})
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const menuTooltipAttribs = {...tooltipMaxWidth("250px"), placement: "left", enterDelay: 1000} as TooltipProps;
|
||||
|
||||
let disabledBecauseNotOwner = false;
|
||||
let notOwnerTooltipText = null;
|
||||
if (currentSavedView && currentSavedView.values.get("userId") != currentUserId)
|
||||
{
|
||||
disabledBecauseNotOwner = true;
|
||||
notOwnerTooltipText = "You may not save changes to this view, because you are not its owner.";
|
||||
}
|
||||
|
||||
const renderSavedViewsMenu = tableMetaData && (
|
||||
<Menu
|
||||
anchorEl={savedViewsMenu}
|
||||
@ -398,68 +456,109 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
open={Boolean(savedViewsMenu)}
|
||||
onClose={closeSavedViewsMenu}
|
||||
keepMounted
|
||||
PaperProps={{style: {maxHeight: "calc(100vh - 200px)", minHeight: "200px"}}}
|
||||
PaperProps={{style: {maxHeight: "calc(100vh - 200px)", minWidth: "300px"}}}
|
||||
>
|
||||
<MenuItem sx={{width: "300px"}} disabled style={{"opacity": "initial"}}><b>View Actions</b></MenuItem>
|
||||
{
|
||||
hasStorePermission &&
|
||||
<Tooltip {...menuTooltipAttribs} title={<>Save your current filters, columns and settings, for quick re-use at a later time.<br /><br />You will be prompted to enter a name if you choose this option.</>}>
|
||||
<MenuItem onClick={() => handleDropdownOptionClick(SAVE_OPTION)}>
|
||||
<ListItemIcon><Icon>save</Icon></ListItemIcon>
|
||||
{currentSavedView ? "Save..." : "Save As..."}
|
||||
</MenuItem>
|
||||
isQueryScreen &&
|
||||
<MenuItem sx={{width: "300px"}} disabled style={{"opacity": "initial"}}><b>View Actions</b></MenuItem>
|
||||
}
|
||||
{
|
||||
isQueryScreen && hasStorePermission &&
|
||||
<Tooltip {...menuTooltipAttribs} title={notOwnerTooltipText ?? <>Save your current filters, columns and settings, for quick re-use at a later time.<br /><br />You will be prompted to enter a name if you choose this option.</>}>
|
||||
<span>
|
||||
<MenuItem disabled={disabledBecauseNotOwner} onClick={() => handleDropdownOptionClick(SAVE_OPTION)}>
|
||||
<ListItemIcon><Icon>save</Icon></ListItemIcon>
|
||||
{currentSavedView ? "Save..." : "Save As..."}
|
||||
</MenuItem>
|
||||
</span>
|
||||
</Tooltip>
|
||||
}
|
||||
{
|
||||
hasStorePermission && currentSavedView != null &&
|
||||
<Tooltip {...menuTooltipAttribs} title="Change the name for this saved view.">
|
||||
<MenuItem disabled={currentSavedView === null} onClick={() => handleDropdownOptionClick(RENAME_OPTION)}>
|
||||
<ListItemIcon><Icon>edit</Icon></ListItemIcon>
|
||||
Rename...
|
||||
</MenuItem>
|
||||
isQueryScreen && hasStorePermission && currentSavedView != null &&
|
||||
<Tooltip {...menuTooltipAttribs} title={notOwnerTooltipText ?? "Change the name for this saved view."}>
|
||||
<span>
|
||||
<MenuItem disabled={currentSavedView === null || disabledBecauseNotOwner} onClick={() => handleDropdownOptionClick(RENAME_OPTION)}>
|
||||
<ListItemIcon><Icon>edit</Icon></ListItemIcon>
|
||||
Rename...
|
||||
</MenuItem>
|
||||
</span>
|
||||
</Tooltip>
|
||||
}
|
||||
{
|
||||
hasStorePermission && currentSavedView != null &&
|
||||
isQueryScreen && hasStorePermission && currentSavedView != null &&
|
||||
<Tooltip {...menuTooltipAttribs} title="Save a new copy this view, with a different name, separate from the original.">
|
||||
<MenuItem disabled={currentSavedView === null} onClick={() => handleDropdownOptionClick(DUPLICATE_OPTION)}>
|
||||
<ListItemIcon><Icon>content_copy</Icon></ListItemIcon>
|
||||
Save As...
|
||||
</MenuItem>
|
||||
<span>
|
||||
<MenuItem disabled={currentSavedView === null} onClick={() => handleDropdownOptionClick(DUPLICATE_OPTION)}>
|
||||
<ListItemIcon><Icon>content_copy</Icon></ListItemIcon>
|
||||
Save As...
|
||||
</MenuItem>
|
||||
</span>
|
||||
</Tooltip>
|
||||
}
|
||||
{
|
||||
hasStorePermission && currentSavedView != null &&
|
||||
<Tooltip {...menuTooltipAttribs} title="Delete this saved view.">
|
||||
<MenuItem disabled={currentSavedView === null} onClick={() => handleDropdownOptionClick(DELETE_OPTION)}>
|
||||
<ListItemIcon><Icon>delete</Icon></ListItemIcon>
|
||||
Delete...
|
||||
</MenuItem>
|
||||
isQueryScreen && hasDeletePermission && currentSavedView != null &&
|
||||
<Tooltip {...menuTooltipAttribs} title={notOwnerTooltipText ?? "Delete this saved view."}>
|
||||
<span>
|
||||
<MenuItem disabled={currentSavedView === null || disabledBecauseNotOwner} onClick={() => handleDropdownOptionClick(DELETE_OPTION)}>
|
||||
<ListItemIcon><Icon>delete</Icon></ListItemIcon>
|
||||
Delete...
|
||||
</MenuItem>
|
||||
</span>
|
||||
</Tooltip>
|
||||
}
|
||||
{
|
||||
isQueryScreen &&
|
||||
<Tooltip {...menuTooltipAttribs} title="Create a new view of this table, resetting the filters and columns to their defaults.">
|
||||
<MenuItem onClick={() => handleDropdownOptionClick(CLEAR_OPTION)}>
|
||||
<ListItemIcon><Icon>monitor</Icon></ListItemIcon>
|
||||
New View
|
||||
</MenuItem>
|
||||
<span>
|
||||
<MenuItem onClick={() => handleDropdownOptionClick(CLEAR_OPTION)}>
|
||||
<ListItemIcon><Icon>monitor</Icon></ListItemIcon>
|
||||
New View
|
||||
</MenuItem>
|
||||
</span>
|
||||
</Tooltip>
|
||||
}
|
||||
<Divider/>
|
||||
{
|
||||
isQueryScreen && hasSavedReportsPermission &&
|
||||
<Tooltip {...menuTooltipAttribs} title="Create a new Saved Report using your current view of this table as a starting point.">
|
||||
<span>
|
||||
<MenuItem onClick={() => handleDropdownOptionClick(NEW_REPORT_OPTION)}>
|
||||
<ListItemIcon><Icon>article</Icon></ListItemIcon>
|
||||
Create Report from Current View
|
||||
</MenuItem>
|
||||
</span>
|
||||
</Tooltip>
|
||||
}
|
||||
{
|
||||
isQueryScreen && <Divider />
|
||||
}
|
||||
<MenuItem disabled style={{"opacity": "initial"}}><b>Your Saved Views</b></MenuItem>
|
||||
{
|
||||
savedViews && savedViews.length > 0 ? (
|
||||
savedViews.map((record: QRecord, index: number) =>
|
||||
yourSavedViews && yourSavedViews.length > 0 ? (
|
||||
yourSavedViews.map((record: QRecord, index: number) =>
|
||||
<MenuItem sx={{paddingLeft: "50px"}} key={`savedFiler-${index}`} onClick={() => handleSavedViewRecordOnClick(record)}>
|
||||
{record.values.get("label")}
|
||||
</MenuItem>
|
||||
)
|
||||
): (
|
||||
<MenuItem>
|
||||
) : (
|
||||
<MenuItem disabled sx={{opacity: "1 !important"}}>
|
||||
<i>You do not have any saved views for this table.</i>
|
||||
</MenuItem>
|
||||
)
|
||||
}
|
||||
<MenuItem disabled style={{"opacity": "initial"}}><b>Views Shared with you</b></MenuItem>
|
||||
{
|
||||
viewsSharedWithYou && viewsSharedWithYou.length > 0 ? (
|
||||
viewsSharedWithYou.map((record: QRecord, index: number) =>
|
||||
<MenuItem sx={{paddingLeft: "50px"}} key={`savedFiler-${index}`} onClick={() => handleSavedViewRecordOnClick(record)}>
|
||||
{record.values.get("label")}
|
||||
</MenuItem>
|
||||
)
|
||||
) : (
|
||||
<MenuItem disabled sx={{opacity: "1 !important"}}>
|
||||
<i>You do not have any views shared with you for this table.</i>
|
||||
</MenuItem>
|
||||
)
|
||||
}
|
||||
</Menu>
|
||||
);
|
||||
|
||||
@ -468,7 +567,7 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
let buttonBorder = colors.grayLines.main;
|
||||
let buttonColor = colors.gray.main;
|
||||
|
||||
if(currentSavedView)
|
||||
if (currentSavedView)
|
||||
{
|
||||
if (viewIsModified)
|
||||
{
|
||||
@ -496,23 +595,23 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
color: buttonColor,
|
||||
backgroundColor: buttonBackground,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function isSaveButtonDisabled(): boolean
|
||||
{
|
||||
if(isSubmitting)
|
||||
if (isSubmitting)
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
|
||||
const haveInputText = (savedViewNameInputValue != null && savedViewNameInputValue.trim() != "")
|
||||
const haveInputText = (savedViewNameInputValue != null && savedViewNameInputValue.trim() != "");
|
||||
|
||||
if(isSaveFilterAs || isRenameFilter || currentSavedView == null)
|
||||
if (isSaveFilterAs || isRenameFilter || currentSavedView == null)
|
||||
{
|
||||
if(!haveInputText)
|
||||
if (!haveInputText)
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
@ -541,7 +640,7 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
fontWeight: 500,
|
||||
fontSize: "0.875rem",
|
||||
p: "0.5rem",
|
||||
... buttonStyles
|
||||
...buttonStyles
|
||||
}}
|
||||
>
|
||||
<Icon sx={{mr: "0.5rem"}}>save</Icon>
|
||||
@ -554,6 +653,29 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
<Box pl={2} pr={2} sx={{display: "flex", alignItems: "center"}}>
|
||||
{
|
||||
!currentSavedView && viewIsModified && <>
|
||||
{
|
||||
isQueryScreen && <>
|
||||
<Tooltip {...tooltipMaxWidth("24rem")} sx={{cursor: "pointer"}} title={<>
|
||||
<b>Unsaved Changes</b>
|
||||
<ul style={{padding: "0.5rem 1rem"}}>
|
||||
{
|
||||
viewDiffs.map((s: string, i: number) => <li key={i}>{s}</li>)
|
||||
}
|
||||
</ul>
|
||||
</>}>
|
||||
<Button disableRipple={true} sx={linkButtonStyle} onClick={() => handleDropdownOptionClick(SAVE_OPTION)}>Save View As…</Button>
|
||||
</Tooltip>
|
||||
|
||||
{/* vertical rule */}
|
||||
<Box display="inline-block" borderLeft={`1px solid ${colors.grayLines.main}`} height="1rem" width="1px" position="relative" />
|
||||
</>
|
||||
}
|
||||
|
||||
<Button disableRipple={true} sx={{color: colors.gray.main, ...linkButtonStyle}} onClick={() => handleDropdownOptionClick(CLEAR_OPTION)}>Reset All Changes</Button>
|
||||
</>
|
||||
}
|
||||
{
|
||||
isQueryScreen && currentSavedView && viewIsModified && <>
|
||||
<Tooltip {...tooltipMaxWidth("24rem")} sx={{cursor: "pointer"}} title={<>
|
||||
<b>Unsaved Changes</b>
|
||||
<ul style={{padding: "0.5rem 1rem"}}>
|
||||
@ -561,36 +683,50 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
viewDiffs.map((s: string, i: number) => <li key={i}>{s}</li>)
|
||||
}
|
||||
</ul>
|
||||
{
|
||||
notOwnerTooltipText && <i>{notOwnerTooltipText}</i>
|
||||
}
|
||||
</>}>
|
||||
<Button disableRipple={true} sx={linkButtonStyle} onClick={() => handleDropdownOptionClick(SAVE_OPTION)}>Save View As…</Button>
|
||||
</Tooltip>
|
||||
|
||||
{/* vertical rule */}
|
||||
<Box display="inline-block" borderLeft={`1px solid ${colors.grayLines.main}`} height="1rem" width="1px" position="relative" />
|
||||
|
||||
<Button disableRipple={true} sx={{color: colors.gray.main, ... linkButtonStyle}} onClick={() => handleDropdownOptionClick(CLEAR_OPTION)}>Reset All Changes</Button>
|
||||
</>
|
||||
}
|
||||
{
|
||||
currentSavedView && viewIsModified && <>
|
||||
<Tooltip {...tooltipMaxWidth("24rem")} sx={{cursor: "pointer"}} title={<>
|
||||
<b>Unsaved Changes</b>
|
||||
<ul style={{padding: "0.5rem 1rem"}}>
|
||||
{
|
||||
viewDiffs.map((s: string, i: number) => <li key={i}>{s}</li>)
|
||||
}
|
||||
</ul></>}>
|
||||
<Box display="inline" sx={{...linkButtonStyle, p: 0, cursor: "default", position: "relative", top: "-1px"}}>{viewDiffs.length} Unsaved Change{viewDiffs.length == 1 ? "" : "s"}</Box>
|
||||
</Tooltip>
|
||||
|
||||
<Button disableRipple={true} sx={linkButtonStyle} onClick={() => handleDropdownOptionClick(SAVE_OPTION)}>Save…</Button>
|
||||
{disabledBecauseNotOwner ? <> </> : <Button disableRipple={true} sx={linkButtonStyle} onClick={() => handleDropdownOptionClick(SAVE_OPTION)}>Save…</Button>}
|
||||
|
||||
{/* vertical rule */}
|
||||
<Box display="inline-block" borderLeft={`1px solid ${colors.grayLines.main}`} height="1rem" width="1px" position="relative" />
|
||||
|
||||
<Button disableRipple={true} sx={{color: colors.gray.main, ... linkButtonStyle}} onClick={() => handleSavedViewRecordOnClick(currentSavedView)}>Reset All Changes</Button>
|
||||
<Button disableRipple={true} sx={{color: colors.gray.main, ...linkButtonStyle}} onClick={() => handleSavedViewRecordOnClick(currentSavedView)}>Reset All Changes</Button>
|
||||
</>
|
||||
}
|
||||
{
|
||||
!isQueryScreen && currentSavedView &&
|
||||
<Box>
|
||||
<Box display="inline-block" fontSize="0.875rem" fontWeight="500" sx={{position: "relative", top: "-1px"}}>
|
||||
{currentSavedView.values.get("label")}
|
||||
</Box>
|
||||
|
||||
{
|
||||
viewIsModified &&
|
||||
<>
|
||||
<Tooltip {...tooltipMaxWidth("24rem")} sx={{cursor: "pointer"}} title={<>
|
||||
<b>Changes</b>
|
||||
<ul style={{padding: "0.5rem 1rem"}}>
|
||||
{
|
||||
viewDiffs.map((s: string, i: number) => <li key={i}>{s}</li>)
|
||||
}
|
||||
</ul>
|
||||
</>}>
|
||||
<Box display="inline" ml="0.25rem" mr="0.25rem" sx={{...linkButtonStyle, p: 0, cursor: "default", position: "relative", top: "-1px"}}>with {viewDiffs.length} Change{viewDiffs.length == 1 ? "" : "s"}</Box>
|
||||
</Tooltip>
|
||||
<Button disableRipple={true} sx={{color: colors.gray.main, ...linkButtonStyle}} onClick={() => handleSavedViewRecordOnClick(currentSavedView)}>Reset Changes</Button>
|
||||
</>
|
||||
}
|
||||
|
||||
{/* vertical rule */}
|
||||
<Box display="inline-block" ml="0.25rem" borderLeft={`1px solid ${colors.grayLines.main}`} height="1rem" width="1px" position="relative" />
|
||||
<Button disableRipple={true} sx={{color: colors.gray.main, ...linkButtonStyle}} onClick={() => handleDropdownOptionClick(CLEAR_OPTION)}>Reset to New View</Button>
|
||||
</Box>
|
||||
}
|
||||
</Box>
|
||||
</Box>
|
||||
{
|
||||
@ -618,15 +754,15 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
) : (
|
||||
isSaveFilterAs ? (
|
||||
<DialogTitle id="alert-dialog-title">Save View As</DialogTitle>
|
||||
):(
|
||||
) : (
|
||||
isRenameFilter ? (
|
||||
<DialogTitle id="alert-dialog-title">Rename View</DialogTitle>
|
||||
):(
|
||||
) : (
|
||||
<DialogTitle id="alert-dialog-title">Update Existing View</DialogTitle>
|
||||
)
|
||||
)
|
||||
)
|
||||
):(
|
||||
) : (
|
||||
<DialogTitle id="alert-dialog-title">Save New View</DialogTitle>
|
||||
)
|
||||
}
|
||||
@ -637,12 +773,12 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
</Box>
|
||||
) : ("")}
|
||||
{
|
||||
(! currentSavedView || isSaveFilterAs || isRenameFilter) && ! isDeleteFilter ? (
|
||||
(!currentSavedView || isSaveFilterAs || isRenameFilter) && !isDeleteFilter ? (
|
||||
<Box>
|
||||
{
|
||||
isSaveFilterAs ? (
|
||||
<Box mb={3}>Enter a name for this new saved view.</Box>
|
||||
):(
|
||||
) : (
|
||||
<Box mb={3}>Enter a new name for this saved view.</Box>
|
||||
)
|
||||
}
|
||||
@ -660,10 +796,10 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
):(
|
||||
) : (
|
||||
isDeleteFilter ? (
|
||||
<Box>Are you sure you want to delete the view {`'${currentSavedView?.values.get("label")}'`}?</Box>
|
||||
):(
|
||||
) : (
|
||||
<Box>Are you sure you want to update the view {`'${currentSavedView?.values.get("label")}'`}?</Box>
|
||||
)
|
||||
)
|
||||
@ -675,7 +811,7 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
|
||||
isDeleteFilter ?
|
||||
<QDeleteButton onClickHandler={handleFilterDialogButtonOnClick} disabled={isSubmitting} />
|
||||
:
|
||||
<QSaveButton label="Save" onClickHandler={handleFilterDialogButtonOnClick} disabled={isSaveButtonDisabled()}/>
|
||||
<QSaveButton label="Save" onClickHandler={handleFilterDialogButtonOnClick} disabled={isSaveButtonDisabled()} />
|
||||
}
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
153
src/qqq/components/query/AdvancedQueryPreview.tsx
Normal file
153
src/qqq/components/query/AdvancedQueryPreview.tsx
Normal file
@ -0,0 +1,153 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import {QQueryFilter} from "@kingsrook/qqq-frontend-core/lib/model/query/QQueryFilter";
|
||||
import Box from "@mui/material/Box";
|
||||
import colors from "qqq/assets/theme/base/colors";
|
||||
import {validateCriteria} from "qqq/components/query/FilterCriteriaRow";
|
||||
import XIcon from "qqq/components/query/XIcon";
|
||||
import FilterUtils from "qqq/utils/qqq/FilterUtils";
|
||||
import React, {useState} from "react";
|
||||
|
||||
interface AdvancedQueryPreviewProps
|
||||
{
|
||||
tableMetaData: QTableMetaData;
|
||||
queryFilter: QQueryFilter;
|
||||
isEditable: boolean;
|
||||
isQueryTooComplex: boolean;
|
||||
removeCriteriaByIndexCallback: (index: number) => void;
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** Box shown on query screen (and more??) to preview what a query looks like,
|
||||
** as an "advanced" style/precursor-to-writing-your-own-query thing.
|
||||
*******************************************************************************/
|
||||
export default function AdvancedQueryPreview({tableMetaData, queryFilter, isEditable, isQueryTooComplex, removeCriteriaByIndexCallback}: AdvancedQueryPreviewProps): JSX.Element
|
||||
{
|
||||
const [mouseOverElement, setMouseOverElement] = useState(null as string);
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function handleMouseOverElement(name: string)
|
||||
{
|
||||
setMouseOverElement(name);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function handleMouseOutElement()
|
||||
{
|
||||
setMouseOverElement(null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** format the current query as a string for showing on-screen as a preview.
|
||||
*******************************************************************************/
|
||||
const queryToAdvancedString = (thisQueryFilter: QQueryFilter) =>
|
||||
{
|
||||
if (queryFilter == null || !queryFilter.criteria)
|
||||
{
|
||||
return (<span></span>);
|
||||
}
|
||||
|
||||
let counter = 0;
|
||||
|
||||
return (
|
||||
<React.Fragment>
|
||||
{thisQueryFilter.criteria?.map((criteria, i) =>
|
||||
{
|
||||
const {criteriaIsValid} = validateCriteria(criteria, null);
|
||||
if (criteriaIsValid)
|
||||
{
|
||||
counter++;
|
||||
return (
|
||||
<span key={i} style={{marginBottom: "0.125rem"}} onMouseOver={() => handleMouseOverElement(`queryPreview-${i}`)} onMouseOut={() => handleMouseOutElement()}>
|
||||
{counter > 1 ? <span style={{marginLeft: "0.25rem", marginRight: "0.25rem"}}>{thisQueryFilter.booleanOperator} </span> : <span />}
|
||||
{FilterUtils.criteriaToHumanString(tableMetaData, criteria, true)}
|
||||
{isEditable && !isQueryTooComplex && (
|
||||
mouseOverElement == `queryPreview-${i}` && <span className={`advancedQueryPreviewX-${counter - 1}`}>
|
||||
<XIcon position="forAdvancedQueryPreview" onClick={() => removeCriteriaByIndexCallback(i)} /></span>
|
||||
)}
|
||||
{counter > 1 && i == thisQueryFilter.criteria?.length - 1 && thisQueryFilter.subFilters?.length > 0 ? <span style={{marginLeft: "0.25rem", marginRight: "0.25rem"}}>{thisQueryFilter.booleanOperator} </span> : <span />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
return (<span />);
|
||||
}
|
||||
})}
|
||||
|
||||
{thisQueryFilter.subFilters?.length > 0 && (thisQueryFilter.subFilters.map((filter: QQueryFilter, j) =>
|
||||
{
|
||||
return (
|
||||
<React.Fragment key={j}>
|
||||
{j > 0 ? <span style={{marginLeft: "0.25rem", marginRight: "0.25rem"}}>{thisQueryFilter.booleanOperator} </span> : <span></span>}
|
||||
<span style={{display: "flex", marginRight: "0.20rem"}}>(</span>
|
||||
{queryToAdvancedString(filter)}
|
||||
<span style={{display: "flex", marginRight: "0.20rem"}}>)</span>
|
||||
</React.Fragment>
|
||||
);
|
||||
}))}
|
||||
</React.Fragment>
|
||||
);
|
||||
};
|
||||
|
||||
const moreSX = isEditable ?
|
||||
{
|
||||
borderTop: `1px solid ${colors.grayLines.main}`,
|
||||
boxShadow: "inset 0px 0px 4px 2px #EFEFED",
|
||||
borderRadius: "0 0 0.75rem 0.75rem",
|
||||
} :
|
||||
{
|
||||
borderRadius: "0.75rem",
|
||||
border: `1px solid ${colors.grayLines.main}`,
|
||||
}
|
||||
|
||||
return (
|
||||
<Box whiteSpace="nowrap" display="flex" flexShrink={1} flexGrow={1} alignItems="center">
|
||||
{
|
||||
<Box
|
||||
className="advancedQueryString"
|
||||
display="inline-block"
|
||||
width="100%"
|
||||
sx={{fontSize: "1rem", background: "#FFFFFF"}}
|
||||
minHeight={"2.5rem"}
|
||||
p={"0.5rem"}
|
||||
pb={"0.125rem"}
|
||||
{...moreSX}
|
||||
>
|
||||
<Box display="flex" flexWrap="wrap" fontSize="0.875rem">
|
||||
{queryToAdvancedString(queryFilter)}
|
||||
</Box>
|
||||
</Box>
|
||||
}
|
||||
</Box>
|
||||
)
|
||||
}
|
66
src/qqq/components/query/AssignFilterVariable.tsx
Normal file
66
src/qqq/components/query/AssignFilterVariable.tsx
Normal file
@ -0,0 +1,66 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2023. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData";
|
||||
import {FilterVariableExpression} from "@kingsrook/qqq-frontend-core/lib/model/query/FilterVariableExpression";
|
||||
import Box from "@mui/material/Box";
|
||||
import Icon from "@mui/material/Icon";
|
||||
import Tooltip from "@mui/material/Tooltip";
|
||||
import CriteriaDateField from "qqq/components/query/CriteriaDateField";
|
||||
import React, {SyntheticEvent, useState} from "react";
|
||||
|
||||
|
||||
export type Expression = FilterVariableExpression;
|
||||
|
||||
|
||||
interface AssignFilterButtonProps
|
||||
{
|
||||
valueIndex: number;
|
||||
field: QFieldMetaData;
|
||||
valueChangeHandler: (event: React.ChangeEvent | SyntheticEvent, valueIndex?: number | "all", newValue?: any) => void;
|
||||
}
|
||||
|
||||
CriteriaDateField.defaultProps = {
|
||||
valueIndex: 0,
|
||||
label: "Value",
|
||||
idPrefix: "value-"
|
||||
};
|
||||
|
||||
export default function AssignFilterVariable({valueIndex, field, valueChangeHandler}: AssignFilterButtonProps): JSX.Element
|
||||
{
|
||||
const [isValueAVariable, setIsValueAVariable] = useState(false);
|
||||
|
||||
const handleVariableButtonOnClick = () =>
|
||||
{
|
||||
setIsValueAVariable(!isValueAVariable);
|
||||
const expression = new FilterVariableExpression({fieldName: field.name, valueIndex: valueIndex});
|
||||
valueChangeHandler(null, valueIndex, expression);
|
||||
};
|
||||
|
||||
return <Box display="flex" alignItems="flex-end">
|
||||
<Box>
|
||||
<Tooltip title={`Use a variable as the value for the ${field.label} field`} placement="bottom">
|
||||
<Icon fontSize="small" color="info" sx={{mx: 0.25, cursor: "pointer", position: "relative", top: "2px"}} onClick={handleVariableButtonOnClick}>functions</Icon>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
</Box>;
|
||||
}
|
||||
|
@ -44,11 +44,13 @@ import {GridApiPro} from "@mui/x-data-grid-pro/models/gridApiPro";
|
||||
import QContext from "QContext";
|
||||
import colors from "qqq/assets/theme/base/colors";
|
||||
import {QCancelButton, QSaveButton} from "qqq/components/buttons/DefaultButtons";
|
||||
import AdvancedQueryPreview from "qqq/components/query/AdvancedQueryPreview";
|
||||
import {QFilterCriteriaWithId} from "qqq/components/query/CustomFilterPanel";
|
||||
import FieldListMenu from "qqq/components/query/FieldListMenu";
|
||||
import {validateCriteria} from "qqq/components/query/FilterCriteriaRow";
|
||||
import QuickFilter, {quickFilterButtonStyles} from "qqq/components/query/QuickFilter";
|
||||
import XIcon from "qqq/components/query/XIcon";
|
||||
import {QueryScreenUsage} from "qqq/pages/records/query/RecordQuery";
|
||||
import FilterUtils from "qqq/utils/qqq/FilterUtils";
|
||||
import TableUtils from "qqq/utils/qqq/TableUtils";
|
||||
import React, {forwardRef, useContext, useImperativeHandle, useReducer, useState} from "react";
|
||||
@ -75,12 +77,34 @@ interface BasicAndAdvancedQueryControlsProps
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////
|
||||
queryFilterJSON: string;
|
||||
|
||||
queryScreenUsage: QueryScreenUsage;
|
||||
|
||||
mode: string;
|
||||
setMode: (mode: string) => void;
|
||||
}
|
||||
|
||||
let debounceTimeout: string | number | NodeJS.Timeout;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** function to generate an element that says how a filter is sorted.
|
||||
*******************************************************************************/
|
||||
export function getCurrentSortIndicator(queryFilter: QQueryFilter, tableMetaData: QTableMetaData, toggleSortDirection: (event: React.MouseEvent<HTMLSpanElement, MouseEvent>) => void)
|
||||
{
|
||||
if (queryFilter && queryFilter.orderBys && queryFilter.orderBys.length > 0)
|
||||
{
|
||||
const orderBy = queryFilter.orderBys[0];
|
||||
const orderByFieldName = orderBy.fieldName;
|
||||
const [field, fieldTable] = TableUtils.getFieldAndTable(tableMetaData, orderByFieldName);
|
||||
const fieldLabel = fieldTable.name == tableMetaData.name ? field.label : `${fieldTable.label}: ${field.label}`;
|
||||
return <>Sort: {fieldLabel} <Icon onClick={toggleSortDirection} sx={{ml: "0.5rem"}}>{orderBy.isAscending ? "arrow_upward" : "arrow_downward"}</Icon></>;
|
||||
}
|
||||
else
|
||||
{
|
||||
return <>Sort...</>;
|
||||
}
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** Component to provide the basic & advanced query-filter controls for the
|
||||
** RecordQueryOrig screen.
|
||||
@ -90,7 +114,7 @@ let debounceTimeout: string | number | NodeJS.Timeout;
|
||||
*******************************************************************************/
|
||||
const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryControlsProps, ref) =>
|
||||
{
|
||||
const {metaData, tableMetaData, savedViewsComponent, columnMenuComponent, quickFilterFieldNames, setQuickFilterFieldNames, setQueryFilter, queryFilter, gridApiRef, queryFilterJSON, mode, setMode} = props;
|
||||
const {metaData, tableMetaData, savedViewsComponent, columnMenuComponent, quickFilterFieldNames, setQuickFilterFieldNames, setQueryFilter, queryFilter, gridApiRef, queryFilterJSON, mode, setMode, queryScreenUsage} = props;
|
||||
|
||||
/////////////////////
|
||||
// state variables //
|
||||
@ -397,60 +421,6 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** format the current query as a string for showing on-screen as a preview.
|
||||
*******************************************************************************/
|
||||
const queryToAdvancedString = (thisQueryFilter: QQueryFilter) =>
|
||||
{
|
||||
if (queryFilter == null || !queryFilter.criteria)
|
||||
{
|
||||
return (<span></span>);
|
||||
}
|
||||
|
||||
let counter = 0;
|
||||
|
||||
return (
|
||||
<React.Fragment>
|
||||
{thisQueryFilter.criteria?.map((criteria, i) =>
|
||||
{
|
||||
const {criteriaIsValid} = validateCriteria(criteria, null);
|
||||
if (criteriaIsValid)
|
||||
{
|
||||
counter++;
|
||||
return (
|
||||
<span key={i} style={{marginBottom: "0.125rem"}} onMouseOver={() => handleMouseOverElement(`queryPreview-${i}`)} onMouseOut={() => handleMouseOutElement()}>
|
||||
{counter > 1 ? <span style={{marginLeft: "0.25rem", marginRight: "0.25rem"}}>{thisQueryFilter.booleanOperator} </span> : <span />}
|
||||
{FilterUtils.criteriaToHumanString(tableMetaData, criteria, true)}
|
||||
{!isQueryTooComplex && (
|
||||
mouseOverElement == `queryPreview-${i}` && <span className={`advancedQueryPreviewX-${counter - 1}`}>
|
||||
<XIcon position="forAdvancedQueryPreview" onClick={() => removeCriteriaByIndex(i)} /></span>
|
||||
)}
|
||||
{counter > 1 && i == thisQueryFilter.criteria?.length - 1 && thisQueryFilter.subFilters?.length > 0 ? <span style={{marginLeft: "0.25rem", marginRight: "0.25rem"}}>{thisQueryFilter.booleanOperator} </span> : <span />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
return (<span />);
|
||||
}
|
||||
})}
|
||||
|
||||
{thisQueryFilter.subFilters?.length > 0 && (thisQueryFilter.subFilters.map((filter: QQueryFilter, j) =>
|
||||
{
|
||||
return (
|
||||
<React.Fragment key={j}>
|
||||
{j > 0 ? <span style={{marginLeft: "0.25rem", marginRight: "0.25rem"}}>{thisQueryFilter.booleanOperator} </span> : <span></span>}
|
||||
<span style={{display: "flex", marginRight: "0.20rem"}}>(</span>
|
||||
{queryToAdvancedString(filter)}
|
||||
<span style={{display: "flex", marginRight: "0.20rem"}}>)</span>
|
||||
</React.Fragment>
|
||||
);
|
||||
}))}
|
||||
</React.Fragment>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** event handler for toggling between modes - basic & advanced.
|
||||
*******************************************************************************/
|
||||
@ -608,15 +578,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
|
||||
/////////////////////////////////
|
||||
// set up the sort menu button //
|
||||
/////////////////////////////////
|
||||
let sortButtonContents = <>Sort...</>;
|
||||
if (queryFilter && queryFilter.orderBys && queryFilter.orderBys.length > 0)
|
||||
{
|
||||
const orderBy = queryFilter.orderBys[0];
|
||||
const orderByFieldName = orderBy.fieldName;
|
||||
const [field, fieldTable] = TableUtils.getFieldAndTable(tableMetaData, orderByFieldName);
|
||||
const fieldLabel = fieldTable.name == tableMetaData.name ? field.label : `${fieldTable.label}: ${field.label}`;
|
||||
sortButtonContents = <>Sort: {fieldLabel} <Icon onClick={toggleSortDirection} sx={{ml: "0.5rem"}}>{orderBy.isAscending ? "arrow_upward" : "arrow_downward"}</Icon></>;
|
||||
}
|
||||
let sortButtonContents = getCurrentSortIndicator(queryFilter, tableMetaData, toggleSortDirection);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// this is being used as a version of like forcing that we get re-rendered if the query filter changes... //
|
||||
@ -720,6 +682,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
|
||||
criteriaParam={getQuickCriteriaParam(fieldName)}
|
||||
fieldMetaData={field}
|
||||
defaultOperator={defaultOperator}
|
||||
queryScreenUsage={queryScreenUsage}
|
||||
handleRemoveQuickFilterField={null} />);
|
||||
})
|
||||
}
|
||||
@ -739,6 +702,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
|
||||
criteriaParam={getQuickCriteriaParam(fieldName)}
|
||||
fieldMetaData={field}
|
||||
defaultOperator={defaultOperator}
|
||||
queryScreenUsage={queryScreenUsage}
|
||||
handleRemoveQuickFilterField={handleRemoveQuickFilterField} />);
|
||||
})
|
||||
}
|
||||
@ -807,26 +771,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
|
||||
{sortMenuComponent}
|
||||
</Box>
|
||||
</Box>
|
||||
<Box whiteSpace="nowrap" display="flex" flexShrink={1} flexGrow={1} alignItems="center">
|
||||
{
|
||||
<Box
|
||||
className="advancedQueryString"
|
||||
display="inline-block"
|
||||
borderTop={`1px solid ${borderGray}`}
|
||||
borderRadius="0 0 0.75rem 0.75rem"
|
||||
width="100%"
|
||||
sx={{fontSize: "1rem", background: "#FFFFFF"}}
|
||||
minHeight={"2.375rem"}
|
||||
p={"0.5rem"}
|
||||
pb={"0.125rem"}
|
||||
boxShadow={"inset 0px 0px 4px 2px #EFEFED"}
|
||||
>
|
||||
<Box display="flex" flexWrap="wrap" fontSize="0.875rem">
|
||||
{queryToAdvancedString(queryFilter)}
|
||||
</Box>
|
||||
</Box>
|
||||
}
|
||||
</Box>
|
||||
<AdvancedQueryPreview tableMetaData={tableMetaData} queryFilter={queryFilter} isEditable={true} isQueryTooComplex={isQueryTooComplex} removeCriteriaByIndexCallback={removeCriteriaByIndex} />
|
||||
</Box>
|
||||
}
|
||||
</Box>
|
||||
|
@ -21,6 +21,7 @@
|
||||
|
||||
import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData";
|
||||
import {QFieldType} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldType";
|
||||
import {FilterVariableExpression} from "@kingsrook/qqq-frontend-core/lib/model/query/FilterVariableExpression";
|
||||
import {NowExpression} from "@kingsrook/qqq-frontend-core/lib/model/query/NowExpression";
|
||||
import {NowWithOffsetExpression, NowWithOffsetOperator, NowWithOffsetUnit} from "@kingsrook/qqq-frontend-core/lib/model/query/NowWithOffsetExpression";
|
||||
import {ThisOrLastPeriodExpression, ThisOrLastPeriodOperator, ThisOrLastPeriodUnit} from "@kingsrook/qqq-frontend-core/lib/model/query/ThisOrLastPeriodExpression";
|
||||
@ -34,14 +35,14 @@ import MenuItem from "@mui/material/MenuItem";
|
||||
import {styled} from "@mui/material/styles";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import Tooltip, {tooltipClasses, TooltipProps} from "@mui/material/Tooltip";
|
||||
import React, {SyntheticEvent, useEffect, useReducer, useState} from "react";
|
||||
import AdvancedDateTimeFilterValues from "qqq/components/query/AdvancedDateTimeFilterValues";
|
||||
import {QFilterCriteriaWithId} from "qqq/components/query/CustomFilterPanel";
|
||||
import {EvaluatedExpression} from "qqq/components/query/EvaluatedExpression";
|
||||
import {makeTextField} from "qqq/components/query/FilterCriteriaRowValues";
|
||||
import React, {SyntheticEvent, useReducer, useState} from "react";
|
||||
|
||||
|
||||
export type Expression = NowWithOffsetExpression | ThisOrLastPeriodExpression | NowExpression;
|
||||
export type Expression = NowWithOffsetExpression | ThisOrLastPeriodExpression | NowExpression | FilterVariableExpression;
|
||||
|
||||
|
||||
interface CriteriaDateFieldProps
|
||||
@ -52,6 +53,7 @@ interface CriteriaDateFieldProps
|
||||
field: QFieldMetaData;
|
||||
criteria: QFilterCriteriaWithId;
|
||||
valueChangeHandler: (event: React.ChangeEvent | SyntheticEvent, valueIndex?: number | "all", newValue?: any) => void;
|
||||
allowVariables?: boolean;
|
||||
}
|
||||
|
||||
CriteriaDateField.defaultProps = {
|
||||
@ -60,19 +62,30 @@ CriteriaDateField.defaultProps = {
|
||||
idPrefix: "value-"
|
||||
};
|
||||
|
||||
export default function CriteriaDateField({valueIndex, label, idPrefix, field, criteria, valueChangeHandler}: CriteriaDateFieldProps): JSX.Element
|
||||
export const NoWrapTooltip = styled(({className, children, ...props}: TooltipProps) => (
|
||||
<Tooltip {...props} classes={{popper: className}}>{children}</Tooltip>
|
||||
))({
|
||||
[`& .${tooltipClasses.tooltip}`]: {
|
||||
whiteSpace: "nowrap"
|
||||
},
|
||||
});
|
||||
|
||||
export default function CriteriaDateField({valueIndex, label, idPrefix, field, criteria, valueChangeHandler, allowVariables}: CriteriaDateFieldProps): JSX.Element
|
||||
{
|
||||
const [relativeDateTimeOpen, setRelativeDateTimeOpen] = useState(false);
|
||||
const [relativeDateTimeMenuAnchorElement, setRelativeDateTimeMenuAnchorElement] = useState(null);
|
||||
const [forceAdvancedDateTimeDialogOpen, setForceAdvancedDateTimeDialogOpen] = useState(false)
|
||||
const [forceAdvancedDateTimeDialogOpen, setForceAdvancedDateTimeDialogOpen] = useState(false);
|
||||
const [, forceUpdate] = useReducer((x) => x + 1, 0);
|
||||
|
||||
const openRelativeDateTimeMenu = (event: React.MouseEvent<HTMLElement>) =>
|
||||
{
|
||||
setRelativeDateTimeOpen(true);
|
||||
setRelativeDateTimeMenuAnchorElement(event.currentTarget);
|
||||
};
|
||||
|
||||
const closeRelativeDateTimeMenu = () =>
|
||||
{
|
||||
setRelativeDateTimeOpen(false);
|
||||
setRelativeDateTimeMenuAnchorElement(null);
|
||||
};
|
||||
|
||||
@ -137,20 +150,12 @@ export default function CriteriaDateField({valueIndex, label, idPrefix, field, c
|
||||
const isExpression = criteria.values && criteria.values[valueIndex] && criteria.values[valueIndex].type;
|
||||
const currentExpression = isExpression ? criteria.values[valueIndex] : null;
|
||||
|
||||
const NoWrapTooltip = styled(({className, children, ...props}: TooltipProps) => (
|
||||
<Tooltip {...props} classes={{popper: className}}>{children}</Tooltip>
|
||||
))({
|
||||
[`& .${tooltipClasses.tooltip}`]: {
|
||||
whiteSpace: "nowrap"
|
||||
},
|
||||
});
|
||||
|
||||
const tooltipMenuItemFromExpression = (valueIndex: number, tooltipPlacement: "left" | "right", expression: Expression) =>
|
||||
{
|
||||
let startOfPrefix = "";
|
||||
if(expression.type == "ThisOrLastPeriod")
|
||||
if (expression.type == "ThisOrLastPeriod")
|
||||
{
|
||||
if(field.type == QFieldType.DATE_TIME || expression.timeUnit != "DAYS")
|
||||
if (field.type == QFieldType.DATE_TIME || expression.timeUnit != "DAYS")
|
||||
{
|
||||
startOfPrefix = "start of ";
|
||||
}
|
||||
@ -191,84 +196,120 @@ export default function CriteriaDateField({valueIndex, label, idPrefix, field, c
|
||||
setTimeout(() => setForceAdvancedDateTimeDialogOpen(false), 100);
|
||||
}
|
||||
|
||||
const makeFilterVariableTextField = (expression: FilterVariableExpression, valueIndex: number = 0, label = "Value", idPrefix = "value-") =>
|
||||
{
|
||||
const clearValue = (event: React.MouseEvent<HTMLAnchorElement> | React.MouseEvent<HTMLButtonElement>, index: number) =>
|
||||
{
|
||||
valueChangeHandler(event, index, "");
|
||||
document.getElementById(`${idPrefix}${criteria.id}`).focus();
|
||||
};
|
||||
|
||||
const inputProps2: any = {};
|
||||
inputProps2.endAdornment = (
|
||||
<InputAdornment position="end">
|
||||
<IconButton sx={{visibility: expression ? "visible" : "hidden"}} onClick={(event) => clearValue(event, valueIndex)}>
|
||||
<Icon>closer</Icon>
|
||||
</IconButton>
|
||||
</InputAdornment>
|
||||
);
|
||||
|
||||
return <NoWrapTooltip title={<EvaluatedExpression field={field} expression={expression} />} placement="bottom" enterDelay={1000} sx={{marginLeft: "-75px !important", marginTop: "-8px !important"}}><TextField
|
||||
id={`${idPrefix}${criteria.id}`}
|
||||
label={label}
|
||||
variant="standard"
|
||||
autoComplete="off"
|
||||
InputProps={{disabled: true, readOnly: true, unselectable: "off", ...inputProps2}}
|
||||
InputLabelProps={{shrink: true}}
|
||||
value="${VARIABLE}"
|
||||
fullWidth
|
||||
/></NoWrapTooltip>;
|
||||
};
|
||||
|
||||
|
||||
return <Box display="flex" alignItems="flex-end">
|
||||
{
|
||||
isExpression ? makeDateTimeExpressionTextField(criteria.values[valueIndex], valueIndex, label, idPrefix)
|
||||
: makeTextField(field, criteria, valueChangeHandler, valueIndex, label, idPrefix)
|
||||
isExpression ?
|
||||
currentExpression?.type == "FilterVariableExpression" ? (
|
||||
makeFilterVariableTextField(criteria.values[valueIndex], valueIndex, label, idPrefix)
|
||||
) : (
|
||||
makeDateTimeExpressionTextField(criteria.values[valueIndex], valueIndex, label, idPrefix)
|
||||
)
|
||||
: makeTextField(field, criteria, valueChangeHandler, valueIndex, label, idPrefix, allowVariables)
|
||||
}
|
||||
<Box>
|
||||
<Tooltip title={`Choose a common relative ${field.type == QFieldType.DATE ? "date" : "date-time"} expression`} placement="bottom">
|
||||
<Icon fontSize="small" color="info" sx={{mx: 0.25, cursor: "pointer", position: "relative", top: "2px"}} onClick={openRelativeDateTimeMenu}>date_range</Icon>
|
||||
</Tooltip>
|
||||
<Menu
|
||||
open={relativeDateTimeMenuAnchorElement}
|
||||
anchorEl={relativeDateTimeMenuAnchorElement}
|
||||
transformOrigin={{horizontal: "left", vertical: "top"}}
|
||||
onClose={closeRelativeDateTimeMenu}
|
||||
>
|
||||
{
|
||||
field.type == QFieldType.DATE ?
|
||||
<Box display="flex">
|
||||
<Box>
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 7, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 14, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 30, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 90, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 180, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 1, "YEARS"))}
|
||||
<Divider />
|
||||
<Tooltip title="Define a custom expression" placement="left">
|
||||
<MenuItem onClick={doForceAdvancedDateTimeDialogOpen}>Custom</MenuItem>
|
||||
</Tooltip>
|
||||
{
|
||||
(!isExpression || currentExpression?.type != "FilterVariableExpression") && (
|
||||
<><Box>
|
||||
<Tooltip title={`Choose a common relative ${field.type == QFieldType.DATE ? "date" : "date-time"} expression`} placement="bottom">
|
||||
<Icon fontSize="small" color="info" sx={{mx: 0.25, cursor: "pointer", position: "relative", top: "2px"}} onClick={openRelativeDateTimeMenu}>date_range</Icon>
|
||||
</Tooltip>
|
||||
<Menu
|
||||
open={relativeDateTimeOpen}
|
||||
anchorEl={relativeDateTimeMenuAnchorElement}
|
||||
transformOrigin={{horizontal: "left", vertical: "top"}}
|
||||
onClose={closeRelativeDateTimeMenu}
|
||||
>
|
||||
{field.type == QFieldType.DATE ?
|
||||
<Box display="flex">
|
||||
<Box>
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 7, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 14, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 30, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 90, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 180, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 1, "YEARS"))}
|
||||
<Divider />
|
||||
<Tooltip title="Define a custom expression" placement="left">
|
||||
<MenuItem onClick={doForceAdvancedDateTimeDialogOpen}>Custom</MenuItem>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
<Box>
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "WEEKS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "WEEKS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "MONTHS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "MONTHS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "YEARS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "YEARS"))}
|
||||
</Box>
|
||||
</Box>
|
||||
<Box>
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "WEEKS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "WEEKS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "MONTHS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "MONTHS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "YEARS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "YEARS"))}
|
||||
</Box>
|
||||
</Box>
|
||||
:
|
||||
<Box display="flex">
|
||||
<Box>
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 1, "HOURS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 12, "HOURS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 24, "HOURS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 7, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 14, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 30, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 90, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 180, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 1, "YEARS"))}
|
||||
<Divider />
|
||||
<Tooltip title="Define a custom expression" placement="left">
|
||||
<MenuItem onClick={doForceAdvancedDateTimeDialogOpen}>Custom</MenuItem>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
<Box>
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newNowExpression())}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "HOURS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "HOURS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "WEEKS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "WEEKS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "MONTHS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "MONTHS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "YEARS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "YEARS"))}
|
||||
</Box>
|
||||
</Box>
|
||||
}
|
||||
</Menu>
|
||||
</Box>
|
||||
<Box>
|
||||
<AdvancedDateTimeFilterValues type={field.type} expression={currentExpression} onSave={(expression: any) => saveNewDateTimeExpression(valueIndex, expression)} forcedOpen={forceAdvancedDateTimeDialogOpen} />
|
||||
</Box>
|
||||
:
|
||||
<Box display="flex">
|
||||
<Box>
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 1, "HOURS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 12, "HOURS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 24, "HOURS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 7, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 14, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 30, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 90, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 180, "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "left", newNowWithOffsetExpression("MINUS", 1, "YEARS"))}
|
||||
<Divider />
|
||||
<Tooltip title="Define a custom expression" placement="left">
|
||||
<MenuItem onClick={doForceAdvancedDateTimeDialogOpen}>Custom</MenuItem>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
<Box>
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newNowExpression())}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "HOURS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "HOURS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "DAYS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "WEEKS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "WEEKS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "MONTHS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "MONTHS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("THIS", "YEARS"))}
|
||||
{tooltipMenuItemFromExpression(valueIndex, "right", newThisOrLastPeriodExpression("LAST", "YEARS"))}
|
||||
</Box>
|
||||
</Box>}
|
||||
</Menu>
|
||||
</Box><Box>
|
||||
<AdvancedDateTimeFilterValues type={field.type} expression={currentExpression} onSave={(expression: any) => saveNewDateTimeExpression(valueIndex, expression)} forcedOpen={forceAdvancedDateTimeDialogOpen} />
|
||||
</Box></>
|
||||
)
|
||||
}
|
||||
</Box>;
|
||||
}
|
||||
|
||||
|
@ -21,7 +21,9 @@
|
||||
|
||||
import {QInstance} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QInstance";
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import {Box, FormControlLabel, FormGroup} from "@mui/material";
|
||||
|
||||
import {FormControlLabel, FormGroup} from "@mui/material";
|
||||
import Box from "@mui/material/Box";
|
||||
import Button from "@mui/material/Button";
|
||||
import Icon from "@mui/material/Icon";
|
||||
import IconButton from "@mui/material/IconButton";
|
||||
@ -56,7 +58,7 @@ export const CustomColumnsPanel = forwardRef<any, GridColumnsPanelProps>(
|
||||
const someRef = createRef();
|
||||
|
||||
const textRef = useRef(null);
|
||||
const [didInitialFocus, setDidInitialFocus] = useState(false)
|
||||
const [didInitialFocus, setDidInitialFocus] = useState(false);
|
||||
|
||||
const [openGroups, setOpenGroups] = useState(props.initialOpenedGroups || {});
|
||||
const openGroupsBecauseOfFilter = {} as { [name: string]: boolean };
|
||||
@ -71,9 +73,9 @@ export const CustomColumnsPanel = forwardRef<any, GridColumnsPanelProps>(
|
||||
|
||||
console.log(`Open groups: ${JSON.stringify(openGroups)}`);
|
||||
|
||||
if(!didInitialFocus)
|
||||
if (!didInitialFocus)
|
||||
{
|
||||
if(textRef.current)
|
||||
if (textRef.current)
|
||||
{
|
||||
textRef.current.select();
|
||||
setDidInitialFocus(true);
|
||||
@ -189,11 +191,11 @@ export const CustomColumnsPanel = forwardRef<any, GridColumnsPanelProps>(
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// always sort columns by label. note, in future may offer different sorts - here's where to do it. //
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
const sortedColumns = [... columns];
|
||||
const sortedColumns = [...columns];
|
||||
sortedColumns.sort((a, b): number =>
|
||||
{
|
||||
return a.headerName.localeCompare(b.headerName);
|
||||
})
|
||||
});
|
||||
|
||||
for (let i = 0; i < sortedColumns.length; i++)
|
||||
{
|
||||
@ -361,7 +363,7 @@ export const CustomColumnsPanel = forwardRef<any, GridColumnsPanelProps>(
|
||||
const changeFilterText = (newValue: string) =>
|
||||
{
|
||||
setFilterText(newValue);
|
||||
props.filterTextChanger(newValue)
|
||||
props.filterTextChanger(newValue);
|
||||
};
|
||||
|
||||
const filterTextChanged = (event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) =>
|
||||
|
@ -28,8 +28,8 @@ import Box from "@mui/material/Box";
|
||||
import Button from "@mui/material/Button/Button";
|
||||
import Icon from "@mui/material/Icon/Icon";
|
||||
import {GridFilterPanelProps, GridSlotsComponentsProps} from "@mui/x-data-grid-pro";
|
||||
import React, {forwardRef, useReducer} from "react";
|
||||
import {FilterCriteriaRow, getDefaultCriteriaValue} from "qqq/components/query/FilterCriteriaRow";
|
||||
import React, {forwardRef, useReducer} from "react";
|
||||
|
||||
|
||||
declare module "@mui/x-data-grid"
|
||||
@ -49,7 +49,7 @@ declare module "@mui/x-data-grid"
|
||||
|
||||
export class QFilterCriteriaWithId extends QFilterCriteria
|
||||
{
|
||||
id: number
|
||||
id: number;
|
||||
}
|
||||
|
||||
|
||||
@ -62,6 +62,7 @@ export const CustomFilterPanel = forwardRef<any, GridFilterPanelProps>(
|
||||
const [, forceUpdate] = useReducer((x) => x + 1, 0);
|
||||
|
||||
const queryFilter = props.queryFilter;
|
||||
|
||||
// console.log(`CustomFilterPanel: filter: ${JSON.stringify(queryFilter)}`);
|
||||
|
||||
function focusLastField()
|
||||
@ -124,7 +125,7 @@ export const CustomFilterPanel = forwardRef<any, GridFilterPanelProps>(
|
||||
}
|
||||
}
|
||||
|
||||
if(queryFilter.criteria.length == 1 && !queryFilter.criteria[0].fieldName)
|
||||
if (queryFilter.criteria.length == 1 && !queryFilter.criteria[0].fieldName)
|
||||
{
|
||||
focusLastField();
|
||||
}
|
||||
@ -142,7 +143,7 @@ export const CustomFilterPanel = forwardRef<any, GridFilterPanelProps>(
|
||||
{
|
||||
queryFilter.criteria[index] = newCriteria;
|
||||
|
||||
clearTimeout(debounceTimeout)
|
||||
clearTimeout(debounceTimeout);
|
||||
debounceTimeout = setTimeout(() => props.updateFilter(queryFilter), needDebounce ? 500 : 1);
|
||||
|
||||
forceUpdate();
|
||||
@ -178,6 +179,7 @@ export const CustomFilterPanel = forwardRef<any, GridFilterPanelProps>(
|
||||
updateCriteria={(newCriteria, needDebounce) => updateCriteria(newCriteria, index, needDebounce)}
|
||||
removeCriteria={() => removeCriteria(index)}
|
||||
updateBooleanOperator={(newValue) => updateBooleanOperator(newValue)}
|
||||
queryScreenUsage={props.queryScreenUsage}
|
||||
/>
|
||||
{/*JSON.stringify(criteria)*/}
|
||||
</Box>
|
||||
|
@ -21,9 +21,9 @@
|
||||
|
||||
import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData";
|
||||
import {QFieldType} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldType";
|
||||
import React, {useEffect, useState} from "react";
|
||||
import {Expression} from "qqq/components/query/CriteriaDateField";
|
||||
import ValueUtils from "qqq/utils/qqq/ValueUtils";
|
||||
import React, {useEffect, useState} from "react";
|
||||
|
||||
/*******************************************************************************
|
||||
** Helper component to show value inside tooltips that ticks up every second.
|
||||
@ -57,6 +57,11 @@ const HOUR_MS = 60 * 60 * 1000;
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
const evaluateExpression = (time: Date, field: QFieldMetaData, expression: Expression): string =>
|
||||
{
|
||||
if (expression.type == "FilterVariableExpression")
|
||||
{
|
||||
return (expression.toString());
|
||||
}
|
||||
|
||||
let rs: Date = null;
|
||||
if (expression.type == "NowWithOffset")
|
||||
{
|
||||
|
@ -46,13 +46,13 @@ export default function ExportMenuItem(props: QExportMenuItemProps)
|
||||
|
||||
const {recordAnalytics} = useContext(QContext);
|
||||
|
||||
recordAnalytics({category: "tableEvents", action: "export", label: tableMetaData.label});
|
||||
|
||||
return (
|
||||
<MenuItem
|
||||
disabled={totalRecords === 0}
|
||||
onClick={() =>
|
||||
{
|
||||
recordAnalytics({category: "tableEvents", action: "export", label: tableMetaData.label});
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// build the list of visible fields. note, not doing them in-order (in case //
|
||||
// the user did drag & drop), because column order model isn't right yet //
|
||||
|
@ -33,10 +33,11 @@ import MenuItem from "@mui/material/MenuItem";
|
||||
import Select, {SelectChangeEvent} from "@mui/material/Select/Select";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import Tooltip from "@mui/material/Tooltip";
|
||||
import React, {ReactNode, SyntheticEvent, useState} from "react";
|
||||
import FieldAutoComplete from "qqq/components/misc/FieldAutoComplete";
|
||||
import FilterCriteriaRowValues from "qqq/components/query/FilterCriteriaRowValues";
|
||||
import {QueryScreenUsage} from "qqq/pages/records/query/RecordQuery";
|
||||
import FilterUtils from "qqq/utils/qqq/FilterUtils";
|
||||
import React, {ReactNode, SyntheticEvent, useState} from "react";
|
||||
|
||||
|
||||
export enum ValueMode
|
||||
@ -72,7 +73,7 @@ export const getValueModeRequiredCount = (valueMode: ValueMode): number =>
|
||||
case ValueMode.PVS_MULTI:
|
||||
return (null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export interface OperatorOption
|
||||
{
|
||||
@ -183,7 +184,7 @@ export const getOperatorOptions = (tableMetaData: QTableMetaData, fieldName: str
|
||||
}
|
||||
|
||||
return (operatorOptions);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
interface FilterCriteriaRowProps
|
||||
@ -197,13 +198,13 @@ interface FilterCriteriaRowProps
|
||||
updateCriteria: (newCriteria: QFilterCriteria, needDebounce: boolean) => void;
|
||||
removeCriteria: () => void;
|
||||
updateBooleanOperator: (newValue: string) => void;
|
||||
queryScreenUsage?: QueryScreenUsage;
|
||||
}
|
||||
|
||||
FilterCriteriaRow.defaultProps =
|
||||
{
|
||||
};
|
||||
{};
|
||||
|
||||
export function validateCriteria(criteria: QFilterCriteria, operatorSelectedValue?: OperatorOption): {criteriaIsValid: boolean, criteriaStatusTooltip: string}
|
||||
export function validateCriteria(criteria: QFilterCriteria, operatorSelectedValue?: OperatorOption): { criteriaIsValid: boolean, criteriaStatusTooltip: string }
|
||||
{
|
||||
let criteriaIsValid = true;
|
||||
let criteriaStatusTooltip = "This condition is fully defined and is part of your filter.";
|
||||
@ -213,7 +214,7 @@ export function validateCriteria(criteria: QFilterCriteria, operatorSelectedValu
|
||||
return (value === null || value == undefined || String(value).trim() === "");
|
||||
}
|
||||
|
||||
if(!criteria)
|
||||
if (!criteria)
|
||||
{
|
||||
criteriaIsValid = false;
|
||||
criteriaStatusTooltip = "This condition is not defined.";
|
||||
@ -266,7 +267,7 @@ export function validateCriteria(criteria: QFilterCriteria, operatorSelectedValu
|
||||
return {criteriaIsValid, criteriaStatusTooltip};
|
||||
}
|
||||
|
||||
export function FilterCriteriaRow({id, index, tableMetaData, metaData, criteria, booleanOperator, updateCriteria, removeCriteria, updateBooleanOperator}: FilterCriteriaRowProps): JSX.Element
|
||||
export function FilterCriteriaRow({id, index, tableMetaData, metaData, criteria, booleanOperator, updateCriteria, removeCriteria, updateBooleanOperator, queryScreenUsage}: FilterCriteriaRowProps): JSX.Element
|
||||
{
|
||||
// console.log(`FilterCriteriaRow: criteria: ${JSON.stringify(criteria)}`);
|
||||
const [operatorSelectedValue, setOperatorSelectedValue] = useState(null as OperatorOption);
|
||||
@ -284,7 +285,7 @@ export function FilterCriteriaRow({id, index, tableMetaData, metaData, criteria,
|
||||
let defaultFieldValue;
|
||||
let field = null;
|
||||
let fieldTable = null;
|
||||
if(criteria && criteria.fieldName)
|
||||
if (criteria && criteria.fieldName)
|
||||
{
|
||||
[field, fieldTable] = FilterUtils.getField(tableMetaData, criteria.fieldName);
|
||||
if (field && fieldTable)
|
||||
@ -303,9 +304,9 @@ export function FilterCriteriaRow({id, index, tableMetaData, metaData, criteria,
|
||||
|
||||
let newOperatorSelectedValue = operatorOptions.filter(option =>
|
||||
{
|
||||
if(option.value == criteria.operator)
|
||||
if (option.value == criteria.operator)
|
||||
{
|
||||
if(option.implicitValues)
|
||||
if (option.implicitValues)
|
||||
{
|
||||
return (JSON.stringify(option.implicitValues) == JSON.stringify(criteria.values));
|
||||
}
|
||||
@ -316,7 +317,7 @@ export function FilterCriteriaRow({id, index, tableMetaData, metaData, criteria,
|
||||
}
|
||||
return (false);
|
||||
})[0];
|
||||
if(newOperatorSelectedValue?.label !== operatorSelectedValue?.label)
|
||||
if (newOperatorSelectedValue?.label !== operatorSelectedValue?.label)
|
||||
{
|
||||
setOperatorSelectedValue(newOperatorSelectedValue);
|
||||
setOperatorInputValue(newOperatorSelectedValue?.label);
|
||||
@ -379,12 +380,12 @@ export function FilterCriteriaRow({id, index, tableMetaData, metaData, criteria,
|
||||
{
|
||||
criteria.operator = newValue ? newValue.value : null;
|
||||
|
||||
if(newValue)
|
||||
if (newValue)
|
||||
{
|
||||
setOperatorSelectedValue(newValue);
|
||||
setOperatorInputValue(newValue.label);
|
||||
|
||||
if(newValue.implicitValues)
|
||||
if (newValue.implicitValues)
|
||||
{
|
||||
criteria.values = newValue.implicitValues;
|
||||
}
|
||||
@ -393,15 +394,15 @@ export function FilterCriteriaRow({id, index, tableMetaData, metaData, criteria,
|
||||
// we've seen cases where switching operators can sometimes put a null in as the first value... //
|
||||
// that just causes a bad time (e.g., null pointers in Autocomplete), so, get rid of that. //
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
if(criteria.values && criteria.values.length == 1 && criteria.values[0] == null)
|
||||
if (criteria.values && criteria.values.length == 1 && criteria.values[0] == null)
|
||||
{
|
||||
criteria.values = [];
|
||||
}
|
||||
|
||||
if(newValue.valueMode && !newValue.implicitValues)
|
||||
if (newValue.valueMode && !newValue.implicitValues)
|
||||
{
|
||||
const requiredValueCount = getValueModeRequiredCount(newValue.valueMode);
|
||||
if(requiredValueCount != null && criteria.values.length > requiredValueCount)
|
||||
if (requiredValueCount != null && criteria.values.length > requiredValueCount)
|
||||
{
|
||||
criteria.values.splice(requiredValueCount);
|
||||
}
|
||||
@ -424,12 +425,12 @@ export function FilterCriteriaRow({id, index, tableMetaData, metaData, criteria,
|
||||
// @ts-ignore
|
||||
const value = newValue !== undefined ? newValue : event ? event.target.value : null;
|
||||
|
||||
if(!criteria.values)
|
||||
if (!criteria.values)
|
||||
{
|
||||
criteria.values = [];
|
||||
}
|
||||
|
||||
if(valueIndex == "all")
|
||||
if (valueIndex == "all")
|
||||
{
|
||||
criteria.values = value;
|
||||
}
|
||||
@ -484,7 +485,9 @@ export function FilterCriteriaRow({id, index, tableMetaData, metaData, criteria,
|
||||
: <span />}
|
||||
</Box>
|
||||
<Box display="inline-block" width={250} className="fieldColumn">
|
||||
<FieldAutoComplete id={`field-${id}`} metaData={metaData} tableMetaData={tableMetaData} defaultValue={defaultFieldValue} handleFieldChange={handleFieldChange} />
|
||||
<FieldAutoComplete id={`field-${id}`} metaData={metaData} tableMetaData={tableMetaData} defaultValue={defaultFieldValue} handleFieldChange={handleFieldChange}
|
||||
autocompleteSlotProps={{popper: {className: "filterCriteriaRowColumnPopper", style: {padding: 0, width: "250px"}}}}
|
||||
/>
|
||||
</Box>
|
||||
<Box display="inline-block" width={200} className="operatorColumn">
|
||||
<Tooltip title={criteria.fieldName == null ? "You must select a field before you can select an operator" : null} enterDelay={tooltipEnterDelay}>
|
||||
@ -512,6 +515,7 @@ export function FilterCriteriaRow({id, index, tableMetaData, metaData, criteria,
|
||||
field={field}
|
||||
table={fieldTable}
|
||||
valueChangeHandler={(event, valueIndex, newValue) => handleValueChange(event, valueIndex, newValue)}
|
||||
queryScreenUsage={queryScreenUsage}
|
||||
/>
|
||||
</Box>
|
||||
<Box display="inline-block">
|
||||
|
@ -23,19 +23,23 @@
|
||||
import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData";
|
||||
import {QFieldType} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldType";
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import {FilterVariableExpression} from "@kingsrook/qqq-frontend-core/lib/model/query/FilterVariableExpression";
|
||||
import Autocomplete from "@mui/material/Autocomplete";
|
||||
import Box from "@mui/material/Box";
|
||||
import Icon from "@mui/material/Icon";
|
||||
import IconButton from "@mui/material/IconButton";
|
||||
import InputAdornment from "@mui/material/InputAdornment/InputAdornment";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import React, {SyntheticEvent, useReducer} from "react";
|
||||
import DynamicSelect from "qqq/components/forms/DynamicSelect";
|
||||
import CriteriaDateField from "qqq/components/query/CriteriaDateField";
|
||||
import AssignFilterVariable from "qqq/components/query/AssignFilterVariable";
|
||||
import CriteriaDateField, {NoWrapTooltip} from "qqq/components/query/CriteriaDateField";
|
||||
import {QFilterCriteriaWithId} from "qqq/components/query/CustomFilterPanel";
|
||||
import {EvaluatedExpression} from "qqq/components/query/EvaluatedExpression";
|
||||
import FilterCriteriaPaster from "qqq/components/query/FilterCriteriaPaster";
|
||||
import {OperatorOption, ValueMode} from "qqq/components/query/FilterCriteriaRow";
|
||||
import {QueryScreenUsage} from "qqq/pages/records/query/RecordQuery";
|
||||
import ValueUtils from "qqq/utils/qqq/ValueUtils";
|
||||
import React, {SyntheticEvent, useReducer, useState} from "react";
|
||||
|
||||
interface Props
|
||||
{
|
||||
@ -44,7 +48,8 @@ interface Props
|
||||
field: QFieldMetaData;
|
||||
table: QTableMetaData;
|
||||
valueChangeHandler: (event: React.ChangeEvent | SyntheticEvent, valueIndex?: number | "all", newValue?: any) => void;
|
||||
initiallyOpenMultiValuePvs?: boolean
|
||||
initiallyOpenMultiValuePvs?: boolean;
|
||||
queryScreenUsage?: QueryScreenUsage;
|
||||
}
|
||||
|
||||
FilterCriteriaRowValues.defaultProps =
|
||||
@ -72,8 +77,10 @@ export const getTypeForTextField = (field: QFieldMetaData): string =>
|
||||
return (type);
|
||||
};
|
||||
|
||||
export const makeTextField = (field: QFieldMetaData, criteria: QFilterCriteriaWithId, valueChangeHandler?: (event: (React.ChangeEvent | React.SyntheticEvent), valueIndex?: (number | "all"), newValue?: any) => void, valueIndex: number = 0, label = "Value", idPrefix = "value-") =>
|
||||
export const makeTextField = (field: QFieldMetaData, criteria: QFilterCriteriaWithId, valueChangeHandler?: (event: (React.ChangeEvent | React.SyntheticEvent), valueIndex?: (number | "all"), newValue?: any) => void, valueIndex: number = 0, label = "Value", idPrefix = "value-", allowVariables = false) =>
|
||||
{
|
||||
const isExpression = criteria.values && criteria.values[valueIndex] && criteria.values[valueIndex].type;
|
||||
|
||||
let type = getTypeForTextField(field);
|
||||
const inputLabelProps: any = {};
|
||||
|
||||
@ -95,7 +102,6 @@ export const makeTextField = (field: QFieldMetaData, criteria: QFilterCriteriaWi
|
||||
};
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Event handler for key-down events - specifically added here, to stop pressing
|
||||
** 'tab' in a date or date-time from closing the quick-filter...
|
||||
@ -104,7 +110,7 @@ export const makeTextField = (field: QFieldMetaData, criteria: QFilterCriteriaWi
|
||||
{
|
||||
if (field.type == QFieldType.DATE || field.type == QFieldType.DATE_TIME)
|
||||
{
|
||||
if(e.code == "Tab")
|
||||
if (e.code == "Tab")
|
||||
{
|
||||
console.log("Tab on date or date-time - don't close me, just move to the next sub-field!...");
|
||||
e.stopPropagation();
|
||||
@ -112,6 +118,36 @@ export const makeTextField = (field: QFieldMetaData, criteria: QFilterCriteriaWi
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const makeFilterVariableTextField = (expression: FilterVariableExpression, valueIndex: number = 0, label = "Value", idPrefix = "value-") =>
|
||||
{
|
||||
const clearValue = (event: React.MouseEvent<HTMLAnchorElement> | React.MouseEvent<HTMLButtonElement>, index: number) =>
|
||||
{
|
||||
valueChangeHandler(event, index, "");
|
||||
document.getElementById(`${idPrefix}${criteria.id}`).focus();
|
||||
};
|
||||
|
||||
const inputProps2: any = {};
|
||||
inputProps2.endAdornment = (
|
||||
<InputAdornment position="end">
|
||||
<IconButton sx={{visibility: expression ? "visible" : "hidden"}} onClick={(event) => clearValue(event, valueIndex)}>
|
||||
<Icon>closer</Icon>
|
||||
</IconButton>
|
||||
</InputAdornment>
|
||||
);
|
||||
|
||||
return <NoWrapTooltip title={<EvaluatedExpression field={field} expression={expression} />} placement="bottom" enterDelay={1000} sx={{marginLeft: "-75px !important", marginTop: "-8px !important"}}><TextField
|
||||
id={`${idPrefix}${criteria.id}`}
|
||||
label={label}
|
||||
variant="standard"
|
||||
autoComplete="off"
|
||||
InputProps={{disabled: true, readOnly: true, unselectable: "off", ...inputProps2}}
|
||||
InputLabelProps={{shrink: true}}
|
||||
value="${VARIABLE}"
|
||||
fullWidth
|
||||
/></NoWrapTooltip>;
|
||||
};
|
||||
|
||||
const inputProps: any = {};
|
||||
inputProps.endAdornment = (
|
||||
<InputAdornment position="end">
|
||||
@ -121,25 +157,40 @@ export const makeTextField = (field: QFieldMetaData, criteria: QFilterCriteriaWi
|
||||
</InputAdornment>
|
||||
);
|
||||
|
||||
return <TextField
|
||||
id={`${idPrefix}${criteria.id}`}
|
||||
label={label}
|
||||
variant="standard"
|
||||
autoComplete="off"
|
||||
type={type}
|
||||
onChange={(event) => valueChangeHandler(event, valueIndex)}
|
||||
onKeyDown={handleKeyDown}
|
||||
value={value}
|
||||
InputLabelProps={inputLabelProps}
|
||||
InputProps={inputProps}
|
||||
fullWidth
|
||||
autoFocus={true}
|
||||
/>;
|
||||
return <Box sx={{margin: 0, padding: 0, display: "flex"}}>
|
||||
{
|
||||
isExpression ? (
|
||||
makeFilterVariableTextField(criteria.values[valueIndex], valueIndex, label, idPrefix)
|
||||
) : (
|
||||
<TextField
|
||||
id={`${idPrefix}${criteria.id}`}
|
||||
label={label}
|
||||
variant="standard"
|
||||
autoComplete="off"
|
||||
type={type}
|
||||
onChange={(event) => valueChangeHandler(event, valueIndex)}
|
||||
onKeyDown={handleKeyDown}
|
||||
value={value}
|
||||
InputLabelProps={inputLabelProps}
|
||||
InputProps={inputProps}
|
||||
fullWidth
|
||||
autoFocus={true}
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
allowVariables && (
|
||||
<AssignFilterVariable field={field} valueChangeHandler={valueChangeHandler} valueIndex={valueIndex} />
|
||||
)
|
||||
}
|
||||
</Box>;
|
||||
};
|
||||
|
||||
function FilterCriteriaRowValues({operatorOption, criteria, field, table, valueChangeHandler, initiallyOpenMultiValuePvs}: Props): JSX.Element
|
||||
|
||||
function FilterCriteriaRowValues({operatorOption, criteria, field, table, valueChangeHandler, initiallyOpenMultiValuePvs, queryScreenUsage}: Props): JSX.Element
|
||||
{
|
||||
const [, forceUpdate] = useReducer((x) => x + 1, 0);
|
||||
const [allowVariables, setAllowVariables] = useState(queryScreenUsage == "reportSetup");
|
||||
|
||||
if (!operatorOption)
|
||||
{
|
||||
@ -169,33 +220,35 @@ function FilterCriteriaRowValues({operatorOption, criteria, field, table, valueC
|
||||
forceUpdate();
|
||||
}
|
||||
|
||||
const isExpression = criteria.values && criteria.values[0] && criteria.values[0].type;
|
||||
|
||||
switch (operatorOption.valueMode)
|
||||
{
|
||||
case ValueMode.NONE:
|
||||
return null;
|
||||
case ValueMode.SINGLE:
|
||||
return makeTextField(field, criteria, valueChangeHandler);
|
||||
return makeTextField(field, criteria, valueChangeHandler, 0, undefined, undefined, allowVariables);
|
||||
case ValueMode.SINGLE_DATE:
|
||||
return <CriteriaDateField field={field} valueChangeHandler={valueChangeHandler} criteria={criteria} />;
|
||||
return <CriteriaDateField field={field} valueChangeHandler={valueChangeHandler} criteria={criteria} allowVariables={allowVariables} />;
|
||||
case ValueMode.DOUBLE_DATE:
|
||||
return <Box>
|
||||
<CriteriaDateField field={field} valueChangeHandler={valueChangeHandler} criteria={criteria} valueIndex={0} label="From" idPrefix="from-" />
|
||||
<CriteriaDateField field={field} valueChangeHandler={valueChangeHandler} criteria={criteria} valueIndex={1} label="To" idPrefix="to-" />
|
||||
<CriteriaDateField field={field} valueChangeHandler={valueChangeHandler} criteria={criteria} valueIndex={0} label="From" idPrefix="from-" allowVariables={allowVariables} />
|
||||
<CriteriaDateField field={field} valueChangeHandler={valueChangeHandler} criteria={criteria} valueIndex={1} label="To" idPrefix="to-" allowVariables={allowVariables} />
|
||||
</Box>;
|
||||
case ValueMode.SINGLE_DATE_TIME:
|
||||
return <CriteriaDateField field={field} valueChangeHandler={valueChangeHandler} criteria={criteria} />;
|
||||
return <CriteriaDateField field={field} valueChangeHandler={valueChangeHandler} criteria={criteria} allowVariables={allowVariables} />;
|
||||
case ValueMode.DOUBLE_DATE_TIME:
|
||||
return <Box>
|
||||
<CriteriaDateField field={field} valueChangeHandler={valueChangeHandler} criteria={criteria} valueIndex={0} label="From" idPrefix="from-" />
|
||||
<CriteriaDateField field={field} valueChangeHandler={valueChangeHandler} criteria={criteria} valueIndex={1} label="To" idPrefix="to-" />
|
||||
<CriteriaDateField field={field} valueChangeHandler={valueChangeHandler} criteria={criteria} valueIndex={0} label="From" idPrefix="from-" allowVariables={allowVariables} />
|
||||
<CriteriaDateField field={field} valueChangeHandler={valueChangeHandler} criteria={criteria} valueIndex={1} label="To" idPrefix="to-" allowVariables={allowVariables} />
|
||||
</Box>;
|
||||
case ValueMode.DOUBLE:
|
||||
return <Box>
|
||||
<Box width="50%" display="inline-block">
|
||||
{makeTextField(field, criteria, valueChangeHandler, 0, "From", "from-")}
|
||||
{makeTextField(field, criteria, valueChangeHandler, 0, "From", "from-", allowVariables)}
|
||||
</Box>
|
||||
<Box width="50%" display="inline-block">
|
||||
{makeTextField(field, criteria, valueChangeHandler, 1, "To", "to-")}
|
||||
{makeTextField(field, criteria, valueChangeHandler, 1, "To", "to-", allowVariables)}
|
||||
</Box>
|
||||
</Box>;
|
||||
case ValueMode.MULTI:
|
||||
@ -228,19 +281,30 @@ function FilterCriteriaRowValues({operatorOption, criteria, field, table, valueC
|
||||
{
|
||||
selectedPossibleValue = criteria.values[0];
|
||||
}
|
||||
return <Box mb={-1.5}>
|
||||
<DynamicSelect
|
||||
tableName={table.name}
|
||||
fieldName={field.name}
|
||||
overrideId={field.name + "-single-" + criteria.id}
|
||||
key={field.name + "-single-" + criteria.id}
|
||||
fieldLabel="Value"
|
||||
initialValue={selectedPossibleValue?.id}
|
||||
initialDisplayValue={selectedPossibleValue?.label}
|
||||
inForm={false}
|
||||
onChange={(value: any) => valueChangeHandler(null, 0, value)}
|
||||
variant="standard"
|
||||
/>
|
||||
return <Box display="flex">
|
||||
{
|
||||
isExpression ? (
|
||||
makeTextField(field, criteria, valueChangeHandler, 0, undefined, undefined, allowVariables)
|
||||
) : (
|
||||
<Box width={"100%"}>
|
||||
<DynamicSelect
|
||||
tableName={table.name}
|
||||
fieldName={field.name}
|
||||
overrideId={field.name + "-single-" + criteria.id}
|
||||
key={field.name + "-single-" + criteria.id}
|
||||
fieldLabel="Value"
|
||||
initialValue={selectedPossibleValue?.id}
|
||||
initialDisplayValue={selectedPossibleValue?.label}
|
||||
inForm={false}
|
||||
onChange={(value: any) => valueChangeHandler(null, 0, value)}
|
||||
variant="standard"
|
||||
/>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
{
|
||||
allowVariables && !isExpression && <Box mt={2.0}><AssignFilterVariable field={field} valueChangeHandler={valueChangeHandler} valueIndex={0} /></Box>
|
||||
}
|
||||
</Box>;
|
||||
case ValueMode.PVS_MULTI:
|
||||
console.log("Doing pvs multi: " + criteria.values);
|
||||
@ -276,4 +340,4 @@ function FilterCriteriaRowValues({operatorOption, criteria, field, table, valueC
|
||||
return (<br />);
|
||||
}
|
||||
|
||||
export default FilterCriteriaRowValues;
|
||||
export default FilterCriteriaRowValues;
|
||||
|
@ -30,14 +30,15 @@ import Box from "@mui/material/Box";
|
||||
import Button from "@mui/material/Button";
|
||||
import Menu from "@mui/material/Menu";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import React, {SyntheticEvent, useContext, useReducer, useState} from "react";
|
||||
import QContext from "QContext";
|
||||
import {QFilterCriteriaWithId} from "qqq/components/query/CustomFilterPanel";
|
||||
import {getDefaultCriteriaValue, getOperatorOptions, getValueModeRequiredCount, OperatorOption, validateCriteria} from "qqq/components/query/FilterCriteriaRow";
|
||||
import FilterCriteriaRowValues from "qqq/components/query/FilterCriteriaRowValues";
|
||||
import XIcon from "qqq/components/query/XIcon";
|
||||
import {QueryScreenUsage} from "qqq/pages/records/query/RecordQuery";
|
||||
import FilterUtils from "qqq/utils/qqq/FilterUtils";
|
||||
import TableUtils from "qqq/utils/qqq/TableUtils";
|
||||
import React, {SyntheticEvent, useContext, useReducer, useState} from "react";
|
||||
|
||||
export type CriteriaParamType = QFilterCriteriaWithId | null | "tooComplex";
|
||||
|
||||
@ -50,6 +51,7 @@ interface QuickFilterProps
|
||||
updateCriteria: (newCriteria: QFilterCriteria, needDebounce: boolean, doRemoveCriteria: boolean) => void;
|
||||
defaultOperator?: QCriteriaOperator;
|
||||
handleRemoveQuickFilterField?: (fieldName: string) => void;
|
||||
queryScreenUsage?: QueryScreenUsage;
|
||||
}
|
||||
|
||||
QuickFilter.defaultProps =
|
||||
@ -71,7 +73,7 @@ export const quickFilterButtonStyles = {
|
||||
minHeight: "auto",
|
||||
padding: "0.375rem 0.625rem", whiteSpace: "nowrap",
|
||||
marginBottom: "0.5rem"
|
||||
}
|
||||
};
|
||||
|
||||
/*******************************************************************************
|
||||
** Test if a CriteriaParamType represents an actual query criteria - or, if it's
|
||||
@ -89,11 +91,11 @@ const criteriaParamIsCriteria = (param: CriteriaParamType): boolean =>
|
||||
*******************************************************************************/
|
||||
const doesOperatorOptionEqualCriteria = (operatorOption: OperatorOption, criteria: QFilterCriteriaWithId): boolean =>
|
||||
{
|
||||
if(operatorOption.value == criteria.operator)
|
||||
if (operatorOption.value == criteria.operator)
|
||||
{
|
||||
if(operatorOption.implicitValues)
|
||||
if (operatorOption.implicitValues)
|
||||
{
|
||||
if(JSON.stringify(operatorOption.implicitValues) == JSON.stringify(criteria.values))
|
||||
if (JSON.stringify(operatorOption.implicitValues) == JSON.stringify(criteria.values))
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
@ -107,7 +109,7 @@ const doesOperatorOptionEqualCriteria = (operatorOption: OperatorOption, criteri
|
||||
}
|
||||
|
||||
return (false);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@ -117,29 +119,29 @@ const doesOperatorOptionEqualCriteria = (operatorOption: OperatorOption, criteri
|
||||
*******************************************************************************/
|
||||
const getOperatorSelectedValue = (operatorOptions: OperatorOption[], criteria: QFilterCriteriaWithId, defaultOperator: QCriteriaOperator): OperatorOption =>
|
||||
{
|
||||
if(criteria)
|
||||
if (criteria)
|
||||
{
|
||||
const filteredOptions = operatorOptions.filter(o => doesOperatorOptionEqualCriteria(o, criteria));
|
||||
if(filteredOptions.length > 0)
|
||||
if (filteredOptions.length > 0)
|
||||
{
|
||||
return (filteredOptions[0]);
|
||||
}
|
||||
}
|
||||
|
||||
const filteredOptions = operatorOptions.filter(o => o.value == defaultOperator);
|
||||
if(filteredOptions.length > 0)
|
||||
if (filteredOptions.length > 0)
|
||||
{
|
||||
return (filteredOptions[0]);
|
||||
}
|
||||
|
||||
return (null);
|
||||
}
|
||||
};
|
||||
|
||||
/*******************************************************************************
|
||||
** Component to render a QuickFilter - that is - a button, with a Menu under it,
|
||||
** with Operator and Value controls.
|
||||
*******************************************************************************/
|
||||
export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData, criteriaParam, updateCriteria, defaultOperator, handleRemoveQuickFilterField}: QuickFilterProps): JSX.Element
|
||||
export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData, criteriaParam, updateCriteria, defaultOperator, handleRemoveQuickFilterField, queryScreenUsage}: QuickFilterProps): JSX.Element
|
||||
{
|
||||
const operatorOptions = fieldMetaData ? getOperatorOptions(tableMetaData, fullFieldName) : [];
|
||||
const [_, tableForField] = TableUtils.getFieldAndTable(tableMetaData, fullFieldName);
|
||||
@ -190,7 +192,7 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
if (criteriaParamIsCriteria(criteriaParam) && JSON.stringify(criteriaParam) !== JSON.stringify(criteria))
|
||||
{
|
||||
if(isOpen)
|
||||
if (isOpen)
|
||||
{
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// this was firing too-often for case where: there was a criteria originally //
|
||||
@ -217,12 +219,12 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
*******************************************************************************/
|
||||
const criteriaNeedsReset = (): boolean =>
|
||||
{
|
||||
if(criteria != null && criteriaParam == null)
|
||||
if (criteria != null && criteriaParam == null)
|
||||
{
|
||||
const defaultOperatorOption = operatorOptions.filter(o => o.value == defaultOperator)[0];
|
||||
if(criteria.operator !== defaultOperatorOption?.value || JSON.stringify(criteria.values) !== JSON.stringify(getDefaultCriteriaValue()))
|
||||
if (criteria.operator !== defaultOperatorOption?.value || JSON.stringify(criteria.values) !== JSON.stringify(getDefaultCriteriaValue()))
|
||||
{
|
||||
if(isOpen)
|
||||
if (isOpen)
|
||||
{
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
// this was firing too-often for case where: there was no criteria originally, //
|
||||
@ -237,7 +239,7 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
}
|
||||
|
||||
return (false);
|
||||
}
|
||||
};
|
||||
|
||||
/*******************************************************************************
|
||||
** Construct a new criteria object - resetting the values tied to the operator
|
||||
@ -251,8 +253,8 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
setOperatorSelectedValue(operatorOption);
|
||||
setOperatorInputValue(operatorOption?.label);
|
||||
setCriteria(criteria);
|
||||
return(criteria);
|
||||
}
|
||||
return (criteria);
|
||||
};
|
||||
|
||||
/*******************************************************************************
|
||||
** event handler to open the menu in response to the button being clicked.
|
||||
@ -266,7 +268,7 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
{
|
||||
const element = document.getElementById("value-" + criteria.id);
|
||||
element?.focus();
|
||||
})
|
||||
});
|
||||
};
|
||||
|
||||
/*******************************************************************************
|
||||
@ -304,15 +306,15 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
// we've seen cases where switching operators can sometimes put a null in as the first value... //
|
||||
// that just causes a bad time (e.g., null pointers in Autocomplete), so, get rid of that. //
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
if(criteria.values && criteria.values.length == 1 && criteria.values[0] == null)
|
||||
if (criteria.values && criteria.values.length == 1 && criteria.values[0] == null)
|
||||
{
|
||||
criteria.values = [];
|
||||
}
|
||||
|
||||
if(newValue.valueMode && !newValue.implicitValues)
|
||||
if (newValue.valueMode && !newValue.implicitValues)
|
||||
{
|
||||
const requiredValueCount = getValueModeRequiredCount(newValue.valueMode);
|
||||
if(requiredValueCount != null && criteria.values.length > requiredValueCount)
|
||||
if (requiredValueCount != null && criteria.values.length > requiredValueCount)
|
||||
{
|
||||
criteria.values.splice(requiredValueCount);
|
||||
}
|
||||
@ -345,6 +347,7 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
// @ts-ignore
|
||||
const value = newValue !== undefined ? newValue : event ? event.target.value : null;
|
||||
|
||||
console.log("IN HERE");
|
||||
if (!criteria.values)
|
||||
{
|
||||
criteria.values = [];
|
||||
@ -376,13 +379,13 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
*******************************************************************************/
|
||||
const resetCriteria = (e: React.MouseEvent<HTMLSpanElement>) =>
|
||||
{
|
||||
if(criteriaIsValid)
|
||||
if (criteriaIsValid)
|
||||
{
|
||||
e.stopPropagation();
|
||||
const newCriteria = makeNewCriteria();
|
||||
updateCriteria(newCriteria, false, true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/*******************************************************************************
|
||||
** event handler for clicking the (x) icon that turns off this quick filter field.
|
||||
@ -390,17 +393,17 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
*******************************************************************************/
|
||||
const handleTurningOffQuickFilterField = () =>
|
||||
{
|
||||
closeMenu()
|
||||
if(handleRemoveQuickFilterField)
|
||||
closeMenu();
|
||||
if (handleRemoveQuickFilterField)
|
||||
{
|
||||
handleRemoveQuickFilterField(criteria?.fieldName);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
// if no field was input (e.g., record-query is still loading), return null early //
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
if(!fieldMetaData)
|
||||
if (!fieldMetaData)
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
@ -410,10 +413,10 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
// from the last selected one, then set the state vars that control that autocomplete //
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
const maybeNewOperatorSelectedValue = getOperatorSelectedValue(operatorOptions, criteria, defaultOperator);
|
||||
if(JSON.stringify(maybeNewOperatorSelectedValue) !== JSON.stringify(operatorSelectedValue))
|
||||
if (JSON.stringify(maybeNewOperatorSelectedValue) !== JSON.stringify(operatorSelectedValue))
|
||||
{
|
||||
setOperatorSelectedValue(maybeNewOperatorSelectedValue)
|
||||
setOperatorInputValue(maybeNewOperatorSelectedValue?.label)
|
||||
setOperatorSelectedValue(maybeNewOperatorSelectedValue);
|
||||
setOperatorInputValue(maybeNewOperatorSelectedValue?.label);
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////
|
||||
@ -431,7 +434,7 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
const tooltipEnterDelay = 500;
|
||||
|
||||
let buttonAdditionalStyles: any = {};
|
||||
let buttonContent = <span>{tableForField?.name != tableMetaData.name ? `${tableForField.label}: ` : ""}{fieldMetaData.label}</span>
|
||||
let buttonContent = <span>{tableForField?.name != tableMetaData.name ? `${tableForField.label}: ` : ""}{fieldMetaData.label}</span>;
|
||||
let buttonClassName = "filterNotActive";
|
||||
if (criteriaIsValid)
|
||||
{
|
||||
@ -446,9 +449,9 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
// don't show the Equals or In operators //
|
||||
///////////////////////////////////////////
|
||||
let operatorString = (<>{operatorSelectedValue.label} </>);
|
||||
if(operatorSelectedValue.value == QCriteriaOperator.EQUALS || operatorSelectedValue.value == QCriteriaOperator.IN)
|
||||
if (operatorSelectedValue.value == QCriteriaOperator.EQUALS || operatorSelectedValue.value == QCriteriaOperator.IN)
|
||||
{
|
||||
operatorString = (<></>)
|
||||
operatorString = (<></>);
|
||||
}
|
||||
|
||||
buttonContent = (<><span style={{fontWeight: 700}}>{buttonContent}:</span> <span style={{fontWeight: 400}}>{operatorString}{valuesString}</span></>);
|
||||
@ -491,7 +494,7 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
const xClicked = (e: React.MouseEvent<HTMLSpanElement>) =>
|
||||
{
|
||||
e.stopPropagation();
|
||||
if(criteriaIsValid)
|
||||
if (criteriaIsValid)
|
||||
{
|
||||
resetCriteria(e);
|
||||
}
|
||||
@ -499,12 +502,12 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
{
|
||||
handleTurningOffQuickFilterField();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//////////////////////////////
|
||||
// return the button & menu //
|
||||
//////////////////////////////
|
||||
const widthAndMaxWidth = fieldMetaData?.type == QFieldType.DATE_TIME ? 275 : 250
|
||||
const widthAndMaxWidth = (fieldMetaData?.type == QFieldType.DATE_TIME) ? 315 : 250;
|
||||
return (
|
||||
<>
|
||||
{button}
|
||||
@ -541,6 +544,7 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
|
||||
</Box>
|
||||
<Box width={widthAndMaxWidth} maxWidth={widthAndMaxWidth} className="quickFilter filterValuesColumn">
|
||||
<FilterCriteriaRowValues
|
||||
queryScreenUsage={queryScreenUsage}
|
||||
operatorOption={operatorSelectedValue}
|
||||
criteria={criteria}
|
||||
field={fieldMetaData}
|
||||
|
487
src/qqq/components/sharing/ShareModal.tsx
Normal file
487
src/qqq/components/sharing/ShareModal.tsx
Normal file
@ -0,0 +1,487 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import {QJobComplete} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJobComplete";
|
||||
import {QJobError} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJobError";
|
||||
import {QRecord} from "@kingsrook/qqq-frontend-core/lib/model/QRecord";
|
||||
import {Alert, Box} from "@mui/material";
|
||||
import Autocomplete from "@mui/material/Autocomplete";
|
||||
import Button from "@mui/material/Button";
|
||||
import Card from "@mui/material/Card";
|
||||
import Icon from "@mui/material/Icon";
|
||||
import Modal from "@mui/material/Modal";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import Tooltip from "@mui/material/Tooltip/Tooltip";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import FormData from "form-data";
|
||||
import colors from "qqq/assets/theme/base/colors";
|
||||
import {QCancelButton} from "qqq/components/buttons/DefaultButtons";
|
||||
import DynamicSelect, {getAutocompleteOutlinedStyle} from "qqq/components/forms/DynamicSelect";
|
||||
import Client from "qqq/utils/qqq/Client";
|
||||
import React, {useEffect, useReducer, useState} from "react";
|
||||
|
||||
interface ShareModalProps
|
||||
{
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
tableMetaData: QTableMetaData;
|
||||
record: QRecord;
|
||||
}
|
||||
|
||||
ShareModal.defaultProps = {};
|
||||
|
||||
|
||||
interface CurrentShare
|
||||
{
|
||||
shareId: any;
|
||||
scopeId: string;
|
||||
audienceType: string;
|
||||
audienceId: any;
|
||||
audienceLabel: string;
|
||||
}
|
||||
|
||||
interface Scope
|
||||
{
|
||||
id: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
const scopeOptions: Scope[] = [
|
||||
{id: "READ_ONLY", label: "Read-Only"},
|
||||
{id: "READ_WRITE", label: "Read and Edit"}
|
||||
];
|
||||
|
||||
const defaultScope = scopeOptions[0];
|
||||
|
||||
const qController = Client.getInstance();
|
||||
|
||||
interface ShareableTableMetaData
|
||||
{
|
||||
sharedRecordTableName: string;
|
||||
assetIdFieldName: string;
|
||||
scopeFieldName: string;
|
||||
audienceTypesPossibleValueSourceName: string;
|
||||
audiencePossibleValueSourceName: string;
|
||||
thisTableOwnerIdFieldName: string;
|
||||
audienceTypes: {[name: string]: any}; // values here are: ShareableAudienceType
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** component containing a Modal dialog for sharing records
|
||||
*******************************************************************************/
|
||||
export default function ShareModal({open, onClose, tableMetaData, record}: ShareModalProps): JSX.Element
|
||||
{
|
||||
const [statusString, setStatusString] = useState("Loading...");
|
||||
const [alert, setAlert] = useState(null as string);
|
||||
|
||||
const [selectedAudienceOption, setSelectedAudienceOption] = useState(null as {id: string, label: string});
|
||||
const [selectedAudienceType, setSelectedAudienceType] = useState(null);
|
||||
const [selectedAudienceId, setSelectedAudienceId] = useState(null);
|
||||
const [selectedScopeId, setSelectedScopeId] = useState(defaultScope.id);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const [currentShares, setCurrentShares] = useState([] as CurrentShare[])
|
||||
const [needToLoadCurrentShares, setNeedToLoadCurrentShares] = useState(true);
|
||||
const [everLoadedCurrentShares, setEverLoadedCurrentShares] = useState(false);
|
||||
|
||||
const shareableTableMetaData = tableMetaData.shareableTableMetaData as ShareableTableMetaData;
|
||||
|
||||
const [, forceUpdate] = useReducer((x) => x + 1, 0);
|
||||
|
||||
if(!shareableTableMetaData)
|
||||
{
|
||||
console.error(`Did not find a shareableTableMetaData on table ${tableMetaData.name}`);
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////
|
||||
// trigger initial load, and post any changes, re-load //
|
||||
/////////////////////////////////////////////////////////
|
||||
useEffect(() =>
|
||||
{
|
||||
if(needToLoadCurrentShares)
|
||||
{
|
||||
loadShares();
|
||||
}
|
||||
}, [needToLoadCurrentShares]);
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function close(event: object, reason: string)
|
||||
{
|
||||
if (reason === "backdropClick" || reason === "escapeKeyDown")
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
onClose();
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function handleAudienceChange(value: any | any[], reason: string)
|
||||
{
|
||||
if(value)
|
||||
{
|
||||
const [audienceType, audienceId] = value.id.split(":");
|
||||
setSelectedAudienceType(audienceType);
|
||||
setSelectedAudienceId(audienceId);
|
||||
}
|
||||
else
|
||||
{
|
||||
setSelectedAudienceType(null);
|
||||
setSelectedAudienceId(null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function handleScopeChange(event: React.SyntheticEvent, value: any | any[], reason: string)
|
||||
{
|
||||
if(value)
|
||||
{
|
||||
setSelectedScopeId(value.id);
|
||||
}
|
||||
else
|
||||
{
|
||||
setSelectedScopeId(null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
async function editingExistingShareScope(shareId: number, value: any | any[])
|
||||
{
|
||||
setStatusString("Saving...");
|
||||
setAlert(null);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("tableName", tableMetaData.name);
|
||||
formData.append("recordId", record.values.get(tableMetaData.primaryKeyField));
|
||||
formData.append("shareId", shareId);
|
||||
formData.append("scopeId", value.id);
|
||||
|
||||
const processResult = await qController.processRun("editSharedRecord", formData, null, true);
|
||||
|
||||
if (processResult instanceof QJobError)
|
||||
{
|
||||
const jobError = processResult as QJobError;
|
||||
setStatusString(null);
|
||||
setAlert("Error editing shared record: " + jobError.error);
|
||||
setSubmitting(false)
|
||||
}
|
||||
else
|
||||
{
|
||||
const result = processResult as QJobComplete;
|
||||
setStatusString(null);
|
||||
setAlert(null);
|
||||
setNeedToLoadCurrentShares(true);
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
async function loadShares()
|
||||
{
|
||||
setNeedToLoadCurrentShares(false);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("tableName", tableMetaData.name);
|
||||
formData.append("recordId", record.values.get(tableMetaData.primaryKeyField));
|
||||
const processResult = await qController.processRun("getSharedRecords", formData, null, true);
|
||||
|
||||
setStatusString("Loading...");
|
||||
setAlert(null)
|
||||
|
||||
if (processResult instanceof QJobError)
|
||||
{
|
||||
const jobError = processResult as QJobError;
|
||||
setStatusString(null);
|
||||
setAlert("Error loading: " + jobError.error);
|
||||
}
|
||||
else
|
||||
{
|
||||
const result = processResult as QJobComplete;
|
||||
|
||||
const newCurrentShares: CurrentShare[] = [];
|
||||
for (let i in result.values["resultList"])
|
||||
{
|
||||
newCurrentShares.push(result.values["resultList"][i].values);
|
||||
}
|
||||
setCurrentShares(newCurrentShares);
|
||||
setEverLoadedCurrentShares(true);
|
||||
|
||||
setStatusString(null);
|
||||
setAlert(null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
async function saveNewShare()
|
||||
{
|
||||
setSubmitting(true)
|
||||
setStatusString("Saving...");
|
||||
setAlert(null);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("tableName", tableMetaData.name);
|
||||
formData.append("recordId", record.values.get(tableMetaData.primaryKeyField));
|
||||
formData.append("audienceType", selectedAudienceType);
|
||||
formData.append("audienceId", selectedAudienceId);
|
||||
formData.append("scopeId", selectedScopeId);
|
||||
|
||||
const processResult = await qController.processRun("insertSharedRecord", formData, null, true);
|
||||
|
||||
if (processResult instanceof QJobError)
|
||||
{
|
||||
const jobError = processResult as QJobError;
|
||||
setStatusString(null);
|
||||
setAlert("Error sharing record: " + jobError.error);
|
||||
setSubmitting(false)
|
||||
}
|
||||
else
|
||||
{
|
||||
const result = processResult as QJobComplete;
|
||||
setStatusString(null);
|
||||
setAlert(null);
|
||||
setSelectedAudienceOption(null);
|
||||
setNeedToLoadCurrentShares(true);
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
async function removeShare(shareId: number)
|
||||
{
|
||||
setStatusString("Deleting...");
|
||||
setAlert(null);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("tableName", tableMetaData.name);
|
||||
formData.append("recordId", record.values.get(tableMetaData.primaryKeyField));
|
||||
formData.append("shareId", shareId);
|
||||
|
||||
const processResult = await qController.processRun("deleteSharedRecord", formData, null, true);
|
||||
|
||||
if (processResult instanceof QJobError)
|
||||
{
|
||||
const jobError = processResult as QJobError;
|
||||
setStatusString(null);
|
||||
setAlert("Error deleting share: " + jobError.error);
|
||||
}
|
||||
else
|
||||
{
|
||||
const result = processResult as QJobComplete;
|
||||
setNeedToLoadCurrentShares(true);
|
||||
setStatusString(null);
|
||||
setAlert(null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function getScopeOption(scopeId: string): Scope
|
||||
{
|
||||
for (let scopeOption of scopeOptions)
|
||||
{
|
||||
if(scopeOption.id == scopeId)
|
||||
{
|
||||
return (scopeOption);
|
||||
}
|
||||
}
|
||||
|
||||
return (null);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function renderScopeDropdown(id: string, defaultValue: Scope, onChange: (event: React.SyntheticEvent, value: any | any[], reason: string) => void)
|
||||
{
|
||||
const isDisabled = (id == "new-share-scope" && submitting);
|
||||
return (
|
||||
<Autocomplete
|
||||
id={id}
|
||||
disabled={isDisabled}
|
||||
renderInput={(params) => (<TextField {...params} label="Scope" variant="outlined" autoComplete="off" type="search" InputProps={{...params.InputProps}} />)}
|
||||
options={scopeOptions}
|
||||
// @ts-ignore
|
||||
defaultValue={defaultValue}
|
||||
onChange={onChange}
|
||||
isOptionEqualToValue={(option, value) => option.id === value.id}
|
||||
// @ts-ignore Property label does not exist on string | {thing with label}
|
||||
getOptionLabel={(option) => option.label}
|
||||
autoSelect={true}
|
||||
autoHighlight={true}
|
||||
disableClearable
|
||||
fullWidth
|
||||
sx={getAutocompleteOutlinedStyle(isDisabled)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
//////////////////////
|
||||
// render the modal //
|
||||
//////////////////////
|
||||
return (<Modal open={open} onClose={close}>
|
||||
<div className="share">
|
||||
<Box sx={{position: "absolute", overflowY: "auto", maxHeight: "100%", width: "100%", display: "flex", height: "100%", flexDirection: "column", justifyContent: "center"}}>
|
||||
<Card sx={{my: 5, mx: "auto", p: 3}}>
|
||||
|
||||
{/* header */}
|
||||
<Box display="flex" flexDirection="row" justifyContent="space-between" alignItems="flex-start" maxWidth="590px">
|
||||
<Typography variant="h4" pb={1} fontWeight="600">
|
||||
Share {tableMetaData.label}: {record?.recordLabel ?? record?.values?.get(tableMetaData.primaryKeyField) ?? "Unknown"}
|
||||
<Box color={colors.gray.main} pb={"0.5rem"} fontSize={"0.875rem"} fontWeight="400">
|
||||
{/* todo move to helpContent (what do we attach the meta-data too??) */}
|
||||
Select a user or a group to share this record with.
|
||||
{/*You can choose if they should only be able to Read the record, or also make Edits to it.*/}
|
||||
</Box>
|
||||
<Box fontSize={14} pb={1} fontWeight="300">
|
||||
{alert && <Alert color="error" onClose={() => setAlert(null)}>{alert}</Alert>}
|
||||
{statusString}
|
||||
{!alert && !statusString && (<> </>)}
|
||||
</Box>
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* body */}
|
||||
<Box pb={3} display="flex" flexDirection="column">
|
||||
{/* row for adding a new share */}
|
||||
<Box display="flex" flexDirection="row" alignItems="center">
|
||||
<Box width="550px" pr={2} mb={-1.5}>
|
||||
<DynamicSelect
|
||||
possibleValueSourceName={shareableTableMetaData.audiencePossibleValueSourceName}
|
||||
fieldLabel="User or Group" // todo should come from shareableTableMetaData
|
||||
initialValue={selectedAudienceOption?.id}
|
||||
initialDisplayValue={selectedAudienceOption?.label}
|
||||
inForm={false}
|
||||
onChange={handleAudienceChange}
|
||||
/>
|
||||
</Box>
|
||||
{/*
|
||||
when turning scope back on, change width of audience box to 350px
|
||||
<Box width="180px" pr={2}>
|
||||
{renderScopeDropdown("new-share-scope", defaultScope, handleScopeChange)}
|
||||
</Box>
|
||||
*/}
|
||||
<Box>
|
||||
<Tooltip title={selectedAudienceId == null ? "Select a user or group to share with." : null}>
|
||||
<span>
|
||||
<Button disabled={submitting || selectedAudienceId == null} sx={iconButtonSX} onClick={() => saveNewShare()}>
|
||||
<Icon color={selectedAudienceId == null ? "secondary" : "info"}>save</Icon>
|
||||
</Button>
|
||||
</span>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* row showing existing shares */}
|
||||
<Box pt={3}>
|
||||
<Box pb="0.25rem">
|
||||
<h5 style={{fontWeight: "600"}}>Current Shares
|
||||
{
|
||||
everLoadedCurrentShares ? <> ({currentShares.length})</> : <></>
|
||||
}
|
||||
</h5>
|
||||
</Box>
|
||||
<Box sx={{border: `1px solid ${colors.grayLines.main}`, borderRadius: "1rem", overflow: "hidden"}}>
|
||||
<Box sx={{overflow: "auto"}} height="210px" pt="0.75rem">
|
||||
{
|
||||
currentShares.map((share) => (
|
||||
<Box key={share.shareId} display="flex" justifyContent="space-between" alignItems="center" p="0.25rem" pb="0.75rem" fontSize="1rem">
|
||||
<Box display="flex" alignItems="center">
|
||||
<Box width="490px" pl="1rem">{share.audienceLabel}</Box>
|
||||
{/*
|
||||
when turning scope back on, change width of audience box to 310px
|
||||
<Box width="160px">{renderScopeDropdown(`scope-${share.shareId}`, getScopeOption(share.scopeId), (event: React.SyntheticEvent, value: any | any[], reason: string) => editingExistingShareScope(share.shareId, value))}</Box>
|
||||
*/}
|
||||
</Box>
|
||||
<Box pr="1rem">
|
||||
<Button sx={{...iconButtonSX, ...redIconButton}} onClick={() => removeShare(share.shareId)}><Icon>clear</Icon></Button>
|
||||
</Box>
|
||||
</Box>
|
||||
))
|
||||
}
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
</Box>
|
||||
|
||||
{/* footer */}
|
||||
<Box display="flex" flexDirection="row" justifyContent="flex-end">
|
||||
<QCancelButton label="Done" iconName="check" onClickHandler={() => close(null, null)} disabled={false} />
|
||||
</Box>
|
||||
</Card>
|
||||
</Box>
|
||||
</div>
|
||||
</Modal>);
|
||||
|
||||
}
|
||||
|
||||
const iconButtonSX =
|
||||
{
|
||||
border: `1px solid ${colors.grayLines.main} !important`,
|
||||
borderRadius: "0.75rem",
|
||||
textTransform: "none",
|
||||
fontSize: "1rem",
|
||||
fontWeight: "400",
|
||||
width: "40px",
|
||||
minWidth: "40px",
|
||||
paddingLeft: 0,
|
||||
paddingRight: 0,
|
||||
color: colors.secondary.main,
|
||||
"&:hover": {color: colors.secondary.main},
|
||||
"&:focus": {color: colors.secondary.main},
|
||||
"&:focus:not(:hover)": {color: colors.secondary.main},
|
||||
};
|
||||
|
||||
const redIconButton =
|
||||
{
|
||||
color: colors.error.main,
|
||||
"&:hover": {color: colors.error.main},
|
||||
"&:focus": {color: colors.error.main},
|
||||
"&:focus:not(:hover)": {color: colors.error.main},
|
||||
};
|
||||
|
@ -22,16 +22,16 @@
|
||||
|
||||
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
|
||||
import {Box, Skeleton} from "@mui/material";
|
||||
import React from "react";
|
||||
import {BlockData} from "qqq/components/widgets/blocks/BlockModels";
|
||||
import WidgetBlock from "qqq/components/widgets/WidgetBlock";
|
||||
import React from "react";
|
||||
|
||||
|
||||
interface CompositeData
|
||||
{
|
||||
blocks: BlockData[];
|
||||
styleOverrides?: any;
|
||||
layout?: string
|
||||
layout?: string;
|
||||
}
|
||||
|
||||
|
||||
@ -57,7 +57,14 @@ export default function CompositeWidget({widgetMetaData, data}: CompositeWidgetP
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
let layout = data?.layout;
|
||||
let boxStyle: any = {};
|
||||
if (layout == "FLEX_ROW_WRAPPED")
|
||||
if (layout == "FLEX_COLUMN")
|
||||
{
|
||||
boxStyle.display = "flex";
|
||||
boxStyle.flexDirection = "column";
|
||||
boxStyle.flexWrap = "wrap";
|
||||
boxStyle.gap = "0.5rem";
|
||||
}
|
||||
else if (layout == "FLEX_ROW_WRAPPED")
|
||||
{
|
||||
boxStyle.display = "flex";
|
||||
boxStyle.flexDirection = "row";
|
||||
@ -68,7 +75,7 @@ export default function CompositeWidget({widgetMetaData, data}: CompositeWidgetP
|
||||
{
|
||||
boxStyle.display = "flex";
|
||||
boxStyle.flexDirection = "row";
|
||||
boxStyle.justifyContent = "space-between"
|
||||
boxStyle.justifyContent = "space-between";
|
||||
boxStyle.gap = "0.25rem";
|
||||
}
|
||||
else if (layout == "TABLE_SUB_ROW_DETAILS")
|
||||
|
@ -19,6 +19,7 @@
|
||||
*/
|
||||
|
||||
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
|
||||
import {QRecord} from "@kingsrook/qqq-frontend-core/lib/model/QRecord";
|
||||
import {Alert, Skeleton} from "@mui/material";
|
||||
import Box from "@mui/material/Box";
|
||||
import Grid from "@mui/material/Grid";
|
||||
@ -37,7 +38,10 @@ import StackedBarChart from "qqq/components/widgets/charts/StackedBarChart";
|
||||
import CompositeWidget from "qqq/components/widgets/CompositeWidget";
|
||||
import DataBagViewer from "qqq/components/widgets/misc/DataBagViewer";
|
||||
import DividerWidget from "qqq/components/widgets/misc/Divider";
|
||||
import DynamicFormWidget from "qqq/components/widgets/misc/DynamicFormWidget";
|
||||
import FieldValueListWidget from "qqq/components/widgets/misc/FieldValueListWidget";
|
||||
import FilterAndColumnsSetupWidget from "qqq/components/widgets/misc/FilterAndColumnsSetupWidget";
|
||||
import PivotTableSetupWidget from "qqq/components/widgets/misc/PivotTableSetupWidget";
|
||||
import QuickSightChart from "qqq/components/widgets/misc/QuickSightChart";
|
||||
import RecordGridWidget from "qqq/components/widgets/misc/RecordGridWidget";
|
||||
import ScriptViewer from "qqq/components/widgets/misc/ScriptViewer";
|
||||
@ -46,7 +50,7 @@ import USMapWidget from "qqq/components/widgets/misc/USMapWidget";
|
||||
import ParentWidget from "qqq/components/widgets/ParentWidget";
|
||||
import MultiStatisticsCard from "qqq/components/widgets/statistics/MultiStatisticsCard";
|
||||
import StatisticsCard from "qqq/components/widgets/statistics/StatisticsCard";
|
||||
import Widget, {HeaderIcon, LabelComponent, WIDGET_DROPDOWN_SELECTION_LOCAL_STORAGE_KEY_ROOT} from "qqq/components/widgets/Widget";
|
||||
import Widget, {HeaderIcon, LabelComponent, WIDGET_DROPDOWN_SELECTION_LOCAL_STORAGE_KEY_ROOT, WidgetData} from "qqq/components/widgets/Widget";
|
||||
import WidgetBlock from "qqq/components/widgets/WidgetBlock";
|
||||
import ProcessRun from "qqq/pages/processes/ProcessRun";
|
||||
import Client from "qqq/utils/qqq/Client";
|
||||
@ -61,6 +65,7 @@ interface Props
|
||||
widgetMetaDataList: QWidgetMetaData[];
|
||||
tableName?: string;
|
||||
entityPrimaryKey?: string;
|
||||
record?: QRecord;
|
||||
omitWrappingGridContainer: boolean;
|
||||
areChildren?: boolean;
|
||||
childUrlParams?: string;
|
||||
@ -79,7 +84,7 @@ DashboardWidgets.defaultProps = {
|
||||
wrapWidgetsInTabPanels: false,
|
||||
};
|
||||
|
||||
function DashboardWidgets({widgetMetaDataList, tableName, entityPrimaryKey, omitWrappingGridContainer, areChildren, childUrlParams, parentWidgetMetaData, wrapWidgetsInTabPanels}: Props): JSX.Element
|
||||
function DashboardWidgets({widgetMetaDataList, tableName, entityPrimaryKey, record, omitWrappingGridContainer, areChildren, childUrlParams, parentWidgetMetaData, wrapWidgetsInTabPanels}: Props): JSX.Element
|
||||
{
|
||||
const [widgetData, setWidgetData] = useState([] as any[]);
|
||||
const [widgetCounter, setWidgetCounter] = useState(0);
|
||||
@ -248,6 +253,23 @@ function DashboardWidgets({widgetMetaDataList, tableName, entityPrimaryKey, omit
|
||||
|
||||
const widgetCount = widgetMetaDataList ? widgetMetaDataList.length : 0;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** helper function, to convert values from a QRecord values map to a regular old
|
||||
** js object
|
||||
*******************************************************************************/
|
||||
function convertQRecordValuesFromMapToObject(record: QRecord): { [name: string]: any }
|
||||
{
|
||||
const rs: { [name: string]: any } = {};
|
||||
|
||||
if (record && record.values)
|
||||
{
|
||||
record.values.forEach((value, key) => rs[key] = value);
|
||||
}
|
||||
|
||||
return (rs);
|
||||
}
|
||||
|
||||
const renderWidget = (widgetMetaData: QWidgetMetaData, i: number): JSX.Element =>
|
||||
{
|
||||
const labelAdditionalComponentsRight: LabelComponent[] = [];
|
||||
@ -271,7 +293,7 @@ function DashboardWidgets({widgetMetaDataList, tableName, entityPrimaryKey, omit
|
||||
}
|
||||
|
||||
return (
|
||||
<Box key={`${widgetMetaData.name}-${i}`} sx={{alignItems: "stretch", flexGrow: 1, display: "flex", marginTop: "0px", paddingTop: "0px", width: "100%", height: "100%"}}>
|
||||
<Box key={`${widgetMetaData.name}-${i}`} sx={{alignItems: "stretch", flexGrow: 1, display: "flex", marginTop: "0px", paddingTop: "0px", width: "100%", height: "100%", flexDirection: widgetMetaData.type == "multiTable" ? "column" : "row"}}>
|
||||
{
|
||||
haveLoadedParams && widgetMetaData.type === "parentWidget" && (
|
||||
<ParentWidget
|
||||
@ -321,6 +343,20 @@ function DashboardWidgets({widgetMetaDataList, tableName, entityPrimaryKey, omit
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
widgetMetaData.type === "multiTable" && (
|
||||
widgetData[i]?.tableDataList?.map((tableData: WidgetData, index: number) =>
|
||||
<Box pb={3} key={`${widgetMetaData.type}-${index}`}>
|
||||
<TableWidget
|
||||
widgetMetaData={widgetMetaData}
|
||||
widgetData={tableData}
|
||||
reloadWidgetCallback={(data) => reloadWidget(i, data)}
|
||||
isChild={areChildren}
|
||||
/>
|
||||
</Box>
|
||||
)
|
||||
)
|
||||
}
|
||||
{
|
||||
widgetMetaData.type === "stackedBarChart" && (
|
||||
<Widget
|
||||
@ -561,6 +597,28 @@ function DashboardWidgets({widgetMetaDataList, tableName, entityPrimaryKey, omit
|
||||
</Widget>
|
||||
)
|
||||
}
|
||||
{
|
||||
widgetMetaData.type === "filterAndColumnsSetup" && (
|
||||
widgetData && widgetData[i] && widgetData[i].queryParams &&
|
||||
<FilterAndColumnsSetupWidget isEditable={false} widgetMetaData={widgetMetaData} recordValues={convertQRecordValuesFromMapToObject(record)} onSaveCallback={() =>
|
||||
{
|
||||
}} />
|
||||
)
|
||||
}
|
||||
{
|
||||
widgetMetaData.type === "pivotTableSetup" && (
|
||||
widgetData && widgetData[i] && widgetData[i].queryParams &&
|
||||
<PivotTableSetupWidget isEditable={false} widgetMetaData={widgetMetaData} recordValues={convertQRecordValuesFromMapToObject(record)} onSaveCallback={() =>
|
||||
{
|
||||
}} />
|
||||
)
|
||||
}
|
||||
{
|
||||
widgetMetaData.type === "dynamicForm" && (
|
||||
widgetData && widgetData[i] &&
|
||||
<DynamicFormWidget isEditable={false} widgetMetaData={widgetMetaData} widgetData={widgetData[i]} record={record} recordValues={convertQRecordValuesFromMapToObject(record)} />
|
||||
)
|
||||
}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
@ -21,10 +21,11 @@
|
||||
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
|
||||
import Box from "@mui/material/Box";
|
||||
import {Box, InputLabel} from "@mui/material";
|
||||
import Button from "@mui/material/Button";
|
||||
import Card from "@mui/material/Card";
|
||||
import Icon from "@mui/material/Icon";
|
||||
import Switch from "@mui/material/Switch";
|
||||
import Tooltip from "@mui/material/Tooltip/Tooltip";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import parse from "html-react-parser";
|
||||
@ -60,6 +61,7 @@ interface Props
|
||||
labelAdditionalComponentsLeft: LabelComponent[];
|
||||
labelAdditionalElementsLeft: JSX.Element[];
|
||||
labelAdditionalComponentsRight: LabelComponent[];
|
||||
labelAdditionalElementsRight: JSX.Element[];
|
||||
labelBoxAdditionalSx?: any;
|
||||
widgetMetaData?: QWidgetMetaData;
|
||||
widgetData?: WidgetData;
|
||||
@ -80,6 +82,7 @@ Widget.defaultProps = {
|
||||
labelAdditionalComponentsLeft: [],
|
||||
labelAdditionalElementsLeft: [],
|
||||
labelAdditionalComponentsRight: [],
|
||||
labelAdditionalElementsRight: [],
|
||||
labelBoxAdditionalSx: {},
|
||||
omitPadding: false,
|
||||
};
|
||||
@ -160,6 +163,76 @@ export class HeaderIcon extends LabelComponent
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** a link (actually a button) for in a widget's header
|
||||
*******************************************************************************/
|
||||
interface HeaderLinkButtonComponentProps
|
||||
{
|
||||
label: string;
|
||||
onClickCallback: () => void;
|
||||
disabled?: boolean;
|
||||
disabledTooltip?: string;
|
||||
}
|
||||
|
||||
HeaderLinkButtonComponent.defaultProps = {
|
||||
disabled: false,
|
||||
disabledTooltip: null
|
||||
};
|
||||
|
||||
export function HeaderLinkButtonComponent({label, onClickCallback, disabled, disabledTooltip}: HeaderLinkButtonComponentProps): JSX.Element
|
||||
{
|
||||
return (
|
||||
<Tooltip title={disabledTooltip}>
|
||||
<span>
|
||||
<Button disabled={disabled} onClick={() => onClickCallback()} sx={{p: 0}} disableRipple>
|
||||
<Typography display="inline" textTransform="none" fontSize={"1.125rem"}>
|
||||
{label}
|
||||
</Typography>
|
||||
</Button>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
interface HeaderToggleComponentProps
|
||||
{
|
||||
label: string;
|
||||
getValue: () => boolean;
|
||||
onClickCallback: () => void;
|
||||
disabled?: boolean;
|
||||
disabledTooltip?: string;
|
||||
}
|
||||
|
||||
HeaderToggleComponent.defaultProps = {
|
||||
disabled: false,
|
||||
disabledTooltip: null
|
||||
};
|
||||
|
||||
export function HeaderToggleComponent({label, getValue, onClickCallback, disabled, disabledTooltip}: HeaderToggleComponentProps): JSX.Element
|
||||
{
|
||||
const onClick = () =>
|
||||
{
|
||||
onClickCallback();
|
||||
};
|
||||
|
||||
return (
|
||||
<Box alignItems="baseline" mr="-0.75rem">
|
||||
<Tooltip title={disabledTooltip}>
|
||||
<span>
|
||||
<InputLabel sx={{fontSize: "1.125rem", px: "0 !important", cursor: disabled ? "default" : "pointer", opacity: disabled ? 0.65 : 1}} unselectable="on">
|
||||
{label} <Switch disabled={disabled} checked={getValue()} onClick={onClick} />
|
||||
</InputLabel>
|
||||
</span>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@ -573,6 +646,8 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
|
||||
localLabelAdditionalElementsLeft.push(WidgetUtils.generateExportButton(onExportClick));
|
||||
}
|
||||
|
||||
let localLabelAdditionalElementsRight = [...props.labelAdditionalElementsRight];
|
||||
|
||||
const hasPermission = props.widgetData?.hasPermission === undefined || props.widgetData?.hasPermission === true;
|
||||
|
||||
const isSet = (v: any): boolean =>
|
||||
@ -589,6 +664,7 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
|
||||
needLabelBox ||= (labelComponentsLeft && labelComponentsLeft.length > 0);
|
||||
needLabelBox ||= (localLabelAdditionalElementsLeft && localLabelAdditionalElementsLeft.length > 0);
|
||||
needLabelBox ||= (labelComponentsRight && labelComponentsRight.length > 0);
|
||||
needLabelBox ||= (localLabelAdditionalElementsRight && localLabelAdditionalElementsRight.length > 0);
|
||||
needLabelBox ||= isSet(props.widgetData?.icon);
|
||||
needLabelBox ||= isSet(props.widgetData?.label);
|
||||
needLabelBox ||= isSet(props.widgetMetaData?.label);
|
||||
@ -618,7 +694,7 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
|
||||
);
|
||||
|
||||
let sublabelElement = (
|
||||
<Box height="20px">
|
||||
<Box key="sublabel" height="20px">
|
||||
<Typography sx={{position: "relative", top: "-18px"}} variant="caption">
|
||||
{props.widgetData?.sublabel}
|
||||
</Typography>
|
||||
@ -705,7 +781,7 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
|
||||
}
|
||||
{localLabelAdditionalElementsLeft}
|
||||
</Box>
|
||||
<Box display="flex">
|
||||
<Box key="sublabelContainer" display="flex">
|
||||
{
|
||||
hasPermission && props.widgetData?.sublabel && (sublabelElement)
|
||||
}
|
||||
@ -720,6 +796,7 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
|
||||
})
|
||||
)
|
||||
}
|
||||
{localLabelAdditionalElementsRight}
|
||||
</Box>
|
||||
</Box>
|
||||
}
|
||||
|
@ -21,14 +21,16 @@
|
||||
|
||||
|
||||
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
|
||||
import Box from "@mui/material/Box";
|
||||
import Button from "@mui/material/Button";
|
||||
import Icon from "@mui/material/Icon";
|
||||
import Tooltip from "@mui/material/Tooltip/Tooltip";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import React from "react";
|
||||
import colors from "qqq/assets/theme/base/colors";
|
||||
import {WidgetData} from "qqq/components/widgets/Widget";
|
||||
import ValueUtils from "qqq/utils/qqq/ValueUtils";
|
||||
import React from "react";
|
||||
import {Link} from "react-router-dom";
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class used by Widgets
|
||||
@ -51,6 +53,17 @@ export class WidgetUtils
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
public static generateLabelLink = (linkText: string, linkURL: string): JSX.Element =>
|
||||
{
|
||||
return (<Box key={1} fontSize="1rem" pl={1} display="inline" position="relative">
|
||||
(<Link to={linkURL}>{linkText}</Link>)
|
||||
</Box>);
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@ -97,4 +110,4 @@ export class WidgetUtils
|
||||
return (fileName);
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -41,7 +41,7 @@ export default function NumberIconBadgeBlock({widgetMetaData, data}: StandardBlo
|
||||
{
|
||||
data.values.iconName &&
|
||||
<BlockElementWrapper metaData={widgetMetaData} data={data} slot="icon">
|
||||
<Icon style={{color: data.styles.color, fontSize: "1rem", position: "relative", top: "3px"}}>{data.values.iconName}</Icon>
|
||||
<Icon style={{color: data.styles.color, fontSize: "1rem", marginLeft: "2px", position: "relative", top: "4px"}}>{data.values.iconName}</Icon>
|
||||
</BlockElementWrapper>
|
||||
}
|
||||
</div>);
|
||||
|
265
src/qqq/components/widgets/misc/DynamicFormWidget.tsx
Normal file
265
src/qqq/components/widgets/misc/DynamicFormWidget.tsx
Normal file
@ -0,0 +1,265 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData";
|
||||
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
|
||||
import {QRecord} from "@kingsrook/qqq-frontend-core/lib/model/QRecord";
|
||||
import Box from "@mui/material/Box";
|
||||
import {FormikContextType, useFormikContext} from "formik";
|
||||
import QDynamicForm from "qqq/components/forms/DynamicForm";
|
||||
import DynamicFormUtils from "qqq/components/forms/DynamicFormUtils";
|
||||
import Widget from "qqq/components/widgets/Widget";
|
||||
import {renderSectionOfFields} from "qqq/pages/records/view/RecordView";
|
||||
import Client from "qqq/utils/qqq/Client";
|
||||
import React, {useEffect, useState} from "react";
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** component props
|
||||
*******************************************************************************/
|
||||
interface DynamicFormWidgetProps
|
||||
{
|
||||
isEditable: boolean;
|
||||
widgetMetaData: QWidgetMetaData;
|
||||
widgetData: any;
|
||||
record: QRecord;
|
||||
recordValues: { [name: string]: any };
|
||||
onSaveCallback?: (values: { [name: string]: any }) => void;
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** default values for props
|
||||
*******************************************************************************/
|
||||
DynamicFormWidget.defaultProps = {
|
||||
onSaveCallback: null
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Component to display a dynamic form - e.g., on a record edit or view screen,
|
||||
** or even within a process.
|
||||
*******************************************************************************/
|
||||
export default function DynamicFormWidget({isEditable, widgetMetaData, widgetData, record, recordValues, onSaveCallback}: DynamicFormWidgetProps): JSX.Element
|
||||
{
|
||||
const [fields, setFields] = useState([] as QFieldMetaData[]);
|
||||
|
||||
const [effectiveIsEditable, setEffectiveIsEditable] = useState(isEditable);
|
||||
if(widgetMetaData.defaultValues.has("isEditable"))
|
||||
{
|
||||
const defaultIsEditableValue = widgetMetaData.defaultValues.get("isEditable")
|
||||
if(defaultIsEditableValue != effectiveIsEditable)
|
||||
{
|
||||
setEffectiveIsEditable(defaultIsEditableValue);
|
||||
}
|
||||
}
|
||||
|
||||
const [dynamicFormFields, setDynamicFormFields] = useState(null as any);
|
||||
const [formValidations, setFormValidations] = useState(null as any);
|
||||
|
||||
const [lastKnowFormValues, setLastKnowFormValues] = useState({} as {[name: string]: any});
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// on initial load, and any time widgetData changes (e.g., if widget gets re-rendered), //
|
||||
// figure out what our form fields are //
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
useEffect(() =>
|
||||
{
|
||||
setDynamicFormFields({})
|
||||
setFormValidations({})
|
||||
|
||||
if(widgetData && widgetData.fieldList)
|
||||
{
|
||||
const newFields: QFieldMetaData[] = [];
|
||||
for (let i = 0; i < widgetData.fieldList.length; i++)
|
||||
{
|
||||
newFields.push(new QFieldMetaData(widgetData.fieldList[i]));
|
||||
}
|
||||
setFields(newFields);
|
||||
|
||||
if(newFields.length > 0)
|
||||
{
|
||||
const recordOfFieldValues = widgetData.recordOfFieldValues ? new QRecord(widgetData.recordOfFieldValues) : null;
|
||||
const {dynamicFormFields: newDynamicFormFields, formValidations: newFormValidations} = DynamicFormUtils.getFormData(newFields);
|
||||
const defaultDisplayValues = new Map<string,string>(); // todo - seems not right?
|
||||
DynamicFormUtils.addPossibleValueProps(newDynamicFormFields, newFields, recordValues.tableName, null, recordOfFieldValues ? recordOfFieldValues.displayValues : defaultDisplayValues);
|
||||
setDynamicFormFields(newDynamicFormFields)
|
||||
setFormValidations(newFormValidations)
|
||||
}
|
||||
|
||||
setLastKnowFormValues({});
|
||||
}
|
||||
else
|
||||
{
|
||||
setFields([])
|
||||
}
|
||||
}, [widgetData]);
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function checkForFormValueChanges(formikProps: FormikContextType<any>)
|
||||
{
|
||||
if(!fields || !fields.length)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let anyChanged = false;
|
||||
for (let i = 0; i < fields.length; i++)
|
||||
{
|
||||
const name = fields[i].name;
|
||||
if(formikProps.values[name] != lastKnowFormValues[name])
|
||||
{
|
||||
anyChanged = true;
|
||||
lastKnowFormValues[name] = formikProps.values[name];
|
||||
}
|
||||
}
|
||||
|
||||
if(anyChanged)
|
||||
{
|
||||
const mergedDynamicFormValuesIntoFieldName = widgetData.mergedDynamicFormValuesIntoFieldName;
|
||||
if(mergedDynamicFormValuesIntoFieldName && onSaveCallback)
|
||||
{
|
||||
const onSaveCallbackParam: {[name: string]: any} = {};
|
||||
onSaveCallbackParam[mergedDynamicFormValuesIntoFieldName] = JSON.stringify(lastKnowFormValues);
|
||||
onSaveCallback(onSaveCallbackParam);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function getInitialValue(fieldName: string)
|
||||
{
|
||||
for (let i = 0; i < fields?.length; i++)
|
||||
{
|
||||
if(fields[i].name == fieldName && fields[i].defaultValue)
|
||||
{
|
||||
return (fields[i].defaultValue)
|
||||
}
|
||||
}
|
||||
|
||||
return (null);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function renderEditForm()
|
||||
{
|
||||
const formikProps = useFormikContext();
|
||||
if(!fields || !fields.length)
|
||||
{
|
||||
return (
|
||||
<Box>
|
||||
<Box fontSize="1rem">{widgetData && widgetData.noFieldsMessage}</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const formData: any = {};
|
||||
formData.values = formikProps.values;
|
||||
formData.touched = formikProps.touched;
|
||||
formData.errors = formikProps.errors;
|
||||
formData.formFields = {};
|
||||
|
||||
// todo - merge the formValidations object with formik's - maybe in the useEffect where we build it
|
||||
// setValidations(Yup.object().shape(formValidations));
|
||||
// formikProps.validationSchema.
|
||||
|
||||
for (let key of Object.keys(dynamicFormFields))
|
||||
{
|
||||
const dynamicFormField = dynamicFormFields[key];
|
||||
formData.formFields[dynamicFormField.name] = dynamicFormField;
|
||||
|
||||
const initialValue = getInitialValue(dynamicFormField.name);
|
||||
if(initialValue != null)
|
||||
{
|
||||
console.log(`@dk trying to set an initial value [${dynamicFormField.name}] to [${initialValue}]`);
|
||||
// @ts-ignore some any
|
||||
formikProps.initialValues[dynamicFormField.name] = initialValue;
|
||||
}
|
||||
}
|
||||
|
||||
if(formData.values)
|
||||
{
|
||||
checkForFormValueChanges(formikProps);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<QDynamicForm formData={formData} record={record} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function renderViewForm()
|
||||
{
|
||||
const fieldNames: string[] = [];
|
||||
const fieldMap: {[name: string]: QFieldMetaData} = {};
|
||||
const fakeRecord = new QRecord(widgetData.recordOfFieldValues ?? {});
|
||||
|
||||
const mergedDynamicFormValuesIntoFieldName = widgetData.mergedDynamicFormValuesIntoFieldName;
|
||||
|
||||
for (let i = 0; i < fields?.length; i++)
|
||||
{
|
||||
const fieldName = fields[i].name;
|
||||
fieldNames.push(fieldName);
|
||||
fieldMap[fieldName] = fields[i];
|
||||
|
||||
if(mergedDynamicFormValuesIntoFieldName && recordValues[mergedDynamicFormValuesIntoFieldName])
|
||||
{
|
||||
fakeRecord.values.set(fieldName, recordValues[mergedDynamicFormValuesIntoFieldName][fieldName]);
|
||||
}
|
||||
}
|
||||
|
||||
const section = renderSectionOfFields(`dynamicFormWidget:${widgetMetaData.name}`, fieldNames, null, false, fakeRecord, fieldMap);
|
||||
|
||||
return (<Box>
|
||||
{section}
|
||||
</Box>);
|
||||
}
|
||||
|
||||
|
||||
////////////
|
||||
// render //
|
||||
////////////
|
||||
return (<Widget widgetMetaData={widgetMetaData}>
|
||||
{
|
||||
<React.Fragment>
|
||||
{effectiveIsEditable ? renderEditForm() : renderViewForm()}
|
||||
</React.Fragment>
|
||||
}
|
||||
</Widget>);
|
||||
}
|
||||
|
450
src/qqq/components/widgets/misc/FilterAndColumnsSetupWidget.tsx
Normal file
450
src/qqq/components/widgets/misc/FilterAndColumnsSetupWidget.tsx
Normal file
@ -0,0 +1,450 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
|
||||
import {QCriteriaOperator} from "@kingsrook/qqq-frontend-core/lib/model/query/QCriteriaOperator";
|
||||
import {QFilterCriteria} from "@kingsrook/qqq-frontend-core/lib/model/query/QFilterCriteria";
|
||||
import {QFilterOrderBy} from "@kingsrook/qqq-frontend-core/lib/model/query/QFilterOrderBy";
|
||||
import {QQueryFilter} from "@kingsrook/qqq-frontend-core/lib/model/query/QQueryFilter";
|
||||
import {Alert, Collapse} from "@mui/material";
|
||||
import Box from "@mui/material/Box";
|
||||
import Button from "@mui/material/Button";
|
||||
import Card from "@mui/material/Card";
|
||||
import Modal from "@mui/material/Modal";
|
||||
import Tooltip from "@mui/material/Tooltip/Tooltip";
|
||||
import QContext from "QContext";
|
||||
import colors from "qqq/assets/theme/base/colors";
|
||||
import {QCancelButton, QSaveButton} from "qqq/components/buttons/DefaultButtons";
|
||||
import HelpContent, {hasHelpContent} from "qqq/components/misc/HelpContent";
|
||||
import AdvancedQueryPreview from "qqq/components/query/AdvancedQueryPreview";
|
||||
import {getCurrentSortIndicator} from "qqq/components/query/BasicAndAdvancedQueryControls";
|
||||
import Widget, {HeaderLinkButtonComponent} from "qqq/components/widgets/Widget";
|
||||
import QQueryColumns, {Column} from "qqq/models/query/QQueryColumns";
|
||||
import RecordQuery from "qqq/pages/records/query/RecordQuery";
|
||||
import Client from "qqq/utils/qqq/Client";
|
||||
import FilterUtils from "qqq/utils/qqq/FilterUtils";
|
||||
import React, {useContext, useEffect, useRef, useState} from "react";
|
||||
|
||||
interface FilterAndColumnsSetupWidgetProps
|
||||
{
|
||||
isEditable: boolean;
|
||||
widgetMetaData: QWidgetMetaData;
|
||||
recordValues: { [name: string]: any };
|
||||
onSaveCallback?: (values: { [name: string]: any }) => void;
|
||||
}
|
||||
|
||||
FilterAndColumnsSetupWidget.defaultProps = {
|
||||
onSaveCallback: null
|
||||
};
|
||||
|
||||
export const buttonSX =
|
||||
{
|
||||
border: `1px solid ${colors.grayLines.main} !important`,
|
||||
borderRadius: "0.75rem",
|
||||
textTransform: "none",
|
||||
fontSize: "1rem",
|
||||
fontWeight: "400",
|
||||
paddingLeft: "1rem",
|
||||
paddingRight: "1rem",
|
||||
opacity: "1",
|
||||
color: colors.dark.main,
|
||||
"&:hover": {color: colors.dark.main},
|
||||
"&:focus": {color: colors.dark.main},
|
||||
"&:focus:not(:hover)": {color: colors.dark.main},
|
||||
};
|
||||
|
||||
export const unborderedButtonSX = Object.assign({}, buttonSX);
|
||||
unborderedButtonSX.border = "none !important";
|
||||
unborderedButtonSX.opacity = "0.7";
|
||||
|
||||
|
||||
const qController = Client.getInstance();
|
||||
|
||||
/*******************************************************************************
|
||||
** Component for editing the main setup of a report - that is: filter & columns
|
||||
*******************************************************************************/
|
||||
export default function FilterAndColumnsSetupWidget({isEditable, widgetMetaData, recordValues, onSaveCallback}: FilterAndColumnsSetupWidgetProps): JSX.Element
|
||||
{
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [hideColumns, setHideColumns] = useState(widgetMetaData?.defaultValues?.has("hideColumns") && widgetMetaData?.defaultValues?.get("hideColumns"));
|
||||
const [tableMetaData, setTableMetaData] = useState(null as QTableMetaData);
|
||||
|
||||
const [alertContent, setAlertContent] = useState(null as string);
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// we'll actually keep 2 copies of the query filter around here - //
|
||||
// the one in the record (as json) is one that the backend likes (e.g., possible values as ids) //
|
||||
// this "frontend" one is one that the frontend can use (possible values as objects w/ labels). //
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
const [frontendQueryFilter, setFrontendQueryFilter] = useState(null as QQueryFilter);
|
||||
|
||||
const {helpHelpActive} = useContext(QContext);
|
||||
|
||||
const recordQueryRef = useRef();
|
||||
|
||||
/////////////////////////////
|
||||
// load values from record //
|
||||
/////////////////////////////
|
||||
let columns: QQueryColumns = null;
|
||||
let usingDefaultEmptyFilter = false;
|
||||
let queryFilter = recordValues["queryFilterJson"] && JSON.parse(recordValues["queryFilterJson"]) as QQueryFilter;
|
||||
if (!queryFilter)
|
||||
{
|
||||
queryFilter = new QQueryFilter();
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// if there is no queryFilter provided, see if there are default fields from which a query should be seeded //
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
const defaultFilterFields = getDefaultFilterFieldNames(widgetMetaData);
|
||||
if (defaultFilterFields?.length > 0)
|
||||
{
|
||||
defaultFilterFields.forEach((fieldName: string) =>
|
||||
{
|
||||
if (recordValues[fieldName])
|
||||
{
|
||||
queryFilter.addCriteria(new QFilterCriteria(fieldName, QCriteriaOperator.EQUALS, [recordValues[fieldName]]));
|
||||
}
|
||||
});
|
||||
|
||||
queryFilter.addOrderBy(new QFilterOrderBy("id", false));
|
||||
queryFilter = Object.assign({}, queryFilter);
|
||||
}
|
||||
else
|
||||
{
|
||||
usingDefaultEmptyFilter = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (recordValues["columnsJson"])
|
||||
{
|
||||
columns = QQueryColumns.buildFromJSON(recordValues["columnsJson"]);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// load tableMetaData initially, and if/when selected table changes //
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
useEffect(() =>
|
||||
{
|
||||
////////////////////////////////////////////////////////////////////////////////////////
|
||||
// if a default table name specified, use it, otherwise use it from the record values //
|
||||
////////////////////////////////////////////////////////////////////////////////////////
|
||||
let tableName = widgetMetaData?.defaultValues?.get("tableName");
|
||||
if (!tableName && recordValues["tableName"] && (tableMetaData == null || tableMetaData.name != recordValues["tableName"]))
|
||||
{
|
||||
tableName = recordValues["tableName"];
|
||||
}
|
||||
|
||||
if (tableName)
|
||||
{
|
||||
(async () =>
|
||||
{
|
||||
const tableMetaData = await qController.loadTableMetaData(tableName);
|
||||
setTableMetaData(tableMetaData);
|
||||
|
||||
const queryFilterForFrontend = Object.assign({}, queryFilter);
|
||||
await FilterUtils.cleanupValuesInFilerFromQueryString(qController, tableMetaData, queryFilterForFrontend);
|
||||
setFrontendQueryFilter(queryFilterForFrontend);
|
||||
})();
|
||||
}
|
||||
}, [JSON.stringify(recordValues)]);
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function getDefaultFilterFieldNames(widgetMetaData: QWidgetMetaData)
|
||||
{
|
||||
if (widgetMetaData?.defaultValues?.has("filterDefaultFieldNames"))
|
||||
{
|
||||
return (widgetMetaData.defaultValues.get("filterDefaultFieldNames").split(","));
|
||||
}
|
||||
|
||||
return ([]);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function openEditor()
|
||||
{
|
||||
let missingRequiredFields = [] as string[];
|
||||
getDefaultFilterFieldNames(widgetMetaData)?.forEach((fieldName: string) =>
|
||||
{
|
||||
if (!recordValues[fieldName])
|
||||
{
|
||||
missingRequiredFields.push(tableMetaData.fields.get(fieldName).label);
|
||||
}
|
||||
});
|
||||
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// display an alert and return if any required fields are missing //
|
||||
////////////////////////////////////////////////////////////////////
|
||||
if (missingRequiredFields.length > 0)
|
||||
{
|
||||
setAlertContent("The following fields must first be selected to add Additional Order Filters: '" + missingRequiredFields.join(", ") + "'");
|
||||
return;
|
||||
}
|
||||
|
||||
if (recordValues["tableName"])
|
||||
{
|
||||
setAlertContent(null);
|
||||
setModalOpen(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function saveClicked()
|
||||
{
|
||||
if (!onSaveCallback)
|
||||
{
|
||||
console.log("onSaveCallback was not defined");
|
||||
return;
|
||||
}
|
||||
|
||||
// @ts-ignore possibly 'undefined'.
|
||||
const view = recordQueryRef?.current?.getCurrentView();
|
||||
|
||||
view.queryColumns.sortColumnsFixingPinPositions();
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// keep the query filter that came from the recordQuery screen as the front-end version (w/ possible value objects) //
|
||||
// but prep a copy of it for the backend, to stringify as json in the record being edited //
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
setFrontendQueryFilter(view.queryFilter);
|
||||
const filter = FilterUtils.prepQueryFilterForBackend(tableMetaData, view.queryFilter);
|
||||
|
||||
onSaveCallback({queryFilterJson: JSON.stringify(filter), columnsJson: JSON.stringify(view.queryColumns)});
|
||||
|
||||
closeEditor();
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function closeEditor(event?: {}, reason?: "backdropClick" | "escapeKeyDown")
|
||||
{
|
||||
if (reason == "backdropClick" || reason == "escapeKeyDown")
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
setModalOpen(false);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function renderColumn(column: Column): JSX.Element
|
||||
{
|
||||
const [field, table] = FilterUtils.getField(tableMetaData, column.name);
|
||||
|
||||
if (!column || !column.isVisible || column.name == "__check__" || !field)
|
||||
{
|
||||
return (<React.Fragment />);
|
||||
}
|
||||
|
||||
const tableLabelPart = table.name != tableMetaData.name ? table.label + ": " : "";
|
||||
|
||||
return (<Box mr="0.375rem" mb="0.5rem" border={`1px solid ${colors.grayLines.main}`} borderRadius="0.75rem" p="0.25rem 0.75rem">
|
||||
{tableLabelPart}{field.label}
|
||||
</Box>);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function mayShowQueryPreview(): boolean
|
||||
{
|
||||
if (tableMetaData)
|
||||
{
|
||||
if (frontendQueryFilter?.criteria?.length > 0 || frontendQueryFilter?.subFilters?.length > 0)
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
}
|
||||
|
||||
return (false);
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function mayShowColumnsPreview(): boolean
|
||||
{
|
||||
if (tableMetaData)
|
||||
{
|
||||
for (let i = 0; i < columns?.columns?.length; i++)
|
||||
{
|
||||
if (columns.columns[i].isVisible && columns.columns[i].name != "__check__")
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (false);
|
||||
}
|
||||
|
||||
const helpRoles = isEditable ? [recordValues["id"] ? "EDIT_SCREEN" : "INSERT_SCREEN", "WRITE_SCREENS", "ALL_SCREENS"] : ["VIEW_SCREEN", "READ_SCREENS", "ALL_SCREENS"];
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function showHelp(slot: string)
|
||||
{
|
||||
return (helpHelpActive || hasHelpContent(widgetMetaData?.helpContent?.get(slot), helpRoles));
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function getHelpContent(slot: string)
|
||||
{
|
||||
const key = `widget:${widgetMetaData.name};slot:${slot}`;
|
||||
return <HelpContent helpContents={widgetMetaData?.helpContent?.get(slot)} roles={helpRoles} helpContentKey={key} />;
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////
|
||||
// add link to widget header for opening modal //
|
||||
/////////////////////////////////////////////////
|
||||
const selectTableFirstTooltipTitle = tableMetaData ? null : "You must select a table before you can set up your report filters and columns";
|
||||
const labelAdditionalElementsRight: JSX.Element[] = [];
|
||||
if (isEditable)
|
||||
{
|
||||
if (!hideColumns)
|
||||
{
|
||||
labelAdditionalElementsRight.push(<HeaderLinkButtonComponent key="filterAndColumnsHeader" label="Edit Filters and Columns" onClickCallback={openEditor} disabled={tableMetaData == null} disabledTooltip={selectTableFirstTooltipTitle} />);
|
||||
}
|
||||
else
|
||||
{
|
||||
labelAdditionalElementsRight.push(<HeaderLinkButtonComponent key="filterAndColumnsHeader" label="Edit Filters" onClickCallback={openEditor} disabled={tableMetaData == null} disabledTooltip={selectTableFirstTooltipTitle} />);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return (<Widget widgetMetaData={widgetMetaData} labelAdditionalElementsRight={labelAdditionalElementsRight}>
|
||||
<React.Fragment>
|
||||
{
|
||||
showHelp("sectionSubhead") &&
|
||||
<Box color={colors.gray.main} pb={"0.5rem"} fontSize={"0.875rem"}>
|
||||
{getHelpContent("sectionSubhead")}
|
||||
</Box>
|
||||
}
|
||||
<Collapse in={Boolean(alertContent)}>
|
||||
<Alert severity="error" sx={{mt: 1.5, mb: 0.5}} onClose={() => setAlertContent(null)}>{alertContent}</Alert>
|
||||
</Collapse>
|
||||
<Box pt="0.5rem">
|
||||
<Box display="flex" justifyContent="space-between" alignItems="center">
|
||||
<h5>Query Filter</h5>
|
||||
<Box fontSize="0.75rem" fontWeight="700">{mayShowQueryPreview() && getCurrentSortIndicator(frontendQueryFilter, tableMetaData, null)}</Box>
|
||||
</Box>
|
||||
{
|
||||
mayShowQueryPreview() &&
|
||||
<AdvancedQueryPreview tableMetaData={tableMetaData} queryFilter={frontendQueryFilter} isEditable={false} isQueryTooComplex={frontendQueryFilter.subFilters?.length > 0} removeCriteriaByIndexCallback={null} />
|
||||
}
|
||||
{
|
||||
!mayShowQueryPreview() &&
|
||||
<Box width="100%" sx={{fontSize: "1rem", background: "#FFFFFF"}} minHeight={"2.5rem"} p={"0.5rem"} pb={"0.125rem"} borderRadius="0.75rem" border={`1px solid ${colors.grayLines.main}`}>
|
||||
{
|
||||
isEditable &&
|
||||
<Tooltip title={selectTableFirstTooltipTitle}>
|
||||
<span><Button disabled={!recordValues["tableName"]} sx={{mb: "0.125rem", ...unborderedButtonSX}} onClick={openEditor}>+ Add Filters</Button></span>
|
||||
</Tooltip>
|
||||
}
|
||||
{
|
||||
!isEditable && <Box color={colors.gray.main}>No filters are configured.</Box>
|
||||
}
|
||||
</Box>
|
||||
}
|
||||
</Box>
|
||||
{!hideColumns && (
|
||||
<Box pt="1rem">
|
||||
<h5>Columns</h5>
|
||||
<Box display="flex" flexWrap="wrap" fontSize="1rem">
|
||||
{
|
||||
mayShowColumnsPreview() &&
|
||||
columns.columns.map((column, i) => <React.Fragment key={`column-${i}`}>{renderColumn(column)}</React.Fragment>)
|
||||
}
|
||||
{
|
||||
!mayShowColumnsPreview() &&
|
||||
<Box width="100%" sx={{fontSize: "1rem", background: "#FFFFFF"}} minHeight={"2.375rem"} p={"0.5rem"} pb={"0.125rem"}>
|
||||
{
|
||||
isEditable &&
|
||||
<Tooltip title={selectTableFirstTooltipTitle}>
|
||||
<span><Button disabled={!recordValues["tableName"]} sx={unborderedButtonSX} onClick={openEditor}>+ Add Columns</Button></span>
|
||||
</Tooltip>
|
||||
}
|
||||
{
|
||||
!isEditable && <Box color={colors.gray.main}>No columns are selected.</Box>
|
||||
}
|
||||
</Box>
|
||||
}
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
{
|
||||
modalOpen &&
|
||||
<Modal open={modalOpen} onClose={(event, reason) => closeEditor(event, reason)}>
|
||||
<div>
|
||||
<Box sx={{position: "absolute", overflowY: "auto", maxHeight: "100%", width: "100%"}}>
|
||||
<Card sx={{m: "2rem", p: "2rem"}}>
|
||||
<h3>Edit Filters and Columns</h3>
|
||||
{
|
||||
showHelp("modalSubheader") &&
|
||||
<Box color={colors.gray.main} pb={"0.5rem"}>
|
||||
{getHelpContent("modalSubheader")}
|
||||
</Box>
|
||||
}
|
||||
{
|
||||
tableMetaData && <RecordQuery
|
||||
ref={recordQueryRef}
|
||||
table={tableMetaData}
|
||||
usage="reportSetup"
|
||||
isModal={true}
|
||||
initialQueryFilter={usingDefaultEmptyFilter ? null : frontendQueryFilter}
|
||||
initialColumns={columns}
|
||||
/>
|
||||
}
|
||||
|
||||
<Box>
|
||||
<Box display="flex" justifyContent="flex-end">
|
||||
<QCancelButton disabled={false} onClickHandler={closeEditor} />
|
||||
<QSaveButton label="OK" iconName="check" disabled={false} onClickHandler={saveClicked} />
|
||||
</Box>
|
||||
</Box>
|
||||
</Card>
|
||||
</Box>
|
||||
</div>
|
||||
</Modal>
|
||||
}
|
||||
</React.Fragment>
|
||||
</Widget>);
|
||||
}
|
209
src/qqq/components/widgets/misc/PivotTableGroupByElement.tsx
Normal file
209
src/qqq/components/widgets/misc/PivotTableGroupByElement.tsx
Normal file
@ -0,0 +1,209 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
import {QInstance} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QInstance";
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import Box from "@mui/material/Box";
|
||||
import Button from "@mui/material/Button";
|
||||
import Icon from "@mui/material/Icon";
|
||||
import type {Identifier, XYCoord} from "dnd-core";
|
||||
import colors from "qqq/assets/theme/base/colors";
|
||||
import FieldAutoComplete from "qqq/components/misc/FieldAutoComplete";
|
||||
import {DragItemTypes, fieldAutoCompleteTextFieldSX, getSelectedFieldForAutoComplete, xIconButtonSX} from "qqq/components/widgets/misc/PivotTableSetupWidget";
|
||||
import {PivotTableDefinition, PivotTableGroupBy} from "qqq/models/misc/PivotTableDefinitionModels";
|
||||
import React, {FC, useRef} from "react";
|
||||
import {useDrag, useDrop} from "react-dnd";
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** component props
|
||||
*******************************************************************************/
|
||||
export interface PivotTableGroupByElementProps
|
||||
{
|
||||
id: string;
|
||||
index: number;
|
||||
dragCallback: (rowsOrColumns: "rows" | "columns", dragIndex: number, hoverIndex: number) => void;
|
||||
metaData: QInstance;
|
||||
tableMetaData: QTableMetaData;
|
||||
pivotTableDefinition: PivotTableDefinition;
|
||||
usedGroupByFieldNames: string[];
|
||||
availableFieldNames: string[];
|
||||
isEditable: boolean;
|
||||
groupBy: PivotTableGroupBy;
|
||||
rowsOrColumns: "rows" | "columns";
|
||||
callback: () => void;
|
||||
attemptedSubmit?: boolean;
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** item to support react-dnd
|
||||
*******************************************************************************/
|
||||
interface DragItem
|
||||
{
|
||||
index: number;
|
||||
id: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
export const PivotTableGroupByElement: FC<PivotTableGroupByElementProps> = ({id, index, dragCallback, rowsOrColumns, metaData, tableMetaData, pivotTableDefinition, groupBy, usedGroupByFieldNames, availableFieldNames, isEditable, callback, attemptedSubmit}) =>
|
||||
{
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// credit: https://react-dnd.github.io/react-dnd/examples/sortable/simple //
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [{handlerId}, drop] = useDrop<DragItem, void, { handlerId: Identifier | null }>(
|
||||
{
|
||||
accept: rowsOrColumns == "rows" ? DragItemTypes.ROW : DragItemTypes.COLUMN,
|
||||
collect(monitor)
|
||||
{
|
||||
return {
|
||||
handlerId: monitor.getHandlerId(),
|
||||
};
|
||||
},
|
||||
hover(item: DragItem, monitor)
|
||||
{
|
||||
if (!ref.current)
|
||||
{
|
||||
return;
|
||||
}
|
||||
const dragIndex = item.index;
|
||||
const hoverIndex = index;
|
||||
|
||||
// Don't replace items with themselves
|
||||
if (dragIndex === hoverIndex)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine rectangle on screen
|
||||
const hoverBoundingRect = ref.current?.getBoundingClientRect();
|
||||
|
||||
// Get vertical middle
|
||||
const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
|
||||
|
||||
// Determine mouse position
|
||||
const clientOffset = monitor.getClientOffset();
|
||||
|
||||
// Get pixels to the top
|
||||
const hoverClientY = (clientOffset as XYCoord).y - hoverBoundingRect.top;
|
||||
|
||||
// Only perform the move when the mouse has crossed half of the items height
|
||||
// When dragging downwards, only move when the cursor is below 50%
|
||||
// When dragging upwards, only move when the cursor is above 50%
|
||||
|
||||
// Dragging downwards
|
||||
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Dragging upwards
|
||||
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Time to actually perform the action
|
||||
dragCallback(rowsOrColumns, dragIndex, hoverIndex);
|
||||
|
||||
// Note: we're mutating the monitor item here! Generally it's better to avoid mutations,
|
||||
// but it's good here for the sake of performance to avoid expensive index searches.
|
||||
item.index = hoverIndex;
|
||||
},
|
||||
});
|
||||
|
||||
const [{isDragging}, drag, preview] = useDrag({
|
||||
type: rowsOrColumns == "rows" ? DragItemTypes.ROW : DragItemTypes.COLUMN,
|
||||
item: () =>
|
||||
{
|
||||
return {id, index};
|
||||
},
|
||||
collect: (monitor: any) => ({
|
||||
isDragging: monitor.isDragging(),
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
const handleFieldChange = (event: any, newValue: any, reason: string) =>
|
||||
{
|
||||
groupBy.fieldName = newValue ? newValue.fieldName : null;
|
||||
callback();
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function removeGroupBy(index: number, rowsOrColumns: "rows" | "columns")
|
||||
{
|
||||
pivotTableDefinition[rowsOrColumns].splice(index, 1);
|
||||
callback();
|
||||
}
|
||||
|
||||
if (!isEditable)
|
||||
{
|
||||
const selectedField = getSelectedFieldForAutoComplete(tableMetaData, groupBy.fieldName);
|
||||
if (selectedField)
|
||||
{
|
||||
const label = selectedField.table.name == tableMetaData.name ? selectedField.field.label : selectedField.table.label + ": " + selectedField.field.label;
|
||||
return (<Box><Box display="inline-block" mr="0.375rem" mb="0.5rem" border={`1px solid ${colors.grayLines.main}`} borderRadius="0.75rem" p="0.25rem 0.75rem">{label}</Box></Box>);
|
||||
}
|
||||
|
||||
return (<React.Fragment />);
|
||||
}
|
||||
|
||||
preview(drop(ref));
|
||||
|
||||
const showError = attemptedSubmit && !groupBy.fieldName;
|
||||
|
||||
return (<Box ref={ref} display="flex" p="0.5rem" pl="0" gap="0.5rem" alignItems="center" sx={{backgroundColor: "white", opacity: isDragging ? 0 : 1}} data-handler-id={handlerId}>
|
||||
<Box>
|
||||
<Icon ref={drag} sx={{cursor: "ns-resize"}}>drag_indicator</Icon>
|
||||
</Box>
|
||||
<Box width="100%">
|
||||
<FieldAutoComplete
|
||||
id={`${rowsOrColumns}-${index}`}
|
||||
label={null}
|
||||
variant="outlined"
|
||||
textFieldSX={fieldAutoCompleteTextFieldSX}
|
||||
metaData={metaData}
|
||||
tableMetaData={tableMetaData}
|
||||
handleFieldChange={handleFieldChange}
|
||||
hiddenFieldNames={usedGroupByFieldNames}
|
||||
availableFieldNames={availableFieldNames}
|
||||
defaultValue={getSelectedFieldForAutoComplete(tableMetaData, groupBy.fieldName)}
|
||||
hasError={showError}
|
||||
noOptionsText="There are no fields available."
|
||||
/>
|
||||
</Box>
|
||||
<Box>
|
||||
<Button sx={xIconButtonSX} onClick={() => removeGroupBy(index, rowsOrColumns)}><Icon>clear</Icon></Button>
|
||||
</Box>
|
||||
</Box>);
|
||||
};
|
870
src/qqq/components/widgets/misc/PivotTableSetupWidget.tsx
Normal file
870
src/qqq/components/widgets/misc/PivotTableSetupWidget.tsx
Normal file
@ -0,0 +1,870 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
import {QInstance} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QInstance";
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import Autocomplete from "@mui/material/Autocomplete";
|
||||
import Box from "@mui/material/Box";
|
||||
import Button from "@mui/material/Button";
|
||||
import Card from "@mui/material/Card";
|
||||
import Grid from "@mui/material/Grid";
|
||||
import Icon from "@mui/material/Icon";
|
||||
import Modal from "@mui/material/Modal";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import Tooltip from "@mui/material/Tooltip/Tooltip";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import QContext from "QContext";
|
||||
import colors from "qqq/assets/theme/base/colors";
|
||||
import {QCancelButton, QSaveButton} from "qqq/components/buttons/DefaultButtons";
|
||||
import FieldAutoComplete from "qqq/components/misc/FieldAutoComplete";
|
||||
import HelpContent, {hasHelpContent} from "qqq/components/misc/HelpContent";
|
||||
import {buttonSX, unborderedButtonSX} from "qqq/components/widgets/misc/FilterAndColumnsSetupWidget";
|
||||
import {PivotTableGroupByElement} from "qqq/components/widgets/misc/PivotTableGroupByElement";
|
||||
import {PivotTableValueElement} from "qqq/components/widgets/misc/PivotTableValueElement";
|
||||
import Widget, {HeaderToggleComponent} from "qqq/components/widgets/Widget";
|
||||
import {PivotObjectKey, PivotTableDefinition, PivotTableFunction, pivotTableFunctionLabels, PivotTableGroupBy, PivotTableValue} from "qqq/models/misc/PivotTableDefinitionModels";
|
||||
import QQueryColumns from "qqq/models/query/QQueryColumns";
|
||||
import Client from "qqq/utils/qqq/Client";
|
||||
import FilterUtils from "qqq/utils/qqq/FilterUtils";
|
||||
import React, {useCallback, useContext, useEffect, useReducer, useState} from "react";
|
||||
import {DndProvider} from "react-dnd";
|
||||
import {HTML5Backend} from "react-dnd-html5-backend";
|
||||
|
||||
export const DragItemTypes =
|
||||
{
|
||||
ROW: "row",
|
||||
COLUMN: "column",
|
||||
VALUE: "value"
|
||||
};
|
||||
|
||||
export const xIconButtonSX =
|
||||
{
|
||||
border: `1px solid ${colors.grayLines.main} !important`,
|
||||
borderRadius: "0.75rem",
|
||||
textTransform: "none",
|
||||
fontSize: "1rem",
|
||||
fontWeight: "400",
|
||||
width: "40px",
|
||||
minWidth: "40px",
|
||||
paddingLeft: 0,
|
||||
paddingRight: 0,
|
||||
color: colors.error.main,
|
||||
"&:hover": {color: colors.error.main},
|
||||
"&:focus": {color: colors.error.main},
|
||||
"&:focus:not(:hover)": {color: colors.error.main},
|
||||
};
|
||||
|
||||
export const fieldAutoCompleteTextFieldSX =
|
||||
{
|
||||
"& .MuiInputBase-input": {fontSize: "1rem", padding: "0 !important"}
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
export function getSelectedFieldForAutoComplete(tableMetaData: QTableMetaData, fieldName: string)
|
||||
{
|
||||
if (fieldName)
|
||||
{
|
||||
let [field, fieldTable] = FilterUtils.getField(tableMetaData, fieldName);
|
||||
if (field && fieldTable)
|
||||
{
|
||||
return ({field: field, table: fieldTable, fieldName: fieldName});
|
||||
}
|
||||
}
|
||||
|
||||
return (null);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** component props
|
||||
*******************************************************************************/
|
||||
interface PivotTableSetupWidgetProps
|
||||
{
|
||||
isEditable: boolean;
|
||||
widgetMetaData: QWidgetMetaData;
|
||||
recordValues: { [name: string]: any };
|
||||
onSaveCallback?: (values: { [name: string]: any }) => void;
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** default values for props
|
||||
*******************************************************************************/
|
||||
PivotTableSetupWidget.defaultProps = {
|
||||
onSaveCallback: null
|
||||
};
|
||||
|
||||
|
||||
const qController = Client.getInstance();
|
||||
|
||||
/*******************************************************************************
|
||||
** Component to edit the setup of a Pivot Table - rows, columns, values!
|
||||
*******************************************************************************/
|
||||
export default function PivotTableSetupWidget({isEditable, widgetMetaData, recordValues, onSaveCallback}: PivotTableSetupWidgetProps): JSX.Element
|
||||
{
|
||||
const [metaData, setMetaData] = useState(null as QInstance);
|
||||
const [tableMetaData, setTableMetaData] = useState(null as QTableMetaData);
|
||||
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [enabled, setEnabled] = useState(!!recordValues["usePivotTable"]);
|
||||
const [attemptedSubmit, setAttemptedSubmit] = useState(false);
|
||||
const [errorAlert, setErrorAlert] = useState(null as string);
|
||||
|
||||
const [pivotTableDefinition, setPivotTableDefinition] = useState(null as PivotTableDefinition);
|
||||
|
||||
const [, forceUpdate] = useReducer((x) => x + 1, 0);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// this is a copy of pivotTableDefinition, that we'll render in the modal. //
|
||||
// then on-save, we'll move it to pivotTableDefinition, e.g., the actual record. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
const [modalPivotTableDefinition, setModalPivotTableDefinition] = useState(null as PivotTableDefinition);
|
||||
|
||||
const [usedGroupByFieldNames, setUsedGroupByFieldNames] = useState([] as string[]);
|
||||
const [usedValueFieldNames, setUsedValueByFieldNames] = useState([] as string[]);
|
||||
const [availableFieldNames, setAvailableFieldNames] = useState([] as string[]);
|
||||
|
||||
const {helpHelpActive} = useContext(QContext);
|
||||
|
||||
//////////////////
|
||||
// initial load //
|
||||
//////////////////
|
||||
useEffect(() =>
|
||||
{
|
||||
if (!pivotTableDefinition)
|
||||
{
|
||||
let originalPivotTableDefinition = recordValues["pivotTableJson"] && JSON.parse(recordValues["pivotTableJson"]) as PivotTableDefinition;
|
||||
if (originalPivotTableDefinition)
|
||||
{
|
||||
setEnabled(true);
|
||||
}
|
||||
else if (!originalPivotTableDefinition)
|
||||
{
|
||||
originalPivotTableDefinition = new PivotTableDefinition();
|
||||
}
|
||||
|
||||
for (let i = 0; i < originalPivotTableDefinition?.rows?.length; i++)
|
||||
{
|
||||
if (!originalPivotTableDefinition?.rows[i].key)
|
||||
{
|
||||
originalPivotTableDefinition.rows[i].key = PivotObjectKey.next();
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < originalPivotTableDefinition?.columns?.length; i++)
|
||||
{
|
||||
if (!originalPivotTableDefinition?.columns[i].key)
|
||||
{
|
||||
originalPivotTableDefinition.columns[i].key = PivotObjectKey.next();
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < originalPivotTableDefinition?.values?.length; i++)
|
||||
{
|
||||
if (!originalPivotTableDefinition?.values[i].key)
|
||||
{
|
||||
originalPivotTableDefinition.values[i].key = PivotObjectKey.next();
|
||||
}
|
||||
}
|
||||
|
||||
setPivotTableDefinition(originalPivotTableDefinition);
|
||||
updateUsedGroupByFieldNames(originalPivotTableDefinition);
|
||||
updateUsedValueFieldNames(modalPivotTableDefinition);
|
||||
}
|
||||
|
||||
if (recordValues["columnsJson"])
|
||||
{
|
||||
updateAvailableFieldNames(JSON.parse(recordValues["columnsJson"]) as QQueryColumns);
|
||||
}
|
||||
|
||||
(async () =>
|
||||
{
|
||||
setMetaData(await qController.loadMetaData());
|
||||
})();
|
||||
});
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// handle the table name changing - load current table's meta-data //
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
useEffect(() =>
|
||||
{
|
||||
if (recordValues["tableName"] && (tableMetaData == null || tableMetaData.name != recordValues["tableName"]))
|
||||
{
|
||||
(async () =>
|
||||
{
|
||||
const tableMetaData = await qController.loadTableMetaData(recordValues["tableName"]);
|
||||
setTableMetaData(tableMetaData);
|
||||
})();
|
||||
}
|
||||
}, [recordValues]);
|
||||
|
||||
|
||||
const helpRoles = isEditable ? [recordValues["id"] ? "EDIT_SCREEN" : "INSERT_SCREEN", "WRITE_SCREENS", "ALL_SCREENS"] : ["VIEW_SCREEN", "READ_SCREENS", "ALL_SCREENS"];
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function showHelp(slot: string)
|
||||
{
|
||||
return (helpHelpActive || hasHelpContent(widgetMetaData?.helpContent?.get(slot), helpRoles));
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function getHelpContent(slot: string)
|
||||
{
|
||||
const key = `widget:${widgetMetaData.name};slot:${slot}`;
|
||||
return <HelpContent helpContents={widgetMetaData?.helpContent?.get(slot)} roles={helpRoles} helpContentKey={key} />;
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function toggleEnabled()
|
||||
{
|
||||
const newEnabled = !!!getEnabled();
|
||||
setEnabled(newEnabled);
|
||||
onSaveCallback({usePivotTable: newEnabled});
|
||||
|
||||
if (!newEnabled)
|
||||
{
|
||||
onSaveCallback({pivotTableJson: null});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function getEnabled()
|
||||
{
|
||||
return (enabled);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function addGroupBy(rowsOrColumns: "rows" | "columns")
|
||||
{
|
||||
if (!modalPivotTableDefinition[rowsOrColumns])
|
||||
{
|
||||
modalPivotTableDefinition[rowsOrColumns] = [];
|
||||
}
|
||||
|
||||
modalPivotTableDefinition[rowsOrColumns].push(new PivotTableGroupBy());
|
||||
validateForm();
|
||||
forceUpdate();
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function childElementChangedCallback()
|
||||
{
|
||||
updateUsedGroupByFieldNames(modalPivotTableDefinition);
|
||||
updateUsedValueFieldNames(modalPivotTableDefinition);
|
||||
validateForm();
|
||||
forceUpdate();
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function addValue()
|
||||
{
|
||||
if (!modalPivotTableDefinition.values)
|
||||
{
|
||||
modalPivotTableDefinition.values = [];
|
||||
}
|
||||
|
||||
modalPivotTableDefinition.values.push(new PivotTableValue());
|
||||
validateForm();
|
||||
forceUpdate();
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function removeValue(index: number)
|
||||
{
|
||||
modalPivotTableDefinition.values.splice(index, 1);
|
||||
validateForm();
|
||||
forceUpdate();
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function updateUsedGroupByFieldNames(ptd: PivotTableDefinition = pivotTableDefinition)
|
||||
{
|
||||
const usedFieldNames: string[] = [];
|
||||
|
||||
for (let i = 0; i < ptd?.rows?.length; i++)
|
||||
{
|
||||
usedFieldNames.push(ptd?.rows[i].fieldName);
|
||||
}
|
||||
|
||||
for (let i = 0; i < ptd?.columns?.length; i++)
|
||||
{
|
||||
usedFieldNames.push(ptd?.columns[i].fieldName);
|
||||
}
|
||||
|
||||
setUsedGroupByFieldNames(usedFieldNames);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function updateUsedValueFieldNames(ptd: PivotTableDefinition = pivotTableDefinition)
|
||||
{
|
||||
const usedFieldNames: string[] = [];
|
||||
|
||||
for (let i = 0; i < ptd?.values?.length; i++)
|
||||
{
|
||||
usedFieldNames.push(ptd?.values[i].fieldName);
|
||||
}
|
||||
|
||||
setUsedValueByFieldNames(usedFieldNames);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function updateAvailableFieldNames(columns: QQueryColumns)
|
||||
{
|
||||
const fieldNames: string[] = [];
|
||||
for (let i = 0; i < columns?.columns?.length; i++)
|
||||
{
|
||||
if (columns.columns[i].isVisible)
|
||||
{
|
||||
fieldNames.push(columns.columns[i].name);
|
||||
}
|
||||
}
|
||||
setAvailableFieldNames(fieldNames);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function renderOneValue(value: PivotTableValue, index: number)
|
||||
{
|
||||
if (!isEditable)
|
||||
{
|
||||
const selectedField = getSelectedFieldForAutoComplete(tableMetaData, value.fieldName);
|
||||
if (selectedField && value.function)
|
||||
{
|
||||
const label = selectedField.table.name == tableMetaData.name ? selectedField.field.label : selectedField.table.label + ": " + selectedField.field.label;
|
||||
return (<Box mr="0.375rem" mb="0.5rem" border={`1px solid ${colors.grayLines.main}`} borderRadius="0.75rem" p="0.25rem 0.75rem">{pivotTableFunctionLabels[value.function]} of {label}</Box>);
|
||||
}
|
||||
|
||||
return (<React.Fragment />);
|
||||
}
|
||||
|
||||
const handleFieldChange = (event: any, newValue: any, reason: string) =>
|
||||
{
|
||||
value.fieldName = newValue ? newValue.fieldName : null;
|
||||
};
|
||||
|
||||
const handleFunctionChange = (event: any, newValue: any, reason: string) =>
|
||||
{
|
||||
value.function = newValue ? newValue.id : null;
|
||||
};
|
||||
|
||||
const functionOptions: any[] = [];
|
||||
let defaultFunctionValue = null;
|
||||
for (let pivotTableFunctionKey in PivotTableFunction)
|
||||
{
|
||||
// @ts-ignore any?
|
||||
const label = "" + pivotTableFunctionLabels[pivotTableFunctionKey];
|
||||
const option = {id: pivotTableFunctionKey, label: label};
|
||||
functionOptions.push(option);
|
||||
|
||||
if (option.id == value.function)
|
||||
{
|
||||
defaultFunctionValue = option;
|
||||
}
|
||||
}
|
||||
|
||||
// maybe cursor:grab (and then change to "grabbing")
|
||||
return (<Box display="flex" p="0.5rem" pl="0" gap="0.5rem" alignItems="center">
|
||||
<Box>
|
||||
<Icon sx={{cursor: "ns-resize"}}>drag_indicator</Icon>
|
||||
</Box>
|
||||
<Box width="100%">
|
||||
<FieldAutoComplete
|
||||
id={`values-field-${index}`}
|
||||
label={null}
|
||||
variant="outlined"
|
||||
textFieldSX={fieldAutoCompleteTextFieldSX}
|
||||
metaData={metaData}
|
||||
tableMetaData={tableMetaData}
|
||||
handleFieldChange={handleFieldChange}
|
||||
defaultValue={getSelectedFieldForAutoComplete(tableMetaData, value.fieldName)}
|
||||
/>
|
||||
</Box>
|
||||
<Box width="330px">
|
||||
<Autocomplete
|
||||
id={`values-field-${index}`}
|
||||
renderInput={(params) => (<TextField {...params} label={null} variant="outlined" sx={fieldAutoCompleteTextFieldSX} autoComplete="off" type="search" InputProps={{...params.InputProps}} />)}
|
||||
// @ts-ignore
|
||||
defaultValue={defaultFunctionValue}
|
||||
options={functionOptions}
|
||||
onChange={handleFunctionChange}
|
||||
isOptionEqualToValue={(option, value) => option.id === value.id}
|
||||
getOptionLabel={(option) => option.label}
|
||||
// todo? renderOption={(props, option, state) => renderFieldOption(props, option, state)}
|
||||
autoSelect={true}
|
||||
autoHighlight={true}
|
||||
disableClearable
|
||||
// slotProps={{popper: {className: "filterCriteriaRowColumnPopper", style: {padding: 0, width: "250px"}}}}
|
||||
// {...alsoOpen}
|
||||
/>
|
||||
</Box>
|
||||
<Box>
|
||||
<Button sx={xIconButtonSX} onClick={() => removeValue(index)}><Icon>clear</Icon></Button>
|
||||
</Box>
|
||||
</Box>);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** drag & drop callback to move one of the pivot-table group-bys (rows/columns)
|
||||
*******************************************************************************/
|
||||
const moveGroupBy = useCallback((rowsOrColumns: "rows" | "columns", dragIndex: number, hoverIndex: number) =>
|
||||
{
|
||||
const array = modalPivotTableDefinition[rowsOrColumns];
|
||||
const dragItem = array[dragIndex];
|
||||
array.splice(dragIndex, 1);
|
||||
array.splice(hoverIndex, 0, dragItem);
|
||||
|
||||
forceUpdate();
|
||||
}, [modalPivotTableDefinition]);
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** drag & drop callback to move one of the pivot-table values
|
||||
*******************************************************************************/
|
||||
const moveValue = useCallback((dragIndex: number, hoverIndex: number) =>
|
||||
{
|
||||
const array = modalPivotTableDefinition.values;
|
||||
const dragItem = array[dragIndex];
|
||||
array.splice(dragIndex, 1);
|
||||
array.splice(hoverIndex, 0, dragItem);
|
||||
|
||||
forceUpdate();
|
||||
}, [modalPivotTableDefinition]);
|
||||
|
||||
|
||||
const noTable = (tableMetaData == null);
|
||||
const noColumns = (!availableFieldNames || availableFieldNames.length == 0);
|
||||
|
||||
const selectTableFirstTooltipTitle = noTable ? "You must select a table before you can set up your pivot table" : null;
|
||||
const selectColumnsFirstTooltipTitle = noColumns ? "You must set up your report's Columns before you can set up your Pivot Table" : null;
|
||||
const editPopupDisabled = noTable || noColumns;
|
||||
|
||||
/////////////////////////////////////////////////////////////
|
||||
// add toggle component to widget header for editable mode //
|
||||
/////////////////////////////////////////////////////////////
|
||||
const labelAdditionalElementsRight: JSX.Element[] = [];
|
||||
if (isEditable)
|
||||
{
|
||||
labelAdditionalElementsRight.push(<HeaderToggleComponent key="pivotTableHeader" disabled={editPopupDisabled} disabledTooltip={selectTableFirstTooltipTitle ?? selectColumnsFirstTooltipTitle} label="Use Pivot Table?" getValue={() => enabled} onClickCallback={toggleEnabled} />);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** render a group-by (row or column)
|
||||
*******************************************************************************/
|
||||
const renderGroupBy = useCallback((groupBy: PivotTableGroupBy, rowsOrColumns: "rows" | "columns", index: number, forModal: boolean) =>
|
||||
{
|
||||
return (
|
||||
<PivotTableGroupByElement
|
||||
key={groupBy.fieldName}
|
||||
index={index}
|
||||
id={`${groupBy.key}`}
|
||||
dragCallback={moveGroupBy}
|
||||
metaData={metaData}
|
||||
tableMetaData={tableMetaData}
|
||||
pivotTableDefinition={forModal ? modalPivotTableDefinition : pivotTableDefinition}
|
||||
usedGroupByFieldNames={[...usedGroupByFieldNames, ...usedValueFieldNames]}
|
||||
availableFieldNames={availableFieldNames}
|
||||
isEditable={isEditable && forModal}
|
||||
groupBy={groupBy}
|
||||
rowsOrColumns={rowsOrColumns}
|
||||
callback={childElementChangedCallback}
|
||||
attemptedSubmit={attemptedSubmit}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[tableMetaData, usedGroupByFieldNames, availableFieldNames],
|
||||
);
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** render a pivot-table value (row or column)
|
||||
*******************************************************************************/
|
||||
const renderValue = useCallback((value: PivotTableValue, index: number, forModal: boolean) =>
|
||||
{
|
||||
return (
|
||||
<PivotTableValueElement
|
||||
key={value.key}
|
||||
index={index}
|
||||
id={`${value.key}`}
|
||||
dragCallback={moveValue}
|
||||
metaData={metaData}
|
||||
tableMetaData={tableMetaData}
|
||||
pivotTableDefinition={forModal ? modalPivotTableDefinition : pivotTableDefinition}
|
||||
availableFieldNames={availableFieldNames}
|
||||
usedGroupByFieldNames={usedGroupByFieldNames}
|
||||
isEditable={isEditable && forModal}
|
||||
value={value}
|
||||
callback={childElementChangedCallback}
|
||||
attemptedSubmit={attemptedSubmit}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[tableMetaData, usedGroupByFieldNames, availableFieldNames],
|
||||
);
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function openEditor()
|
||||
{
|
||||
if (recordValues["tableName"])
|
||||
{
|
||||
setModalPivotTableDefinition(Object.assign({}, pivotTableDefinition));
|
||||
setModalOpen(true);
|
||||
setAttemptedSubmit(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function closeEditor(event?: {}, reason?: "backdropClick" | "escapeKeyDown")
|
||||
{
|
||||
if (reason == "backdropClick" || reason == "escapeKeyDown")
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
setModalOpen(false);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function renderGroupBys(forModal: boolean, rowsOrColumns: "rows" | "columns")
|
||||
{
|
||||
const ptd = forModal ? modalPivotTableDefinition : pivotTableDefinition;
|
||||
|
||||
return <>
|
||||
<h5>{rowsOrColumns == "rows" ? "Rows" : "Columns"}</h5>
|
||||
<Box fontSize="1rem">
|
||||
{
|
||||
tableMetaData && (<div>{ptd[rowsOrColumns]?.map((groupBy, i) => renderGroupBy(groupBy, rowsOrColumns, i, forModal))}</div>)
|
||||
}
|
||||
</Box>
|
||||
{
|
||||
(forModal || (isEditable && !ptd[rowsOrColumns]?.length)) &&
|
||||
<Box mt={forModal ? "0.5rem" : "0"} mb="1rem">
|
||||
<Tooltip title={selectTableFirstTooltipTitle ?? selectColumnsFirstTooltipTitle}>
|
||||
<span><Button disabled={editPopupDisabled} sx={forModal ? buttonSX : unborderedButtonSX} onClick={() => forModal ? addGroupBy(rowsOrColumns) : openEditor()}>+ Add new {rowsOrColumns == "rows" ? "row" : "column"}</Button></span>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
}
|
||||
{
|
||||
!isEditable && !forModal && !ptd[rowsOrColumns]?.length &&
|
||||
<Box color={colors.gray.main} fontSize="1rem">Your pivot table has no {rowsOrColumns}.</Box>
|
||||
}
|
||||
</>;
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function renderValues(forModal: boolean)
|
||||
{
|
||||
const ptd = forModal ? modalPivotTableDefinition : pivotTableDefinition;
|
||||
|
||||
return <>
|
||||
<h5>Values</h5>
|
||||
<Box fontSize="1rem">
|
||||
{
|
||||
tableMetaData && (<div>{ptd?.values?.map((value, i) => renderValue(value, i, forModal))}</div>)
|
||||
}
|
||||
</Box>
|
||||
{
|
||||
(forModal || (isEditable && !ptd?.values?.length)) &&
|
||||
<Box mt={forModal ? "0.5rem" : "0"} mb="1rem">
|
||||
<Tooltip title={selectTableFirstTooltipTitle ?? selectColumnsFirstTooltipTitle}>
|
||||
<span><Button disabled={editPopupDisabled} sx={forModal ? buttonSX : unborderedButtonSX} onClick={() => forModal ? addValue() : openEditor()}>+ Add new value</Button></span>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
}
|
||||
{
|
||||
!isEditable && !forModal && !ptd?.values?.length &&
|
||||
<Box color={colors.gray.main} fontSize="1rem">Your pivot table has no values.</Box>
|
||||
}
|
||||
</>;
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function validateForm(submitting: boolean = false)
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// if this isn't a call from the on-submit handler, and we haven't previously attempted a submit, then return w/o setting any alerts //
|
||||
// this is like a version of considering "touched"... //
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
if (!submitting && !attemptedSubmit)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let missingValues = 0;
|
||||
|
||||
for (let i = 0; i < modalPivotTableDefinition?.rows?.length; i++)
|
||||
{
|
||||
if (!modalPivotTableDefinition.rows[i].fieldName)
|
||||
{
|
||||
missingValues++;
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < modalPivotTableDefinition?.columns?.length; i++)
|
||||
{
|
||||
if (!modalPivotTableDefinition.columns[i].fieldName)
|
||||
{
|
||||
missingValues++;
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < modalPivotTableDefinition?.values?.length; i++)
|
||||
{
|
||||
if (!modalPivotTableDefinition.values[i].fieldName)
|
||||
{
|
||||
missingValues++;
|
||||
}
|
||||
if (!modalPivotTableDefinition.values[i].function)
|
||||
{
|
||||
missingValues++;
|
||||
}
|
||||
}
|
||||
|
||||
if (missingValues == 0)
|
||||
{
|
||||
setErrorAlert(null);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
// this is to catch the case of - user attempted to submit, and there were errors //
|
||||
// now they've fixed 'em - so go back to a 'clean' state - so if they add more //
|
||||
// boxes, they won't immediately show errors, until a re-submit //
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
if (attemptedSubmit)
|
||||
{
|
||||
setAttemptedSubmit(false);
|
||||
}
|
||||
return (false);
|
||||
}
|
||||
|
||||
setErrorAlert(`Missing value in ${missingValues} field${missingValues == 1 ? "" : "s"}.`);
|
||||
return (true);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function saveClicked()
|
||||
{
|
||||
setAttemptedSubmit(true);
|
||||
|
||||
if (validateForm(true))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!onSaveCallback)
|
||||
{
|
||||
console.log("onSaveCallback was not defined");
|
||||
return;
|
||||
}
|
||||
|
||||
setPivotTableDefinition(Object.assign({}, modalPivotTableDefinition));
|
||||
updateUsedGroupByFieldNames(modalPivotTableDefinition);
|
||||
updateUsedValueFieldNames(modalPivotTableDefinition);
|
||||
|
||||
onSaveCallback({pivotTableJson: JSON.stringify(modalPivotTableDefinition)});
|
||||
|
||||
closeEditor();
|
||||
}
|
||||
|
||||
|
||||
////////////
|
||||
// render //
|
||||
////////////
|
||||
return (<Widget widgetMetaData={widgetMetaData} labelAdditionalElementsRight={labelAdditionalElementsRight}>
|
||||
{
|
||||
<React.Fragment>
|
||||
<DndProvider backend={HTML5Backend}>
|
||||
{
|
||||
enabled &&
|
||||
<Box display="flex" justifyContent="space-between">
|
||||
<Box>
|
||||
{
|
||||
showHelp("sectionSubhead") &&
|
||||
<Box color={colors.gray.main} pb={"0.5rem"} fontSize={"0.875rem"}>
|
||||
{getHelpContent("sectionSubhead")}
|
||||
</Box>
|
||||
}
|
||||
</Box>
|
||||
{
|
||||
isEditable &&
|
||||
<Tooltip title={selectTableFirstTooltipTitle ?? selectColumnsFirstTooltipTitle}>
|
||||
<span>
|
||||
<Button disabled={editPopupDisabled} onClick={() => openEditor()} sx={{p: 0}} disableRipple>
|
||||
<Typography display="inline" textTransform="none" fontSize={"1.125rem"}>
|
||||
Edit Pivot Table
|
||||
</Typography>
|
||||
</Button>
|
||||
</span>
|
||||
</Tooltip>
|
||||
}
|
||||
</Box>
|
||||
}
|
||||
{
|
||||
(!enabled || !pivotTableDefinition) && !isEditable &&
|
||||
<Box fontSize="1rem">Your report does not use a Pivot Table.</Box>
|
||||
}
|
||||
{
|
||||
enabled && pivotTableDefinition &&
|
||||
<>
|
||||
<Grid container spacing="16">
|
||||
|
||||
<Grid item lg={4} md={6} xs={12}>{renderGroupBys(false, "rows")}</Grid>
|
||||
<Grid item lg={4} md={6} xs={12}>{renderGroupBys(false, "columns")}</Grid>
|
||||
<Grid item lg={4} md={6} xs={12}>{renderValues(false)}</Grid>
|
||||
|
||||
</Grid>
|
||||
{
|
||||
modalOpen &&
|
||||
<Modal open={modalOpen} onClose={(event, reason) => closeEditor(event, reason)}>
|
||||
<div>
|
||||
<Box sx={{position: "absolute", width: "100%"}}>
|
||||
<Card sx={{m: "2rem", p: "2rem", overflowY: "auto", height: "calc(100vh - 4rem)"}}>
|
||||
<h3>Edit Pivot Table</h3>
|
||||
{
|
||||
showHelp("modalSubheader") &&
|
||||
<Box color={colors.gray.main}>
|
||||
{getHelpContent("modalSubheader")}
|
||||
</Box>
|
||||
}
|
||||
{
|
||||
errorAlert && <Alert icon={<Icon>error_outline</Icon>} color="error" onClose={() => setErrorAlert(null)}>{errorAlert}</Alert>
|
||||
}
|
||||
<Grid container spacing="16" overflow="auto" mt="0.5rem" mb="1rem" height="100%">
|
||||
|
||||
<Grid item lg={4} md={6} xs={12}>{renderGroupBys(true, "rows")}</Grid>
|
||||
<Grid item lg={4} md={6} xs={12}>{renderGroupBys(true, "columns")}</Grid>
|
||||
<Grid item lg={4} md={6} xs={12}>{renderValues(true)}</Grid>
|
||||
|
||||
</Grid>
|
||||
<Box>
|
||||
<Box display="flex" justifyContent="flex-end">
|
||||
<QCancelButton disabled={false} onClickHandler={closeEditor} />
|
||||
<QSaveButton label="OK" iconName="check" disabled={false} onClickHandler={saveClicked} />
|
||||
</Box>
|
||||
</Box>
|
||||
</Card>
|
||||
</Box>
|
||||
</div>
|
||||
</Modal>
|
||||
}
|
||||
</>
|
||||
}
|
||||
</DndProvider>
|
||||
</React.Fragment>
|
||||
}
|
||||
</Widget>);
|
||||
}
|
||||
|
||||
/* this was a rough-draft of what a preview of a pivot could look like...
|
||||
<Box mt={"1rem"}>
|
||||
<h5>Preview</h5>
|
||||
<table>
|
||||
<tr>
|
||||
<th style={{textAlign: "left", fontSize: "0.875rem"}}></th>
|
||||
<th style={{textAlign: "left", fontSize: "0.875rem"}}>Column Labels</th>
|
||||
</tr>
|
||||
{
|
||||
pivotTableDefinition?.columns?.map((column, i) =>
|
||||
(
|
||||
<tr key={column.key}>
|
||||
<th style={{textAlign: "left", fontSize: "0.875rem"}}></th>
|
||||
<th style={{textAlign: "left", fontSize: "0.875rem"}}>{column.fieldName}</th>
|
||||
</tr>
|
||||
))
|
||||
}
|
||||
<tr>
|
||||
<th style={{textAlign: "left", fontSize: "0.875rem"}}>Row Labels</th>
|
||||
{
|
||||
pivotTableDefinition?.values?.map((value, i) =>
|
||||
(
|
||||
<th key={value.key} style={{textAlign: "left", fontSize: "0.875rem"}}>{value.function} of {value.fieldName}</th>
|
||||
))
|
||||
}
|
||||
</tr>
|
||||
{
|
||||
pivotTableDefinition?.rows?.map((row, i) =>
|
||||
(
|
||||
<tr key={row.key}>
|
||||
<th style={{textAlign: "left", fontSize: "0.875rem", paddingLeft: (i * 1) + "rem"}}>{row.fieldName}</th>
|
||||
</tr>
|
||||
))
|
||||
}
|
||||
</table>
|
||||
</Box>
|
||||
*/
|
319
src/qqq/components/widgets/misc/PivotTableValueElement.tsx
Normal file
319
src/qqq/components/widgets/misc/PivotTableValueElement.tsx
Normal file
@ -0,0 +1,319 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData";
|
||||
import {QFieldType} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldType";
|
||||
import {QInstance} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QInstance";
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import Autocomplete from "@mui/material/Autocomplete";
|
||||
import Box from "@mui/material/Box";
|
||||
import Button from "@mui/material/Button";
|
||||
import Icon from "@mui/material/Icon";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import type {Identifier, XYCoord} from "dnd-core";
|
||||
import colors from "qqq/assets/theme/base/colors";
|
||||
import FieldAutoComplete from "qqq/components/misc/FieldAutoComplete";
|
||||
import {DragItemTypes, fieldAutoCompleteTextFieldSX, getSelectedFieldForAutoComplete, xIconButtonSX} from "qqq/components/widgets/misc/PivotTableSetupWidget";
|
||||
import {functionsPerFieldType, PivotTableDefinition, pivotTableFunctionLabels, PivotTableValue} from "qqq/models/misc/PivotTableDefinitionModels";
|
||||
import React, {FC, useReducer, useRef, useState} from "react";
|
||||
import {useDrag, useDrop} from "react-dnd";
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** component props
|
||||
*******************************************************************************/
|
||||
export interface PivotTableValueElementProps
|
||||
{
|
||||
id: string;
|
||||
index: number;
|
||||
dragCallback: (dragIndex: number, hoverIndex: number) => void;
|
||||
metaData: QInstance;
|
||||
tableMetaData: QTableMetaData;
|
||||
pivotTableDefinition: PivotTableDefinition;
|
||||
availableFieldNames: string[];
|
||||
usedGroupByFieldNames: string[];
|
||||
isEditable: boolean;
|
||||
value: PivotTableValue;
|
||||
callback: () => void;
|
||||
attemptedSubmit?: boolean;
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** item to support react-dnd
|
||||
*******************************************************************************/
|
||||
interface DragItem
|
||||
{
|
||||
index: number;
|
||||
id: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Element to render 1 pivot-table value.
|
||||
*******************************************************************************/
|
||||
export const PivotTableValueElement: FC<PivotTableValueElementProps> = ({id, index, dragCallback, metaData, tableMetaData, pivotTableDefinition, availableFieldNames, usedGroupByFieldNames, value, isEditable, callback, attemptedSubmit}) =>
|
||||
{
|
||||
const [defaultFunctionValue, setDefaultFunctionValue] = useState(null);
|
||||
const [, forceUpdate] = useReducer((x) => x + 1, 0);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// credit: https://react-dnd.github.io/react-dnd/examples/sortable/simple //
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [{handlerId}, drop] = useDrop<DragItem, void, { handlerId: Identifier | null }>(
|
||||
{
|
||||
accept: DragItemTypes.VALUE,
|
||||
collect(monitor)
|
||||
{
|
||||
return {
|
||||
handlerId: monitor.getHandlerId(),
|
||||
};
|
||||
},
|
||||
hover(item: DragItem, monitor)
|
||||
{
|
||||
if (!ref.current)
|
||||
{
|
||||
return;
|
||||
}
|
||||
const dragIndex = item.index;
|
||||
const hoverIndex = index;
|
||||
|
||||
// Don't replace items with themselves
|
||||
if (dragIndex === hoverIndex)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine rectangle on screen
|
||||
const hoverBoundingRect = ref.current?.getBoundingClientRect();
|
||||
|
||||
// Get vertical middle
|
||||
const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
|
||||
|
||||
// Determine mouse position
|
||||
const clientOffset = monitor.getClientOffset();
|
||||
|
||||
// Get pixels to the top
|
||||
const hoverClientY = (clientOffset as XYCoord).y - hoverBoundingRect.top;
|
||||
|
||||
// Only perform the move when the mouse has crossed half of the items height
|
||||
// When dragging downwards, only move when the cursor is below 50%
|
||||
// When dragging upwards, only move when the cursor is above 50%
|
||||
|
||||
// Dragging downwards
|
||||
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Dragging upwards
|
||||
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Time to actually perform the action
|
||||
dragCallback(dragIndex, hoverIndex);
|
||||
|
||||
// Note: we're mutating the monitor item here! Generally it's better to avoid mutations,
|
||||
// but it's good here for the sake of performance to avoid expensive index searches.
|
||||
item.index = hoverIndex;
|
||||
},
|
||||
});
|
||||
|
||||
const [{isDragging}, drag] = useDrag({
|
||||
type: DragItemTypes.VALUE,
|
||||
item: () =>
|
||||
{
|
||||
return {id, index};
|
||||
},
|
||||
collect: (monitor: any) => ({
|
||||
isDragging: monitor.isDragging(),
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function getFunctionsForField(field: QFieldMetaData)
|
||||
{
|
||||
if(field)
|
||||
{
|
||||
let type = field.type;
|
||||
if (field.possibleValueSourceName)
|
||||
{
|
||||
type = QFieldType.STRING;
|
||||
}
|
||||
|
||||
if(functionsPerFieldType[type])
|
||||
{
|
||||
return (functionsPerFieldType[type]);
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////
|
||||
// return broadest list if no field //
|
||||
//////////////////////////////////////
|
||||
return (functionsPerFieldType[QFieldType.INTEGER]);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** event handler for user selecting a field
|
||||
*******************************************************************************/
|
||||
function handleFieldChange(event: any, newValue: any, reason: string)
|
||||
{
|
||||
value.fieldName = newValue ? newValue.fieldName : null;
|
||||
|
||||
if(newValue)
|
||||
{
|
||||
/////////////////////////////////////////////////////////////////////////////////////////
|
||||
// if newly selected field doesn't have the currently selected function, then clear it //
|
||||
/////////////////////////////////////////////////////////////////////////////////////////
|
||||
const newSelectedField = getSelectedFieldForAutoComplete(tableMetaData, newValue.fieldName);
|
||||
if (newSelectedField)
|
||||
{
|
||||
if(getFunctionsForField(newSelectedField.field).indexOf(value.function) == -1)
|
||||
{
|
||||
setDefaultFunctionValue(null);
|
||||
handleFunctionChange(null, null, null);
|
||||
forceUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
callback();
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** event handler for user selecting a function
|
||||
*******************************************************************************/
|
||||
function handleFunctionChange(event: any, newValue: any, reason: string)
|
||||
{
|
||||
value.function = newValue ? newValue.id : null;
|
||||
callback();
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** event handler for clicking remove button
|
||||
*******************************************************************************/
|
||||
function removeValue(index: number)
|
||||
{
|
||||
pivotTableDefinition.values.splice(index, 1);
|
||||
callback();
|
||||
}
|
||||
|
||||
const selectedField = getSelectedFieldForAutoComplete(tableMetaData, value.fieldName);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// if we're not on an edit screen, return a simpler read-only view //
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
if (!isEditable)
|
||||
{
|
||||
let label = "--";
|
||||
if (selectedField && value.function)
|
||||
{
|
||||
label = pivotTableFunctionLabels[value.function] + " of " + (selectedField.table.name == tableMetaData.name ? selectedField.field.label : selectedField.table.label + ": " + selectedField.field.label);
|
||||
}
|
||||
|
||||
return (<Box><Box display="inline-block" mr="0.375rem" mb="0.5rem" border={`1px solid ${colors.grayLines.main}`} borderRadius="0.75rem" p="0.25rem 0.75rem">{label}</Box></Box>);
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// figure out functions to display in drop down, plus selected/default value //
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
const functionOptions: any[] = [];
|
||||
const availableFunctions = getFunctionsForField(selectedField?.field);
|
||||
for (let pivotTableFunction of availableFunctions)
|
||||
{
|
||||
const label = pivotTableFunctionLabels[pivotTableFunction];
|
||||
const option = {id: pivotTableFunction, label: label};
|
||||
functionOptions.push(option);
|
||||
|
||||
if (option.id == value.function && JSON.stringify(option) != JSON.stringify(defaultFunctionValue))
|
||||
{
|
||||
setDefaultFunctionValue(option);
|
||||
}
|
||||
}
|
||||
|
||||
drag(drop(ref));
|
||||
|
||||
const showValueError = attemptedSubmit && !value.fieldName;
|
||||
const showFunctionError = attemptedSubmit && !value.function;
|
||||
|
||||
return (<Box ref={ref} display="flex" p="0.5rem" pl="0" gap="0.5rem" alignItems="center" sx={{backgroundColor: "white", opacity: isDragging ? 0 : 1}} data-handler-id={handlerId}>
|
||||
<Box>
|
||||
<Icon sx={{cursor: "ns-resize"}}>drag_indicator</Icon>
|
||||
</Box>
|
||||
<Box width="100%">
|
||||
<FieldAutoComplete
|
||||
id={`values-field-${index}`}
|
||||
label={null}
|
||||
variant="outlined"
|
||||
textFieldSX={fieldAutoCompleteTextFieldSX}
|
||||
metaData={metaData}
|
||||
tableMetaData={tableMetaData}
|
||||
handleFieldChange={handleFieldChange}
|
||||
availableFieldNames={availableFieldNames}
|
||||
hiddenFieldNames={usedGroupByFieldNames}
|
||||
defaultValue={selectedField}
|
||||
hasError={showValueError}
|
||||
noOptionsText="There are no fields available."
|
||||
/>
|
||||
</Box>
|
||||
<Box width="370px">
|
||||
<Autocomplete
|
||||
id={`values-function-${index}`}
|
||||
renderInput={(params) =>
|
||||
{
|
||||
const inputProps = params.InputProps;
|
||||
const originalEndAdornment = inputProps.endAdornment;
|
||||
inputProps.endAdornment = <Box>
|
||||
{showFunctionError && <Icon color="error">error_outline</Icon>}
|
||||
{originalEndAdornment}
|
||||
</Box>;
|
||||
|
||||
return (<TextField {...params} label={null} variant="outlined" sx={fieldAutoCompleteTextFieldSX} autoComplete="off" type="search" InputProps={inputProps} />)
|
||||
}}
|
||||
// @ts-ignore
|
||||
value={defaultFunctionValue}
|
||||
inputValue={defaultFunctionValue?.label ?? ""}
|
||||
options={functionOptions}
|
||||
onChange={handleFunctionChange}
|
||||
isOptionEqualToValue={(option, value) => option.id === value.id}
|
||||
getOptionLabel={(option) => option.label}
|
||||
autoSelect={true}
|
||||
autoHighlight={true}
|
||||
disableClearable
|
||||
/>
|
||||
</Box>
|
||||
<Box>
|
||||
<Button sx={xIconButtonSX} onClick={() => removeValue(index)}><Icon>clear</Icon></Button>
|
||||
</Box>
|
||||
</Box>);
|
||||
|
||||
};
|
@ -185,7 +185,7 @@ function RecordGridWidget({widgetMetaData, data, addNewRecordCallback, disableRo
|
||||
if(data && data.viewAllLink)
|
||||
{
|
||||
labelAdditionalElementsLeft.push(
|
||||
<Typography variant="body2" p={2} display="inline" fontSize=".875rem" pt="0" position="relative">
|
||||
<Typography key={"viewAllLink"} variant="body2" p={2} display="inline" fontSize=".875rem" pt="0" position="relative">
|
||||
<Link to={data.viewAllLink}>View All</Link>
|
||||
</Typography>
|
||||
)
|
||||
@ -225,8 +225,8 @@ function RecordGridWidget({widgetMetaData, data, addNewRecordCallback, disableRo
|
||||
if(widgetMetaData?.showExportButton)
|
||||
{
|
||||
labelAdditionalElementsLeft.push(
|
||||
<Typography key={1} variant="body2" px={0} display="inline" position="relative">
|
||||
<Tooltip title={tooltipTitle}><Button sx={{px: 1, py: 0, minWidth: "initial"}} onClick={onExportClick} disabled={isExportDisabled}><Icon sx={{color: "#757575", fontSize: 1.25}}>save_alt</Icon></Button></Tooltip>
|
||||
<Typography key={"exportButton"} variant="body2" px={0} display="inline" position="relative">
|
||||
<Tooltip title={tooltipTitle}><span><Button sx={{px: 1, py: 0, minWidth: "initial"}} onClick={onExportClick} disabled={isExportDisabled}><Icon sx={{color: "#757575", fontSize: 1.25}}>save_alt</Icon></Button></span></Tooltip>
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
@ -305,48 +305,50 @@ function RecordGridWidget({widgetMetaData, data, addNewRecordCallback, disableRo
|
||||
labelBoxAdditionalSx={{position: "relative", top: "-0.375rem"}}
|
||||
>
|
||||
<Box mx={-2} mb={-3}>
|
||||
<DataGridPro
|
||||
autoHeight
|
||||
sx={{
|
||||
borderBottom: "none",
|
||||
borderLeft: "none",
|
||||
borderRight: "none"
|
||||
}}
|
||||
rows={rows}
|
||||
disableSelectionOnClick
|
||||
columns={columns}
|
||||
rowBuffer={10}
|
||||
getRowClassName={(params) => (params.indexRelativeToCurrentPage % 2 === 0 ? "even" : "odd")}
|
||||
onRowClick={handleRowClick}
|
||||
getRowId={(row) => row.__rowIndex}
|
||||
// getRowHeight={() => "auto"} // maybe nice? wraps values in cells...
|
||||
components={{
|
||||
Toolbar: CustomToolbar
|
||||
}}
|
||||
// pinnedColumns={pinnedColumns}
|
||||
// onPinnedColumnsChange={handlePinnedColumnsChange}
|
||||
// pagination
|
||||
// paginationMode="server"
|
||||
// rowsPerPageOptions={[20]}
|
||||
// sortingMode="server"
|
||||
// filterMode="server"
|
||||
// page={pageNumber}
|
||||
// checkboxSelection
|
||||
rowCount={data && data.totalRows}
|
||||
// onPageSizeChange={handleRowsPerPageChange}
|
||||
// onStateChange={handleStateChange}
|
||||
// density={density}
|
||||
// loading={loading}
|
||||
// filterModel={filterModel}
|
||||
// onFilterModelChange={handleFilterChange}
|
||||
// columnVisibilityModel={columnVisibilityModel}
|
||||
// onColumnVisibilityModelChange={handleColumnVisibilityChange}
|
||||
// onColumnOrderChange={handleColumnOrderChange}
|
||||
// onSelectionModelChange={selectionChanged}
|
||||
// onSortModelChange={handleSortChange}
|
||||
// sortingOrder={[ "asc", "desc" ]}
|
||||
// sortModel={columnSortModel}
|
||||
/>
|
||||
<Box className="recordGridWidget">
|
||||
<DataGridPro
|
||||
autoHeight
|
||||
sx={{
|
||||
borderBottom: "none",
|
||||
borderLeft: "none",
|
||||
borderRight: "none"
|
||||
}}
|
||||
rows={rows}
|
||||
disableSelectionOnClick
|
||||
columns={columns}
|
||||
rowBuffer={10}
|
||||
getRowClassName={(params) => (params.indexRelativeToCurrentPage % 2 === 0 ? "even" : "odd")}
|
||||
onRowClick={handleRowClick}
|
||||
getRowId={(row) => row.__rowIndex}
|
||||
// getRowHeight={() => "auto"} // maybe nice? wraps values in cells...
|
||||
components={{
|
||||
Toolbar: CustomToolbar
|
||||
}}
|
||||
// pinnedColumns={pinnedColumns}
|
||||
// onPinnedColumnsChange={handlePinnedColumnsChange}
|
||||
// pagination
|
||||
// paginationMode="server"
|
||||
// rowsPerPageOptions={[20]}
|
||||
// sortingMode="server"
|
||||
// filterMode="server"
|
||||
// page={pageNumber}
|
||||
// checkboxSelection
|
||||
rowCount={data && data.totalRows}
|
||||
// onPageSizeChange={handleRowsPerPageChange}
|
||||
// onStateChange={handleStateChange}
|
||||
// density={density}
|
||||
// loading={loading}
|
||||
// filterModel={filterModel}
|
||||
// onFilterModelChange={handleFilterChange}
|
||||
// columnVisibilityModel={columnVisibilityModel}
|
||||
// onColumnVisibilityModelChange={handleColumnVisibilityChange}
|
||||
// onColumnOrderChange={handleColumnOrderChange}
|
||||
// onSelectionModelChange={selectionChanged}
|
||||
// onSortModelChange={handleSortChange}
|
||||
// sortingOrder={[ "asc", "desc" ]}
|
||||
// sortModel={columnSortModel}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
</Widget>
|
||||
);
|
||||
|
@ -30,8 +30,6 @@ import TableContainer from "@mui/material/TableContainer";
|
||||
import TableRow from "@mui/material/TableRow";
|
||||
import Tooltip from "@mui/material/Tooltip";
|
||||
import parse from "html-react-parser";
|
||||
import React, {useEffect, useMemo, useState} from "react";
|
||||
import {useAsyncDebounce, useExpanded, useGlobalFilter, usePagination, useSortBy, useTable} from "react-table";
|
||||
import colors from "qqq/assets/theme/base/colors";
|
||||
import MDInput from "qqq/components/legacy/MDInput";
|
||||
import MDPagination from "qqq/components/legacy/MDPagination";
|
||||
@ -43,6 +41,8 @@ import DefaultCell from "qqq/components/widgets/tables/cells/DefaultCell";
|
||||
import ImageCell from "qqq/components/widgets/tables/cells/ImageCell";
|
||||
import {TableDataInput} from "qqq/components/widgets/tables/TableCard";
|
||||
import WidgetBlock from "qqq/components/widgets/WidgetBlock";
|
||||
import React, {useEffect, useMemo, useState} from "react";
|
||||
import {useAsyncDebounce, useExpanded, useGlobalFilter, usePagination, useSortBy, useTable} from "react-table";
|
||||
|
||||
interface Props
|
||||
{
|
||||
@ -106,17 +106,17 @@ function DataTable({
|
||||
entries = entriesPerPageOptions ? entriesPerPageOptions : ["10", "25", "50", "100"];
|
||||
|
||||
let widths = [];
|
||||
for(let i = 0; i<table.columns.length; i++)
|
||||
for (let i = 0; i < table.columns.length; i++)
|
||||
{
|
||||
const column = table.columns[i];
|
||||
if(column.type !== "hidden")
|
||||
if (column.type !== "hidden")
|
||||
{
|
||||
widths.push(table.columns[i].width ?? "1fr");
|
||||
}
|
||||
}
|
||||
|
||||
let showExpandColumn = false;
|
||||
if(table.rows)
|
||||
if (table.rows)
|
||||
{
|
||||
for (let i = 0; i < table.rows.length; i++)
|
||||
{
|
||||
@ -129,7 +129,7 @@ function DataTable({
|
||||
}
|
||||
|
||||
const columnsToMemo = [...table.columns];
|
||||
if(showExpandColumn)
|
||||
if (showExpandColumn)
|
||||
{
|
||||
widths.push("60px");
|
||||
columnsToMemo.push(
|
||||
@ -173,11 +173,11 @@ function DataTable({
|
||||
);
|
||||
}
|
||||
|
||||
if(table.columnHeaderTooltips)
|
||||
if (table.columnHeaderTooltips)
|
||||
{
|
||||
for (let column of columnsToMemo)
|
||||
{
|
||||
if(table.columnHeaderTooltips[column.accessor])
|
||||
if (table.columnHeaderTooltips[column.accessor])
|
||||
{
|
||||
column.tooltip = table.columnHeaderTooltips[column.accessor];
|
||||
}
|
||||
@ -297,7 +297,7 @@ function DataTable({
|
||||
}
|
||||
|
||||
let visibleFooterRows = 1;
|
||||
if(expanded && expanded[`${table.rows.length-1}`])
|
||||
if (expanded && expanded[`${table.rows.length - 1}`])
|
||||
{
|
||||
//////////////////////////////////////////////////
|
||||
// todo - should count how many are expanded... //
|
||||
@ -308,7 +308,7 @@ function DataTable({
|
||||
function getTable(includeHead: boolean, rows: any, isFooter: boolean)
|
||||
{
|
||||
let boxStyle = {};
|
||||
if(fixedStickyLastRow)
|
||||
if (fixedStickyLastRow)
|
||||
{
|
||||
boxStyle = isFooter
|
||||
? {borderTop: `0.0625rem solid ${colors.grayLines.main};`, backgroundColor: "#EEEEEE"}
|
||||
@ -316,7 +316,7 @@ function DataTable({
|
||||
}
|
||||
|
||||
let innerBoxStyle = {};
|
||||
if(fixedStickyLastRow && isFooter)
|
||||
if (fixedStickyLastRow && isFooter)
|
||||
{
|
||||
innerBoxStyle = {overflowY: "auto", scrollbarGutter: "stable"};
|
||||
}
|
||||
@ -327,7 +327,7 @@ function DataTable({
|
||||
includeHead && (
|
||||
<Box component="thead" sx={{position: "sticky", top: 0, background: "white", zIndex: 10}}>
|
||||
{headerGroups.map((headerGroup: any, i: number) => (
|
||||
<TableRow key={i} {...headerGroup.getHeaderGroupProps()} sx={{display: "grid", gridTemplateColumns: gridTemplateColumns}}>
|
||||
<TableRow key={i} {...headerGroup.getHeaderGroupProps()} sx={{display: "grid", alignItems: "flex-end", gridTemplateColumns: gridTemplateColumns}}>
|
||||
{headerGroup.headers.map((column: any) => (
|
||||
column.type !== "hidden" && (
|
||||
<DataTableHeadCell
|
||||
@ -356,10 +356,10 @@ function DataTable({
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
// don't do an end-border on nested rows - unless they're the last one in a set //
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
if(row.depth > 0)
|
||||
if (row.depth > 0)
|
||||
{
|
||||
overrideNoEndBorder = true;
|
||||
if(key + 1 < rows.length && rows[key + 1].depth == 0)
|
||||
if (key + 1 < rows.length && rows[key + 1].depth == 0)
|
||||
{
|
||||
overrideNoEndBorder = false;
|
||||
}
|
||||
@ -368,17 +368,17 @@ function DataTable({
|
||||
///////////////////////////////////////
|
||||
// don't do end-border on the footer //
|
||||
///////////////////////////////////////
|
||||
if(isFooter)
|
||||
if (isFooter)
|
||||
{
|
||||
overrideNoEndBorder = true;
|
||||
}
|
||||
|
||||
let background = "initial";
|
||||
if(isFooter)
|
||||
if (isFooter)
|
||||
{
|
||||
background = "#EEEEEE";
|
||||
}
|
||||
else if(row.depth > 0 || row.isExpanded)
|
||||
else if (row.depth > 0 || row.isExpanded)
|
||||
{
|
||||
background = "#FAFAFA";
|
||||
}
|
||||
@ -453,7 +453,7 @@ function DataTable({
|
||||
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Box></Box>
|
||||
</Box></Box>;
|
||||
}
|
||||
|
||||
return (
|
||||
|
@ -28,13 +28,13 @@ import TableBody from "@mui/material/TableBody";
|
||||
import TableContainer from "@mui/material/TableContainer";
|
||||
import TableRow from "@mui/material/TableRow";
|
||||
import parse from "html-react-parser";
|
||||
import React, {useEffect, useState} from "react";
|
||||
import MDTypography from "qqq/components/legacy/MDTypography";
|
||||
import DataTableBodyCell from "qqq/components/widgets/tables/cells/DataTableBodyCell";
|
||||
import DataTableHeadCell from "qqq/components/widgets/tables/cells/DataTableHeadCell";
|
||||
import DefaultCell from "qqq/components/widgets/tables/cells/DefaultCell";
|
||||
import DataTable from "qqq/components/widgets/tables/DataTable";
|
||||
import Client from "qqq/utils/qqq/Client";
|
||||
import React, {useEffect, useState} from "react";
|
||||
|
||||
|
||||
//////////////////////////////////////
|
||||
@ -43,7 +43,7 @@ import Client from "qqq/utils/qqq/Client";
|
||||
export interface TableDataInput
|
||||
{
|
||||
columns: { [key: string]: any }[];
|
||||
columnHeaderTooltips?: { [columnName: string]: string | JSX.Element }
|
||||
columnHeaderTooltips?: { [columnName: string]: string | JSX.Element };
|
||||
rows: { [key: string]: any }[];
|
||||
}
|
||||
|
||||
@ -63,6 +63,7 @@ interface Props
|
||||
}
|
||||
|
||||
const qController = Client.getInstance();
|
||||
|
||||
function TableCard({noRowsFoundHTML, data, rowsPerPage, hidePaginationDropdown, fixedStickyLastRow, fixedHeight, widgetMetaData}: Props): JSX.Element
|
||||
{
|
||||
const [qInstance, setQInstance] = useState(null as QInstance);
|
||||
@ -108,7 +109,7 @@ function TableCard({noRowsFoundHTML, data, rowsPerPage, hidePaginationDropdown,
|
||||
<TableContainer sx={{boxShadow: "none"}}>
|
||||
<Table>
|
||||
<Box component="thead">
|
||||
<TableRow key="header">
|
||||
<TableRow sx={{alignItems: "flex-end"}} key="header">
|
||||
{Array(8).fill(0).map((_, i) =>
|
||||
<DataTableHeadCell key={`head-${i}`} sorted={false} width="auto" align="center">
|
||||
<Skeleton width="100%" />
|
||||
|
@ -23,7 +23,6 @@
|
||||
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
|
||||
// @ts-ignore
|
||||
import {htmlToText} from "html-to-text";
|
||||
import React, {useContext, useEffect, useState} from "react";
|
||||
import QContext from "QContext";
|
||||
import HelpContent, {hasHelpContent} from "qqq/components/misc/HelpContent";
|
||||
import TableCard from "qqq/components/widgets/tables/TableCard";
|
||||
@ -31,6 +30,7 @@ import Widget, {WidgetData} from "qqq/components/widgets/Widget";
|
||||
import {WidgetUtils} from "qqq/components/widgets/WidgetUtils";
|
||||
import HtmlUtils from "qqq/utils/HtmlUtils";
|
||||
import ValueUtils from "qqq/utils/qqq/ValueUtils";
|
||||
import React, {useContext, useEffect, useState} from "react";
|
||||
|
||||
interface Props
|
||||
{
|
||||
@ -40,8 +40,7 @@ interface Props
|
||||
isChild?: boolean;
|
||||
}
|
||||
|
||||
TableWidget.defaultProps = {
|
||||
};
|
||||
TableWidget.defaultProps = {};
|
||||
|
||||
function TableWidget(props: Props): JSX.Element
|
||||
{
|
||||
@ -86,7 +85,7 @@ function TableWidget(props: Props): JSX.Element
|
||||
|
||||
const cell = rows[i][columns[j].accessor];
|
||||
let text = cell;
|
||||
if(columns[j].type != "default")
|
||||
if (columns[j].type != "default")
|
||||
{
|
||||
text = htmlToText(cell,
|
||||
{
|
||||
@ -105,7 +104,7 @@ function TableWidget(props: Props): JSX.Element
|
||||
setCsv(csv);
|
||||
|
||||
const fileName = WidgetUtils.makeExportFileName(props.widgetData, props.widgetMetaData);
|
||||
setFileName(fileName)
|
||||
setFileName(fileName);
|
||||
|
||||
console.log(`useEffect, setting fileName ${fileName}`);
|
||||
}
|
||||
@ -114,24 +113,28 @@ function TableWidget(props: Props): JSX.Element
|
||||
|
||||
const onExportClick = () =>
|
||||
{
|
||||
if(props.widgetData?.csvData)
|
||||
if (props.widgetData?.csvData)
|
||||
{
|
||||
const csv = WidgetUtils.widgetCsvDataToString(props.widgetData);
|
||||
const fileName = WidgetUtils.makeExportFileName(props.widgetData, props.widgetMetaData);
|
||||
HtmlUtils.download(fileName, csv);
|
||||
}
|
||||
else if(csv)
|
||||
else if (csv)
|
||||
{
|
||||
HtmlUtils.download(fileName, csv);
|
||||
}
|
||||
else
|
||||
{
|
||||
alert("There is no data available to export.")
|
||||
alert("There is no data available to export.");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const labelAdditionalElementsLeft: JSX.Element[] = [];
|
||||
if(props.widgetMetaData?.showExportButton)
|
||||
if (props.widgetData?.linkText && props.widgetData?.linkURL)
|
||||
{
|
||||
labelAdditionalElementsLeft.push(WidgetUtils.generateLabelLink(props.widgetData?.linkText, props.widgetData?.linkURL));
|
||||
}
|
||||
if (props.widgetMetaData?.showExportButton)
|
||||
{
|
||||
labelAdditionalElementsLeft.push(WidgetUtils.generateExportButton(onExportClick));
|
||||
}
|
||||
@ -139,14 +142,14 @@ function TableWidget(props: Props): JSX.Element
|
||||
//////////////////////////////////////////////////////
|
||||
// look for column-header tooltips from helpContent //
|
||||
//////////////////////////////////////////////////////
|
||||
const columnHeaderTooltips: {[columnName: string]: JSX.Element} = {}
|
||||
const columnHeaderTooltips: { [columnName: string]: JSX.Element } = {};
|
||||
for (let column of props.widgetData?.columns ?? [])
|
||||
{
|
||||
const helpRoles = ["ALL_SCREENS"]
|
||||
const helpRoles = ["ALL_SCREENS"];
|
||||
const slotName = `columnHeader=${column.accessor}`;
|
||||
const showHelp = helpHelpActive || hasHelpContent(props.widgetMetaData?.helpContent?.get(slotName), helpRoles);
|
||||
|
||||
if(showHelp)
|
||||
if (showHelp)
|
||||
{
|
||||
const formattedHelpContent = <HelpContent helpContents={props.widgetMetaData?.helpContent?.get(slotName)} roles={helpRoles} helpContentKey={`widget:${props.widgetMetaData?.name};slot:${slotName}`} />;
|
||||
columnHeaderTooltips[column.accessor] = formattedHelpContent;
|
||||
|
52
src/qqq/models/fields/FieldRules.ts
Normal file
52
src/qqq/models/fields/FieldRules.ts
Normal file
@ -0,0 +1,52 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
export interface FieldRule
|
||||
{
|
||||
trigger: FieldRuleTrigger;
|
||||
sourceField: string;
|
||||
action: FieldRuleAction;
|
||||
targetField: string;
|
||||
targetWidget: string;
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
export enum FieldRuleTrigger
|
||||
{
|
||||
ON_CHANGE = "ON_CHANGE"
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
export enum FieldRuleAction
|
||||
{
|
||||
CLEAR_TARGET_FIELD = "CLEAR_TARGET_FIELD",
|
||||
RELOAD_WIDGET = "RELOAD_WIDGET"
|
||||
}
|
159
src/qqq/models/misc/PivotTableDefinitionModels.ts
Normal file
159
src/qqq/models/misc/PivotTableDefinitionModels.ts
Normal file
@ -0,0 +1,159 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {QFieldType} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldType";
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** put a unique key value in all the pivot table group-by and value objects,
|
||||
** to help react rendering be sane.
|
||||
*******************************************************************************/
|
||||
export class PivotObjectKey
|
||||
{
|
||||
private static value = new Date().getTime();
|
||||
|
||||
static next(): number
|
||||
{
|
||||
return PivotObjectKey.value++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Full definition of pivot table
|
||||
*******************************************************************************/
|
||||
export class PivotTableDefinition
|
||||
{
|
||||
rows: PivotTableGroupBy[];
|
||||
columns: PivotTableGroupBy[];
|
||||
values: PivotTableValue[];
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A field that the pivot table is grouped by, either as a row or column
|
||||
*******************************************************************************/
|
||||
export class PivotTableGroupBy
|
||||
{
|
||||
fieldName: string;
|
||||
key: number;
|
||||
|
||||
constructor()
|
||||
{
|
||||
this.key = PivotObjectKey.next();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A field & function that serves as the computed values in the pivot table
|
||||
*******************************************************************************/
|
||||
export class PivotTableValue
|
||||
{
|
||||
fieldName: string;
|
||||
function: PivotTableFunction;
|
||||
|
||||
key: number;
|
||||
|
||||
constructor()
|
||||
{
|
||||
this.key = PivotObjectKey.next();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Functions that can be applied to pivot table values
|
||||
*******************************************************************************/
|
||||
export enum PivotTableFunction
|
||||
{
|
||||
SUM = "SUM",
|
||||
COUNT = "COUNT",
|
||||
AVERAGE = "AVERAGE",
|
||||
MAX = "MAX",
|
||||
MIN = "MIN",
|
||||
PRODUCT = "PRODUCT",
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// i don't think we have a useful version of count-nums --unless we allowed //
|
||||
// it on string fields, and counted if they looked like numbers? is that //
|
||||
// what we should do? ... leave here as zombie in case that request comes in //
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// COUNT_NUMS = "COUNT_NUMS",
|
||||
|
||||
STD_DEV = "STD_DEV",
|
||||
STD_DEVP = "STD_DEVP",
|
||||
VAR = "VAR",
|
||||
VARP = "VARP",
|
||||
}
|
||||
|
||||
const allFunctions = [
|
||||
PivotTableFunction.SUM,
|
||||
PivotTableFunction.COUNT,
|
||||
PivotTableFunction.AVERAGE,
|
||||
PivotTableFunction.MAX,
|
||||
PivotTableFunction.MIN,
|
||||
PivotTableFunction.PRODUCT,
|
||||
// PivotTableFunction.COUNT_NUMS,
|
||||
PivotTableFunction.STD_DEV,
|
||||
PivotTableFunction.STD_DEVP,
|
||||
PivotTableFunction.VAR,
|
||||
PivotTableFunction.VARP
|
||||
];
|
||||
|
||||
const onlyCount = [PivotTableFunction.COUNT];
|
||||
|
||||
const functionsForDates = [PivotTableFunction.COUNT, PivotTableFunction.AVERAGE, PivotTableFunction.MAX, PivotTableFunction.MIN];
|
||||
|
||||
export const functionsPerFieldType: { [type: string]: PivotTableFunction[] } = {};
|
||||
functionsPerFieldType[QFieldType.STRING] = onlyCount;
|
||||
functionsPerFieldType[QFieldType.BOOLEAN] = onlyCount;
|
||||
functionsPerFieldType[QFieldType.BLOB] = onlyCount;
|
||||
functionsPerFieldType[QFieldType.HTML] = onlyCount;
|
||||
functionsPerFieldType[QFieldType.PASSWORD] = onlyCount;
|
||||
functionsPerFieldType[QFieldType.TEXT] = onlyCount;
|
||||
functionsPerFieldType[QFieldType.TIME] = onlyCount;
|
||||
|
||||
functionsPerFieldType[QFieldType.INTEGER] = allFunctions;
|
||||
functionsPerFieldType[QFieldType.DECIMAL] = allFunctions;
|
||||
// functionsPerFieldType[QFieldType.LONG] = allFunctions;
|
||||
|
||||
functionsPerFieldType[QFieldType.DATE] = functionsForDates;
|
||||
functionsPerFieldType[QFieldType.DATE_TIME] = functionsForDates;
|
||||
|
||||
|
||||
//////////////////////////////////////
|
||||
// labels for pivot table functions //
|
||||
//////////////////////////////////////
|
||||
export const pivotTableFunctionLabels =
|
||||
{
|
||||
"SUM": "Sum",
|
||||
"COUNT": "Count",
|
||||
"AVERAGE": "Average",
|
||||
"MAX": "Max",
|
||||
"MIN": "Min",
|
||||
"PRODUCT": "Product",
|
||||
// "COUNT_NUMS": "Count Numbers",
|
||||
"STD_DEV": "StdDev",
|
||||
"STD_DEVP": "StdDevp",
|
||||
"VAR": "Var",
|
||||
"VARP": "Varp"
|
||||
};
|
@ -23,14 +23,13 @@
|
||||
import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData";
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import {GridPinnedColumns} from "@mui/x-data-grid-pro";
|
||||
import quickSightChart from "qqq/components/widgets/misc/QuickSightChart";
|
||||
import DataGridUtils from "qqq/utils/DataGridUtils";
|
||||
import TableUtils from "qqq/utils/qqq/TableUtils";
|
||||
|
||||
/*******************************************************************************
|
||||
** member object
|
||||
*******************************************************************************/
|
||||
interface Column
|
||||
export interface Column
|
||||
{
|
||||
name: string;
|
||||
isVisible: boolean;
|
||||
@ -81,11 +80,19 @@ export default class QQueryColumns
|
||||
fields.forEach((field) =>
|
||||
{
|
||||
const column: Column = {name: field.name, isVisible: true, width: DataGridUtils.getColumnWidthForField(field, table)};
|
||||
queryColumns.columns.push(column);
|
||||
|
||||
if (field.name == table.primaryKeyField)
|
||||
{
|
||||
column.pinned = "left";
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
// insert the primary key field after __check__ //
|
||||
//////////////////////////////////////////////////
|
||||
queryColumns.columns.splice(1, 0, column);
|
||||
}
|
||||
else
|
||||
{
|
||||
queryColumns.columns.push(column);
|
||||
}
|
||||
});
|
||||
|
||||
@ -393,6 +400,42 @@ export default class QQueryColumns
|
||||
return columnVisibilityModel;
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** sort the columns list, so that pinned columns go to the front (left) or back
|
||||
** (right) of the list.
|
||||
*******************************************************************************/
|
||||
public sortColumnsFixingPinPositions = (): void =>
|
||||
{
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// do a sort to push pinned-left columns to the start, and pinned-right columns to the end //
|
||||
// and otherwise, leave everything alone //
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////
|
||||
this.columns = this.columns.sort((a: Column, b: Column) =>
|
||||
{
|
||||
if(a.pinned == "left" && b.pinned != "left")
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
else if(b.pinned == "left" && a.pinned != "left")
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
else if(a.pinned == "right" && b.pinned != "right")
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
else if(b.pinned == "right" && a.pinned != "right")
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
return (0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
@ -35,8 +35,7 @@ import {QJobRunning} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJob
|
||||
import {QJobStarted} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJobStarted";
|
||||
import {QRecord} from "@kingsrook/qqq-frontend-core/lib/model/QRecord";
|
||||
import {QQueryFilter} from "@kingsrook/qqq-frontend-core/lib/model/query/QQueryFilter";
|
||||
import {Alert, Button, CircularProgress, Icon, TablePagination} from "@mui/material";
|
||||
import Box from "@mui/material/Box";
|
||||
import {Alert, Box, Button, CircularProgress, Icon, TablePagination} from "@mui/material";
|
||||
import Card from "@mui/material/Card";
|
||||
import Grid from "@mui/material/Grid";
|
||||
import Step from "@mui/material/Step";
|
||||
@ -48,16 +47,19 @@ import FormData from "form-data";
|
||||
import {Form, Formik} from "formik";
|
||||
import parse from "html-react-parser";
|
||||
import QContext from "QContext";
|
||||
import colors from "qqq/assets/theme/base/colors";
|
||||
import {QCancelButton, QSubmitButton} from "qqq/components/buttons/DefaultButtons";
|
||||
import QDynamicForm from "qqq/components/forms/DynamicForm";
|
||||
import DynamicFormUtils from "qqq/components/forms/DynamicFormUtils";
|
||||
import MDButton from "qqq/components/legacy/MDButton";
|
||||
import MDProgress from "qqq/components/legacy/MDProgress";
|
||||
import MDTypography from "qqq/components/legacy/MDTypography";
|
||||
import HelpContent, {hasHelpContent} from "qqq/components/misc/HelpContent";
|
||||
import QRecordSidebar from "qqq/components/misc/RecordSidebar";
|
||||
import {GoogleDriveFolderPickerWrapper} from "qqq/components/processes/GoogleDriveFolderPickerWrapper";
|
||||
import ProcessSummaryResults from "qqq/components/processes/ProcessSummaryResults";
|
||||
import ValidationReview from "qqq/components/processes/ValidationReview";
|
||||
import DashboardWidgets from "qqq/components/widgets/DashboardWidgets";
|
||||
import BaseLayout from "qqq/layouts/BaseLayout";
|
||||
import {TABLE_VARIANT_LOCAL_STORAGE_KEY_ROOT} from "qqq/pages/records/query/RecordQuery";
|
||||
import Client from "qqq/utils/qqq/Client";
|
||||
@ -86,6 +88,14 @@ const INITIAL_RETRY_MILLIS = 1_500;
|
||||
const RETRY_MAX_MILLIS = 12_000;
|
||||
const BACKOFF_AMOUNT = 1.5;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// define a function that we can make referenes to, which we'll overwrite //
|
||||
// with formik's setFieldValue function, once we're inside formik. //
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
let formikSetFieldValueFunction = (field: string, value: any, shouldValidate?: boolean): void =>
|
||||
{
|
||||
};
|
||||
|
||||
function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, isReport, recordIds, closeModalHandler, forceReInit, overrideLabel}: Props): JSX.Element
|
||||
{
|
||||
const processNameParam = useParams().processName;
|
||||
@ -124,7 +134,9 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
const [showErrorDetail, setShowErrorDetail] = useState(false);
|
||||
const [showFullHelpText, setShowFullHelpText] = useState(false);
|
||||
|
||||
const {pageHeader, recordAnalytics, setPageHeader} = useContext(QContext);
|
||||
const [renderedWidgets, setRenderedWidgets] = useState({} as { [step: string]: { [widgetName: string]: any } });
|
||||
|
||||
const {pageHeader, recordAnalytics, setPageHeader, helpHelpActive} = useContext(QContext);
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// for setting the processError state - call this function, which will also set the isUserFacingError state //
|
||||
@ -226,8 +238,19 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
setShowFullHelpText(!showFullHelpText);
|
||||
};
|
||||
|
||||
const download = (url: string, fileName: string) =>
|
||||
const download = (processValues: { [key: string]: string }) =>
|
||||
{
|
||||
let url;
|
||||
let fileName = processValues.downloadFileName;
|
||||
if (processValues.serverFilePath)
|
||||
{
|
||||
url = `/download/${encodeURIComponent(processValues.downloadFileName)}?filePath=${encodeURIComponent(processValues.serverFilePath)}`;
|
||||
}
|
||||
else if (processValues.storageTableName && processValues.storageReference)
|
||||
{
|
||||
url = `/download/${encodeURIComponent(processValues.downloadFileName)}?storageTableName=${encodeURIComponent(processValues.storageTableName)}&storageReference=${encodeURIComponent(processValues.storageReference)}`;
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// todo - this could be simplified, i think? //
|
||||
// it was originally built like this when we had to submit full access token to backend... //
|
||||
@ -262,6 +285,42 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function renderWidget(widgetName: string)
|
||||
{
|
||||
if (!renderedWidgets[activeStep.name])
|
||||
{
|
||||
renderedWidgets[activeStep.name] = {};
|
||||
setRenderedWidgets(renderedWidgets);
|
||||
}
|
||||
|
||||
if (renderedWidgets[activeStep.name][widgetName])
|
||||
{
|
||||
return renderedWidgets[activeStep.name][widgetName];
|
||||
}
|
||||
|
||||
const widgetMetaData = qInstance.widgets.get(widgetName);
|
||||
if (!widgetMetaData)
|
||||
{
|
||||
return (<Alert color="error">Unrecognized widget name: {widgetName}</Alert>);
|
||||
}
|
||||
|
||||
const queryStringParts: string[] = [];
|
||||
for (let name in processValues)
|
||||
{
|
||||
queryStringParts.push(`${name}=${encodeURIComponent(processValues[name])}`);
|
||||
}
|
||||
|
||||
const renderedWidget = (<Box m={-2}>
|
||||
<DashboardWidgets widgetMetaDataList={[widgetMetaData]} omitWrappingGridContainer={true} childUrlParams={queryStringParts.join("&")} />
|
||||
</Box>);
|
||||
renderedWidgets[activeStep.name][widgetName] = renderedWidget;
|
||||
return renderedWidget;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////
|
||||
// generate the main form body content for a step //
|
||||
////////////////////////////////////////////////////
|
||||
@ -308,8 +367,8 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
</MDTypography>
|
||||
<Box component="div" py={3}>
|
||||
<Grid container justifyContent="flex-end" spacing={3}>
|
||||
{isModal ? <QCancelButton onClickHandler={handleCancelClicked} disabled={false} label="Close" />
|
||||
: !isWidget && <QCancelButton onClickHandler={handleCancelClicked} disabled={false} />
|
||||
{isModal ? <QCancelButton onClickHandler={() => handleCancelClicked(true)} disabled={false} label="Close" />
|
||||
: !isWidget && <QCancelButton onClickHandler={() => handleCancelClicked(true)} disabled={false} />
|
||||
}
|
||||
</Grid>
|
||||
</Box>
|
||||
@ -396,6 +455,13 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
});
|
||||
}
|
||||
|
||||
/////////////////////////////////////
|
||||
// screen(step)-level help content //
|
||||
/////////////////////////////////////
|
||||
let helpRoles = ["PROCESS_SCREEN", "ALL_SCREENS"];
|
||||
const showHelp = helpHelpActive || hasHelpContent(step.helpContents, helpRoles);
|
||||
const formattedHelpContent = <HelpContent helpContents={step.helpContents} roles={helpRoles} helpContentKey={`process:${processName};step:${step?.name}`} />;
|
||||
|
||||
return (
|
||||
<>
|
||||
{
|
||||
@ -410,6 +476,13 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
</MDTypography>
|
||||
}
|
||||
|
||||
{
|
||||
showHelp &&
|
||||
<Box fontSize={"0.875rem"} color={colors.blueGray.main} pb={2}>
|
||||
{formattedHelpContent}
|
||||
</Box>
|
||||
}
|
||||
|
||||
{
|
||||
//////////////////////////////////////////////////
|
||||
// render all of the components for this screen //
|
||||
@ -422,6 +495,23 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
helpRoles = ["EDIT_SCREEN", "WRITE_SCREENS", "ALL_SCREENS"];
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// if the component specifies a sub-set of field names to include, then //
|
||||
// edit the formData object to just include those. //
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
let formDataToUse = formData;
|
||||
if (component.values && component.values.includeFieldNames)
|
||||
{
|
||||
formDataToUse = Object.assign({}, formData);
|
||||
|
||||
formDataToUse.formFields = {};
|
||||
for (let i = 0; i < component.values.includeFieldNames.length; i++)
|
||||
{
|
||||
const fieldName = component.values.includeFieldNames[i];
|
||||
formDataToUse.formFields[fieldName] = formData.formFields[fieldName];
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={index}>
|
||||
{
|
||||
@ -517,9 +607,22 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
)
|
||||
}
|
||||
{
|
||||
component.type === QComponentType.EDIT_FORM && (
|
||||
<QDynamicForm formData={formData} helpRoles={helpRoles} helpContentKeyPrefix={`process:${processName};`} />
|
||||
)
|
||||
component.type === QComponentType.EDIT_FORM &&
|
||||
<>
|
||||
{
|
||||
component.values?.sectionLabel ?
|
||||
<Box py={1.5}>
|
||||
<Card sx={{scrollMarginTop: "20px"}}>
|
||||
<MDTypography variant="h5" p={3} pl={2} pb={1}>
|
||||
{component.values?.sectionLabel}
|
||||
</MDTypography>
|
||||
<Box pt={0} p={2}>
|
||||
<QDynamicForm formData={formDataToUse} helpRoles={helpRoles} helpContentKeyPrefix={`process:${processName};`} />
|
||||
</Box>
|
||||
</Card>
|
||||
</Box> : <QDynamicForm formData={formDataToUse} helpRoles={helpRoles} helpContentKeyPrefix={`process:${processName};`} />
|
||||
}
|
||||
</>
|
||||
}
|
||||
{
|
||||
component.type === QComponentType.VIEW_FORM && step.viewFields && (
|
||||
@ -556,7 +659,7 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
Download
|
||||
</Box>
|
||||
<Box display="flex" py={1} pr={2}>
|
||||
<MDTypography variant="button" fontWeight="bold" onClick={() => download(`/download/${processValues.downloadFileName}?filePath=${processValues.serverFilePath}`, processValues.downloadFileName)} sx={{cursor: "pointer"}}>
|
||||
<MDTypography variant="button" fontWeight="bold" onClick={() => download(processValues)} sx={{cursor: "pointer"}}>
|
||||
<Box display="flex" alignItems="center" gap={1} py={1} pr={2}>
|
||||
<Icon fontSize="large">download_for_offline</Icon>
|
||||
{processValues.downloadFileName}
|
||||
@ -642,6 +745,12 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
{
|
||||
component.type === QComponentType.WIDGET && (
|
||||
component.values?.widgetName &&
|
||||
renderWidget(component.values?.widgetName)
|
||||
)
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}))
|
||||
@ -904,7 +1013,7 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
}
|
||||
});
|
||||
|
||||
DynamicFormUtils.addPossibleValueProps(newDynamicFormFields, fullFieldList, tableMetaData.name, null, null);
|
||||
DynamicFormUtils.addPossibleValueProps(newDynamicFormFields, fullFieldList, tableMetaData?.name, null, null);
|
||||
|
||||
setFormFields(newDynamicFormFields);
|
||||
setValidationScheme(Yup.object().shape(newFormValidations));
|
||||
@ -970,6 +1079,30 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
setProcessValues(qJobComplete.values);
|
||||
setQJobRunning(null);
|
||||
|
||||
if (formikSetFieldValueFunction)
|
||||
{
|
||||
//////////////////////////////////
|
||||
// reset field values in formik //
|
||||
//////////////////////////////////
|
||||
for (let key in qJobComplete.values)
|
||||
{
|
||||
if (Object.hasOwn(formFields, key))
|
||||
{
|
||||
console.log(`(re)setting form field [${key}] to [${qJobComplete.values[key]}]`);
|
||||
formikSetFieldValueFunction(key, qJobComplete.values[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// if the process step sent a new frontend-step-list, then refresh what we have in state (constructing new full model objects) //
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
const updatedFrontendStepList = qJobComplete.updatedFrontendStepList;
|
||||
if (updatedFrontendStepList)
|
||||
{
|
||||
setSteps(updatedFrontendStepList);
|
||||
}
|
||||
|
||||
if (activeStep && activeStep.recordListFields)
|
||||
{
|
||||
setNeedRecords(true);
|
||||
@ -1268,8 +1401,20 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
});
|
||||
};
|
||||
|
||||
const handleCancelClicked = () =>
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
const handleCancelClicked = (isClose: boolean) =>
|
||||
{
|
||||
//////////////////////////////////////////////////////////////////
|
||||
// unless this is a 'close', then tell backend we're cancelling //
|
||||
//////////////////////////////////////////////////////////////////
|
||||
if (!isClose)
|
||||
{
|
||||
Client.getInstance().processCancel(processName, processUUID);
|
||||
}
|
||||
|
||||
if (isModal && closeModalHandler)
|
||||
{
|
||||
closeModalHandler(null, "cancelClicked");
|
||||
@ -1282,6 +1427,7 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
navigate(path, {replace: true});
|
||||
};
|
||||
|
||||
|
||||
const mainCardStyles: any = {};
|
||||
const formStyles: any = {};
|
||||
mainCardStyles.minHeight = `calc(100vh - ${isModal ? 150 : 400}px)`;
|
||||
@ -1329,89 +1475,98 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
|
||||
>
|
||||
{({
|
||||
values, errors, touched, isSubmitting, setFieldValue,
|
||||
}) => (
|
||||
<Form style={formStyles} id={formId} autoComplete="off">
|
||||
<Card sx={mainCardStyles}>
|
||||
{
|
||||
!isWidget && (
|
||||
<Box mx={2} mt={-3}>
|
||||
<Stepper activeStep={activeStepIndex} alternativeLabel>
|
||||
{steps.map((step) => (
|
||||
<Step key={step.name}>
|
||||
<StepLabel>{step.label}</StepLabel>
|
||||
</Step>
|
||||
))}
|
||||
</Stepper>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
}) =>
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////
|
||||
// once we're in the formik form, use its setFieldValue function //
|
||||
// over top of the default one we created globally //
|
||||
///////////////////////////////////////////////////////////////////
|
||||
formikSetFieldValueFunction = setFieldValue;
|
||||
|
||||
<Box p={3}>
|
||||
<Box pb={isWidget ? 6 : "initial"}>
|
||||
{/***************************************************************************
|
||||
** step content - e.g., the appropriate form or other screen for the step **
|
||||
***************************************************************************/}
|
||||
{getDynamicStepContent(
|
||||
activeStepIndex,
|
||||
activeStep,
|
||||
{
|
||||
values,
|
||||
touched,
|
||||
formFields,
|
||||
errors,
|
||||
},
|
||||
processError,
|
||||
processValues,
|
||||
recordConfig,
|
||||
setFieldValue,
|
||||
)}
|
||||
{/********************************
|
||||
** back &| next/submit buttons **
|
||||
********************************/}
|
||||
<Box mt={6} width="100%" display="flex" justifyContent="space-between" position={isWidget ? "absolute" : "initial"} bottom={isWidget ? "3rem" : "initial"} right={isWidget ? "1.5rem" : "initial"}>
|
||||
{true || activeStepIndex === 0 ? (
|
||||
<Box />
|
||||
) : (
|
||||
<MDButton variant="gradient" color="light" onClick={handleBack}>back</MDButton>
|
||||
)}
|
||||
{processError || qJobRunning || !activeStep ? (
|
||||
<Box />
|
||||
) : (
|
||||
<>
|
||||
{formError && (
|
||||
<MDTypography component="div" variant="caption" color="error" fontWeight="regular" align="right" fullWidth>
|
||||
{formError}
|
||||
</MDTypography>
|
||||
)}
|
||||
{
|
||||
noMoreSteps && <QCancelButton
|
||||
onClickHandler={handleCancelClicked}
|
||||
label={isModal ? "Close" : "Return"}
|
||||
iconName={isModal ? "cancel" : "arrow_back"}
|
||||
disabled={isSubmitting} />
|
||||
}
|
||||
{
|
||||
!noMoreSteps && (
|
||||
<Box component="div" py={3}>
|
||||
<Grid container justifyContent="flex-end" spacing={3}>
|
||||
{
|
||||
!isWidget && (
|
||||
<QCancelButton onClickHandler={handleCancelClicked} disabled={isSubmitting} />
|
||||
)
|
||||
}
|
||||
<QSubmitButton label={nextButtonLabel} iconName={nextButtonIcon} disabled={isSubmitting} />
|
||||
</Grid>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
</>
|
||||
return (
|
||||
<Form style={formStyles} id={formId} autoComplete="off">
|
||||
<Card sx={mainCardStyles}>
|
||||
{
|
||||
!isWidget && (
|
||||
<Box mx={2} mt={-3} sx={{"& .MuiStepper-horizontal": {minHeight: "5rem"}}}>
|
||||
<Stepper activeStep={activeStepIndex} alternativeLabel>
|
||||
{steps.map((step) => (
|
||||
<Step key={step.name}>
|
||||
<StepLabel>{step.label}</StepLabel>
|
||||
</Step>
|
||||
))}
|
||||
</Stepper>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
<Box p={3}>
|
||||
<Box pb={isWidget ? 6 : "initial"}>
|
||||
{/***************************************************************************
|
||||
** step content - e.g., the appropriate form or other screen for the step **
|
||||
***************************************************************************/}
|
||||
{getDynamicStepContent(
|
||||
activeStepIndex,
|
||||
activeStep,
|
||||
{
|
||||
values,
|
||||
touched,
|
||||
formFields,
|
||||
errors,
|
||||
},
|
||||
processError,
|
||||
processValues,
|
||||
recordConfig,
|
||||
setFieldValue,
|
||||
)}
|
||||
{/********************************
|
||||
** back &| next/submit buttons **
|
||||
********************************/}
|
||||
<Box mt={6} width="100%" display="flex" justifyContent="space-between" position={isWidget ? "absolute" : "initial"} bottom={isWidget ? "3rem" : "initial"} right={isWidget ? "1.5rem" : "initial"}>
|
||||
{true || activeStepIndex === 0 ? (
|
||||
<Box />
|
||||
) : (
|
||||
<MDButton variant="gradient" color="light" onClick={handleBack}>back</MDButton>
|
||||
)}
|
||||
{processError || qJobRunning || !activeStep ? (
|
||||
<Box />
|
||||
) : (
|
||||
<>
|
||||
{formError && (
|
||||
<MDTypography component="div" variant="caption" color="error" fontWeight="regular" align="right" fullWidth>
|
||||
{formError}
|
||||
</MDTypography>
|
||||
)}
|
||||
{
|
||||
noMoreSteps && <QCancelButton
|
||||
onClickHandler={() => handleCancelClicked(true)}
|
||||
label={isModal ? "Close" : "Return"}
|
||||
iconName={isModal ? "cancel" : "arrow_back"}
|
||||
disabled={isSubmitting} />
|
||||
}
|
||||
{
|
||||
!noMoreSteps && (
|
||||
<Box component="div" py={3}>
|
||||
<Grid container justifyContent="flex-end" spacing={3}>
|
||||
{
|
||||
!isWidget && (
|
||||
<QCancelButton onClickHandler={() => handleCancelClicked(false)} disabled={isSubmitting} />
|
||||
)
|
||||
}
|
||||
<QSubmitButton label={nextButtonLabel} iconName={nextButtonIcon} disabled={isSubmitting} />
|
||||
</Grid>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
</>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
</Card>
|
||||
</Form>
|
||||
)}
|
||||
</Card>
|
||||
</Form>
|
||||
);
|
||||
}}
|
||||
</Formik>
|
||||
);
|
||||
|
||||
|
@ -76,7 +76,7 @@ import ProcessUtils from "qqq/utils/qqq/ProcessUtils";
|
||||
import {SavedViewUtils} from "qqq/utils/qqq/SavedViewUtils";
|
||||
import TableUtils from "qqq/utils/qqq/TableUtils";
|
||||
import ValueUtils from "qqq/utils/qqq/ValueUtils";
|
||||
import React, {forwardRef, useContext, useEffect, useReducer, useRef, useState} from "react";
|
||||
import React, {forwardRef, useContext, useEffect, useImperativeHandle, useReducer, useRef, useState} from "react";
|
||||
import {useLocation, useNavigate, useSearchParams} from "react-router-dom";
|
||||
|
||||
const CURRENT_SAVED_VIEW_ID_LOCAL_STORAGE_KEY_ROOT = "qqq.currentSavedViewId";
|
||||
@ -84,18 +84,18 @@ const DENSITY_LOCAL_STORAGE_KEY_ROOT = "qqq.density";
|
||||
const VIEW_LOCAL_STORAGE_KEY_ROOT = "qqq.recordQueryView";
|
||||
|
||||
export const TABLE_VARIANT_LOCAL_STORAGE_KEY_ROOT = "qqq.tableVariant";
|
||||
export type QueryScreenUsage = "queryScreen" | "reportSetup"
|
||||
|
||||
interface Props
|
||||
{
|
||||
table?: QTableMetaData;
|
||||
launchProcess?: QProcessMetaData;
|
||||
usage?: QueryScreenUsage;
|
||||
isModal?: boolean;
|
||||
initialQueryFilter?: QQueryFilter;
|
||||
initialColumns?: QQueryColumns;
|
||||
}
|
||||
|
||||
RecordQuery.defaultProps = {
|
||||
table: null,
|
||||
launchProcess: null
|
||||
};
|
||||
|
||||
///////////////////////////////////////////////////////
|
||||
// define possible values for our pageState variable //
|
||||
///////////////////////////////////////////////////////
|
||||
@ -107,8 +107,13 @@ const qController = Client.getInstance();
|
||||
** function to produce standard version of the screen while we're "loading"
|
||||
** like the main table meta data etc.
|
||||
*******************************************************************************/
|
||||
const getLoadingScreen = () =>
|
||||
const getLoadingScreen = (isModal: boolean) =>
|
||||
{
|
||||
if (isModal)
|
||||
{
|
||||
return (<Box> </Box>);
|
||||
}
|
||||
|
||||
return (<BaseLayout>
|
||||
|
||||
</BaseLayout>);
|
||||
@ -120,7 +125,7 @@ const getLoadingScreen = () =>
|
||||
**
|
||||
** Yuge component. The best. Lots of very smart people are saying so.
|
||||
*******************************************************************************/
|
||||
function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
const RecordQuery = forwardRef(({table, usage, isModal, initialQueryFilter, initialColumns}: Props, ref) =>
|
||||
{
|
||||
const tableName = table.name;
|
||||
const [searchParams] = useSearchParams();
|
||||
@ -136,6 +141,44 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
const [firstRender, setFirstRender] = useState(true);
|
||||
const [isFirstRenderAfterChangingTables, setIsFirstRenderAfterChangingTables] = useState(false);
|
||||
|
||||
const [loadedFilterFromInitialFilterParam, setLoadedFilterFromInitialFilterParam] = useState(false);
|
||||
|
||||
const mayWriteLocalStorage = usage == "queryScreen";
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function localStorageSet(key: string, value: string)
|
||||
{
|
||||
if (mayWriteLocalStorage)
|
||||
{
|
||||
localStorage.setItem(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
function localStorageRemove(key: string)
|
||||
{
|
||||
if (mayWriteLocalStorage)
|
||||
{
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
}
|
||||
|
||||
useImperativeHandle(ref, () =>
|
||||
{
|
||||
return {
|
||||
getCurrentView(): RecordQueryView
|
||||
{
|
||||
return view;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// manage "state" being passed from some screens (like delete) into query screen - by grabbing, and then deleting //
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
@ -180,7 +223,9 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
/////////////////////////////////////
|
||||
const densityLocalStorageKey = `${DENSITY_LOCAL_STORAGE_KEY_ROOT}`;
|
||||
|
||||
// only load things out of local storage on the first render
|
||||
///////////////////////////////////////////////////////////////
|
||||
// only load things out of local storage on the first render //
|
||||
///////////////////////////////////////////////////////////////
|
||||
if (firstRender)
|
||||
{
|
||||
console.log("This is firstRender, so reading defaults from local storage...");
|
||||
@ -211,6 +256,26 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
defaultView.mode = defaultMode;
|
||||
}
|
||||
|
||||
if (firstRender)
|
||||
{
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
// allow a caller to send in an initial filter & set of columns. //
|
||||
// only to be used on "first render". //
|
||||
// JSON.parse(JSON.stringify()) to do deep clone and keep object clean //
|
||||
// unclear why not needed on initialColumns... //
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
if (initialQueryFilter)
|
||||
{
|
||||
defaultView.queryFilter = JSON.parse(JSON.stringify(initialQueryFilter));
|
||||
setLoadedFilterFromInitialFilterParam(true);
|
||||
}
|
||||
|
||||
if (initialColumns)
|
||||
{
|
||||
defaultView.queryColumns = initialColumns;
|
||||
}
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////
|
||||
// in case the view is missing any of these attributes, give them a reasonable default //
|
||||
/////////////////////////////////////////////////////////////////////////////////////////
|
||||
@ -343,7 +408,10 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
//////////////////////////////////////////////////////////////////
|
||||
// we use our own header - so clear out the context page header //
|
||||
//////////////////////////////////////////////////////////////////
|
||||
setPageHeader(null);
|
||||
if (!isModal)
|
||||
{
|
||||
setPageHeader(null);
|
||||
}
|
||||
|
||||
//////////////////////
|
||||
// ole' faithful... //
|
||||
@ -418,52 +486,6 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
const prepQueryFilterForBackend = (sourceFilter: QQueryFilter) =>
|
||||
{
|
||||
const filterForBackend = new QQueryFilter([], sourceFilter.orderBys, sourceFilter.subFilters, sourceFilter.booleanOperator);
|
||||
for (let i = 0; i < sourceFilter?.criteria?.length; i++)
|
||||
{
|
||||
const criteria = sourceFilter.criteria[i];
|
||||
const {criteriaIsValid} = validateCriteria(criteria, null);
|
||||
if (criteriaIsValid)
|
||||
{
|
||||
if (criteria.operator == QCriteriaOperator.IS_BLANK || criteria.operator == QCriteriaOperator.IS_NOT_BLANK)
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////////////////////////////
|
||||
// do this to avoid submitting an empty-string argument for blank/not-blank operators... //
|
||||
///////////////////////////////////////////////////////////////////////////////////////////
|
||||
filterForBackend.criteria.push(new QFilterCriteria(criteria.fieldName, criteria.operator, []));
|
||||
}
|
||||
else
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// else push a clone of the criteria - since it may get manipulated below (convertFilterPossibleValuesToIds) //
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
const [field] = FilterUtils.getField(tableMetaData, criteria.fieldName);
|
||||
filterForBackend.criteria.push(new QFilterCriteria(criteria.fieldName, criteria.operator, FilterUtils.cleanseCriteriaValueForQQQ(criteria.values, field)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/////////////////////////////////////////
|
||||
// recursively prep subfilters as well //
|
||||
/////////////////////////////////////////
|
||||
let subFilters = [] as QQueryFilter[];
|
||||
for (let j = 0; j < sourceFilter?.subFilters?.length; j++)
|
||||
{
|
||||
subFilters.push(prepQueryFilterForBackend(sourceFilter.subFilters[j]));
|
||||
}
|
||||
|
||||
filterForBackend.subFilters = subFilters;
|
||||
filterForBackend.skip = pageNumber * rowsPerPage;
|
||||
filterForBackend.limit = rowsPerPage;
|
||||
return filterForBackend;
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@ -494,7 +516,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
totalRecords: totalRecords,
|
||||
columnsModel: columnsModel,
|
||||
columnVisibilityModel: columnVisibilityModel,
|
||||
queryFilter: prepQueryFilterForBackend(queryFilter)
|
||||
queryFilter: FilterUtils.prepQueryFilterForBackend(tableMetaData, queryFilter)
|
||||
};
|
||||
|
||||
exportMenu = (<>
|
||||
@ -688,8 +710,11 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
{
|
||||
if (localStorage.getItem(currentSavedViewLocalStorageKey))
|
||||
{
|
||||
currentSavedViewId = Number.parseInt(localStorage.getItem(currentSavedViewLocalStorageKey));
|
||||
navigate(`${metaData.getTablePathByName(tableName)}/savedView/${currentSavedViewId}`);
|
||||
if (usage == "queryScreen")
|
||||
{
|
||||
currentSavedViewId = Number.parseInt(localStorage.getItem(currentSavedViewLocalStorageKey));
|
||||
navigate(`${metaData.getTablePathByName(tableName)}/savedView/${currentSavedViewId}`);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -724,13 +749,13 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
const viewForLocalStorage: RecordQueryView = JSON.parse(viewAsJSON);
|
||||
if (viewForLocalStorage?.queryFilter?.criteria?.length > 0)
|
||||
{
|
||||
FilterUtils.stripAwayIncompleteCriteria(viewForLocalStorage.queryFilter)
|
||||
FilterUtils.stripAwayIncompleteCriteria(viewForLocalStorage.queryFilter);
|
||||
}
|
||||
localStorage.setItem(viewLocalStorageKey, JSON.stringify(viewForLocalStorage));
|
||||
localStorageSet(viewLocalStorageKey, JSON.stringify(viewForLocalStorage));
|
||||
}
|
||||
catch(e)
|
||||
catch (e)
|
||||
{
|
||||
console.log("Error storing view in local storage: " + e)
|
||||
console.log("Error storing view in local storage: " + e);
|
||||
}
|
||||
};
|
||||
|
||||
@ -842,7 +867,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
for (let i = 0; i < queryFilter?.orderBys?.length; i++)
|
||||
{
|
||||
const fieldName = queryFilter.orderBys[i].fieldName;
|
||||
if (fieldName.indexOf(".") > -1)
|
||||
if (fieldName != null && fieldName.indexOf(".") > -1)
|
||||
{
|
||||
const joinTableName = fieldName.replaceAll(/\..*/g, "");
|
||||
if (!vjtToUse.has(joinTableName))
|
||||
@ -861,7 +886,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
/*******************************************************************************
|
||||
** This is the method that actually executes a query to update the data in the table.
|
||||
*******************************************************************************/
|
||||
const updateTable = (reason?: string) =>
|
||||
const updateTable = (reason?: string, clearOutCount = true) =>
|
||||
{
|
||||
if (pageState != "ready")
|
||||
{
|
||||
@ -875,6 +900,26 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
return;
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// if any values in the query are of type "FilterVariableExpression", display an error showing //
|
||||
// that a backend query cannot be made because of missing values for that expression //
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
setWarningAlert(null);
|
||||
for (var i = 0; i < queryFilter?.criteria?.length; i++)
|
||||
{
|
||||
for (var j = 0; j < queryFilter?.criteria[i]?.values?.length; j++)
|
||||
{
|
||||
const value = queryFilter.criteria[i].values[j];
|
||||
if (value?.type == "FilterVariableExpression")
|
||||
{
|
||||
setWarningAlert("Cannot perform query because of a missing value for a variable.");
|
||||
setLoading(false);
|
||||
setRows([]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
recordAnalytics({category: "tableEvents", action: "query", label: tableMetaData.label});
|
||||
|
||||
console.log(`In updateTable for ${reason} ${JSON.stringify(queryFilter)}`);
|
||||
@ -887,7 +932,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
// copy the orderBys & operator into it - but we'll build its criteria one-by-one, //
|
||||
// as clones, as we'll need to tweak them a bit //
|
||||
/////////////////////////////////////////////////////////////////////////////////////
|
||||
const filterForBackend = prepQueryFilterForBackend(queryFilter);
|
||||
const filterForBackend = FilterUtils.prepQueryFilterForBackend(tableMetaData, queryFilter, pageNumber, rowsPerPage);
|
||||
|
||||
//////////////////////////////////////////
|
||||
// figure out joins to use in the query //
|
||||
@ -913,6 +958,12 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
console.log(`Issuing query: ${thisQueryId}`);
|
||||
if (tableMetaData.capabilities.has(Capability.TABLE_COUNT))
|
||||
{
|
||||
if (clearOutCount)
|
||||
{
|
||||
setTotalRecords(null);
|
||||
setDistinctRecords(null);
|
||||
}
|
||||
|
||||
let includeDistinct = isJoinMany(tableMetaData, getVisibleJoinTables());
|
||||
qController.count(tableName, filterForBackend, queryJoins, includeDistinct, tableVariant).then(([count, distinctCount]) =>
|
||||
{
|
||||
@ -945,7 +996,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
console.log(`Received error for query ${thisQueryId}`);
|
||||
console.log(error);
|
||||
|
||||
var errorMessage;
|
||||
let errorMessage;
|
||||
if (error && error.message)
|
||||
{
|
||||
errorMessage = error.message;
|
||||
@ -1110,7 +1161,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
if (state && state.density && state.density.value !== density)
|
||||
{
|
||||
setDensity(state.density.value);
|
||||
localStorage.setItem(densityLocalStorageKey, JSON.stringify(state.density.value));
|
||||
localStorageSet(densityLocalStorageKey, JSON.stringify(state.density.value));
|
||||
}
|
||||
};
|
||||
|
||||
@ -1405,7 +1456,6 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
return (selectedIds.length);
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** get a query-string to put on the url to indicate what records are going into
|
||||
** a process.
|
||||
@ -1414,7 +1464,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
{
|
||||
if (selectFullFilterState === "filter")
|
||||
{
|
||||
const filterForBackend = prepQueryFilterForBackend(queryFilter);
|
||||
const filterForBackend = FilterUtils.prepQueryFilterForBackend(tableMetaData, queryFilter);
|
||||
filterForBackend.skip = 0;
|
||||
filterForBackend.limit = null;
|
||||
return `?recordsParam=filterJSON&filterJSON=${encodeURIComponent(JSON.stringify(filterForBackend))}`;
|
||||
@ -1422,7 +1472,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
|
||||
if (selectFullFilterState === "filterSubset")
|
||||
{
|
||||
const filterForBackend = prepQueryFilterForBackend(queryFilter);
|
||||
const filterForBackend = FilterUtils.prepQueryFilterForBackend(tableMetaData, queryFilter);
|
||||
filterForBackend.skip = 0;
|
||||
filterForBackend.limit = selectionSubsetSize;
|
||||
return `?recordsParam=filterJSON&filterJSON=${encodeURIComponent(JSON.stringify(filterForBackend))}`;
|
||||
@ -1445,14 +1495,14 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
{
|
||||
if (selectFullFilterState === "filter")
|
||||
{
|
||||
const filterForBackend = prepQueryFilterForBackend(queryFilter);
|
||||
const filterForBackend = FilterUtils.prepQueryFilterForBackend(tableMetaData, queryFilter);
|
||||
filterForBackend.skip = 0;
|
||||
filterForBackend.limit = null;
|
||||
setRecordIdsForProcess(filterForBackend);
|
||||
}
|
||||
else if (selectFullFilterState === "filterSubset")
|
||||
{
|
||||
const filterForBackend = prepQueryFilterForBackend(queryFilter);
|
||||
const filterForBackend = FilterUtils.prepQueryFilterForBackend(tableMetaData, queryFilter);
|
||||
filterForBackend.skip = 0;
|
||||
filterForBackend.limit = selectionSubsetSize;
|
||||
setRecordIdsForProcess(filterForBackend);
|
||||
@ -1607,7 +1657,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
////////////////////////////////////////////////////////////////
|
||||
// todo can/should/does this move into the view's "identity"? //
|
||||
////////////////////////////////////////////////////////////////
|
||||
localStorage.setItem(currentSavedViewLocalStorageKey, `${savedViewRecord.values.get("id")}`);
|
||||
localStorageSet(currentSavedViewLocalStorageKey, `${savedViewRecord.values.get("id")}`);
|
||||
};
|
||||
|
||||
|
||||
@ -1617,7 +1667,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
const doClearCurrentSavedView = () =>
|
||||
{
|
||||
setCurrentSavedView(null);
|
||||
localStorage.removeItem(currentSavedViewLocalStorageKey);
|
||||
localStorageRemove(currentSavedViewLocalStorageKey);
|
||||
};
|
||||
|
||||
|
||||
@ -1667,7 +1717,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
// wipe away the saved view //
|
||||
//////////////////////////////
|
||||
setCurrentSavedView(null);
|
||||
localStorage.removeItem(currentSavedViewLocalStorageKey);
|
||||
localStorageRemove(currentSavedViewLocalStorageKey);
|
||||
|
||||
///////////////////////////////////////////////
|
||||
// activate a new default view for the table //
|
||||
@ -1913,7 +1963,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
*******************************************************************************/
|
||||
const openColumnStatistics = async (column: GridColDef) =>
|
||||
{
|
||||
setFilterForColumnStats(prepQueryFilterForBackend(queryFilter));
|
||||
setFilterForColumnStats(FilterUtils.prepQueryFilterForBackend(tableMetaData, queryFilter));
|
||||
setColumnStatsFieldName(column.field);
|
||||
|
||||
const [field, fieldTable] = TableUtils.getFieldAndTable(tableMetaData, column.field);
|
||||
@ -2188,27 +2238,30 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
<GridToolbarDensitySelector nonce={undefined} />
|
||||
</div>
|
||||
|
||||
<div style={{zIndex: 10}}>
|
||||
<MenuButton label="Selection" iconName={selectedIds.length == 0 ? "check_box_outline_blank" : "check_box"} disabled={totalRecords == 0} options={selectionMenuOptions} callback={selectionMenuCallback} />
|
||||
<SelectionSubsetDialog isOpen={selectionSubsetSizePromptOpen} initialValue={selectionSubsetSize} closeHandler={(value) =>
|
||||
{
|
||||
setSelectionSubsetSizePromptOpen(false);
|
||||
|
||||
if (value !== undefined)
|
||||
{
|
||||
usage == "queryScreen" &&
|
||||
<div style={{zIndex: 10}}>
|
||||
<MenuButton label="Selection" iconName={selectedIds.length == 0 ? "check_box_outline_blank" : "check_box"} disabled={totalRecords == 0} options={selectionMenuOptions} callback={selectionMenuCallback} />
|
||||
<SelectionSubsetDialog isOpen={selectionSubsetSizePromptOpen} initialValue={selectionSubsetSize} closeHandler={(value) =>
|
||||
{
|
||||
if (typeof value === "number" && value > 0)
|
||||
setSelectionSubsetSizePromptOpen(false);
|
||||
|
||||
if (value !== undefined)
|
||||
{
|
||||
programmaticallySelectSomeOrAllRows(value);
|
||||
setSelectionSubsetSize(value);
|
||||
setSelectFullFilterState("filterSubset");
|
||||
if (typeof value === "number" && value > 0)
|
||||
{
|
||||
programmaticallySelectSomeOrAllRows(value);
|
||||
setSelectionSubsetSize(value);
|
||||
setSelectFullFilterState("filterSubset");
|
||||
}
|
||||
else
|
||||
{
|
||||
setAlertContent("Unexpected value: " + value);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
setAlertContent("Unexpected value: " + value);
|
||||
}
|
||||
}
|
||||
}} />
|
||||
</div>
|
||||
}} />
|
||||
</div>
|
||||
}
|
||||
|
||||
<div>
|
||||
{
|
||||
@ -2271,7 +2324,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
// to avoid both this useEffect and the one below from both doing an "initial query", //
|
||||
// only run this one if at least 1 query has already been ran //
|
||||
////////////////////////////////////////////////////////////////////////////////////////
|
||||
updateTable("useEffect(pageNumber,rowsPerPage)");
|
||||
updateTable("useEffect(pageNumber,rowsPerPage)", false);
|
||||
}
|
||||
}, [pageNumber, rowsPerPage]);
|
||||
|
||||
@ -2306,7 +2359,18 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
|
||||
if (pageState == "ready")
|
||||
{
|
||||
const newFilterHash = JSON.stringify(prepQueryFilterForBackend(queryFilter));
|
||||
const filterForBackend = FilterUtils.prepQueryFilterForBackend(tableMetaData, queryFilter);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
// remove the skip & limit (e.g., pagination) from this hash - //
|
||||
// as we have a specific useEffect watching these, specifically //
|
||||
// so we can pass the dont-clear-count flag into updateTable, //
|
||||
// to try to keep the count from flashing back & forth to "Counting" //
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
filterForBackend.skip = null;
|
||||
filterForBackend.limit = null;
|
||||
|
||||
const newFilterHash = JSON.stringify(filterForBackend);
|
||||
if (filterHash != newFilterHash)
|
||||
{
|
||||
setFilterHash(newFilterHash);
|
||||
@ -2477,11 +2541,14 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
// if the last time we were on this table, a currentSavedView was written to local storage - //
|
||||
// then navigate back to that view's URL - unless - it looks like we're on a process! //
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////
|
||||
if (localStorage.getItem(currentSavedViewLocalStorageKey) && !urlLooksLikeProcess())
|
||||
if (localStorage.getItem(currentSavedViewLocalStorageKey) && !urlLooksLikeProcess() && !loadedFilterFromInitialFilterParam)
|
||||
{
|
||||
const currentSavedViewId = Number.parseInt(localStorage.getItem(currentSavedViewLocalStorageKey));
|
||||
console.log(`returning to previously active saved view ${currentSavedViewId}`);
|
||||
navigate(`${metaData.getTablePathByName(tableName)}/savedView/${currentSavedViewId}`);
|
||||
if (usage == "queryScreen")
|
||||
{
|
||||
navigate(`${metaData.getTablePathByName(tableName)}/savedView/${currentSavedViewId}`);
|
||||
}
|
||||
setViewIdInLocation(currentSavedViewId);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
@ -2537,7 +2604,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
promptForTableVariantSelection();
|
||||
}
|
||||
|
||||
return (getLoadingScreen());
|
||||
return (getLoadingScreen(isModal));
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
@ -2571,7 +2638,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
setRows([]);
|
||||
setIsFirstRenderAfterChangingTables(true);
|
||||
|
||||
return (getLoadingScreen());
|
||||
return (getLoadingScreen(isModal));
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////
|
||||
@ -2615,7 +2682,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
if (pageState != "ready")
|
||||
{
|
||||
console.log(`page state is ${pageState}... no-op while those complete async's run...`);
|
||||
return (getLoadingScreen());
|
||||
return (getLoadingScreen(isModal));
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////////////
|
||||
@ -2624,13 +2691,13 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
///////////////////////////////////////////////////////////////////////////////////////////
|
||||
if (!tableMetaData)
|
||||
{
|
||||
return (getLoadingScreen());
|
||||
return (getLoadingScreen(isModal));
|
||||
}
|
||||
|
||||
let savedViewsComponent = null;
|
||||
if (metaData && metaData.processes.has("querySavedView"))
|
||||
{
|
||||
savedViewsComponent = (<SavedViews qController={qController} metaData={metaData} tableMetaData={tableMetaData} view={view} viewAsJson={viewAsJson} currentSavedView={currentSavedView} tableDefaultView={tableDefaultView} viewOnChangeCallback={handleSavedViewChange} loadingSavedView={loadingSavedView} />);
|
||||
savedViewsComponent = (<SavedViews qController={qController} metaData={metaData} tableMetaData={tableMetaData} view={view} viewAsJson={viewAsJson} currentSavedView={currentSavedView} tableDefaultView={tableDefaultView} viewOnChangeCallback={handleSavedViewChange} loadingSavedView={loadingSavedView} queryScreenUsage={usage} />);
|
||||
}
|
||||
|
||||
|
||||
@ -2707,7 +2774,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// these numbers help set the height of the grid (so page won't scroll) based on spcae above & below it //
|
||||
// these numbers help set the height of the grid (so page won't scroll) based on space above & below it //
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
let spaceBelowGrid = 40;
|
||||
let spaceAboveGrid = 205;
|
||||
@ -2721,40 +2788,48 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
spaceAboveGrid += 60;
|
||||
}
|
||||
|
||||
if (isModal)
|
||||
{
|
||||
spaceAboveGrid += 130;
|
||||
}
|
||||
|
||||
////////////////////////
|
||||
// main screen render //
|
||||
////////////////////////
|
||||
return (
|
||||
<BaseLayout>
|
||||
const body = (
|
||||
<React.Fragment>
|
||||
<Box display="flex" justifyContent="space-between">
|
||||
<Box>
|
||||
<Typography textTransform="capitalize" variant="h3">
|
||||
{pageLoadingState.isLoading() && ""}
|
||||
{pageLoadingState.isLoadingSlow() && "Loading..."}
|
||||
{pageLoadingState.isNotLoading() && getPageHeader(tableMetaData, visibleJoinTables, tableVariant)}
|
||||
{pageLoadingState.isNotLoading() && !isModal && getPageHeader(tableMetaData, visibleJoinTables, tableVariant)}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box whiteSpace="nowrap">
|
||||
<GotoRecordButton metaData={metaData} tableMetaData={tableMetaData} />
|
||||
<Box display="inline-block" width="150px">
|
||||
{
|
||||
!isModal &&
|
||||
<Box whiteSpace="nowrap">
|
||||
<GotoRecordButton metaData={metaData} tableMetaData={tableMetaData} />
|
||||
<Box display="inline-block" width="150px">
|
||||
{
|
||||
tableMetaData &&
|
||||
<QueryScreenActionMenu
|
||||
metaData={metaData}
|
||||
tableMetaData={tableMetaData}
|
||||
tableProcesses={tableProcesses}
|
||||
bulkLoadClicked={bulkLoadClicked}
|
||||
bulkEditClicked={bulkEditClicked}
|
||||
bulkDeleteClicked={bulkDeleteClicked}
|
||||
processClicked={processClicked}
|
||||
/>
|
||||
}
|
||||
</Box>
|
||||
{
|
||||
tableMetaData &&
|
||||
<QueryScreenActionMenu
|
||||
metaData={metaData}
|
||||
tableMetaData={tableMetaData}
|
||||
tableProcesses={tableProcesses}
|
||||
bulkLoadClicked={bulkLoadClicked}
|
||||
bulkEditClicked={bulkEditClicked}
|
||||
bulkDeleteClicked={bulkDeleteClicked}
|
||||
processClicked={processClicked}
|
||||
/>
|
||||
table.capabilities.has(Capability.TABLE_INSERT) && table.insertPermission &&
|
||||
<QCreateNewButton tablePath={metaData?.getTablePathByName(tableName)} />
|
||||
}
|
||||
</Box>
|
||||
{
|
||||
table.capabilities.has(Capability.TABLE_INSERT) && table.insertPermission &&
|
||||
<QCreateNewButton tablePath={metaData?.getTablePathByName(tableName)} />
|
||||
}
|
||||
</Box>
|
||||
}
|
||||
</Box>
|
||||
<div className="recordQuery">
|
||||
{/*
|
||||
@ -2808,6 +2883,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
setQuickFilterFieldNames={doSetQuickFilterFieldNames}
|
||||
gridApiRef={gridApiRef}
|
||||
mode={mode}
|
||||
queryScreenUsage={usage}
|
||||
setMode={doSetMode}
|
||||
savedViewsComponent={savedViewsComponent}
|
||||
columnMenuComponent={buildColumnMenu()}
|
||||
@ -2832,6 +2908,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
filterPanel:
|
||||
{
|
||||
tableMetaData: tableMetaData,
|
||||
queryScreenUsage: usage,
|
||||
metaData: metaData,
|
||||
queryFilter: queryFilter,
|
||||
updateFilter: doSetQueryFilter,
|
||||
@ -2848,7 +2925,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
sortingMode="server"
|
||||
filterMode="server"
|
||||
page={pageNumber}
|
||||
checkboxSelection
|
||||
checkboxSelection={usage == "queryScreen"}
|
||||
disableSelectionOnClick
|
||||
autoHeight={false}
|
||||
rows={rows}
|
||||
@ -2857,7 +2934,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
rowBuffer={10}
|
||||
rowCount={totalRecords === null || totalRecords === undefined ? 0 : totalRecords}
|
||||
onPageSizeChange={handleRowsPerPageChange}
|
||||
onRowClick={handleRowClick}
|
||||
onRowClick={usage == "queryScreen" ? handleRowClick : null}
|
||||
onStateChange={handleStateChange}
|
||||
density={density}
|
||||
loading={loading}
|
||||
@ -2915,8 +2992,28 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
|
||||
</Modal>
|
||||
}
|
||||
</div>
|
||||
</BaseLayout>
|
||||
</React.Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
if (isModal)
|
||||
{
|
||||
return body;
|
||||
}
|
||||
|
||||
return (
|
||||
<BaseLayout>{body}</BaseLayout>
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
RecordQuery.defaultProps = {
|
||||
table: null,
|
||||
usage: "queryScreen",
|
||||
launchProcess: null,
|
||||
isModal: false,
|
||||
initialQueryFilter: null,
|
||||
initialColumns: null,
|
||||
};
|
||||
|
||||
|
||||
export default RecordQuery;
|
||||
|
@ -21,6 +21,7 @@
|
||||
|
||||
import {QException} from "@kingsrook/qqq-frontend-core/lib/exceptions/QException";
|
||||
import {Capability} from "@kingsrook/qqq-frontend-core/lib/model/metaData/Capability";
|
||||
import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData";
|
||||
import {QInstance} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QInstance";
|
||||
import {QProcessMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QProcessMetaData";
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
@ -49,11 +50,13 @@ import Tooltip from "@mui/material/Tooltip/Tooltip";
|
||||
import QContext from "QContext";
|
||||
import colors from "qqq/assets/theme/base/colors";
|
||||
import AuditBody from "qqq/components/audits/AuditBody";
|
||||
import {QActionsMenuButton, QCancelButton, QDeleteButton, QEditButton} from "qqq/components/buttons/DefaultButtons";
|
||||
import {QActionsMenuButton, QCancelButton, QDeleteButton, QEditButton, standardWidth} from "qqq/components/buttons/DefaultButtons";
|
||||
import EntityForm from "qqq/components/forms/EntityForm";
|
||||
import MDButton from "qqq/components/legacy/MDButton";
|
||||
import {GotoRecordButton} from "qqq/components/misc/GotoRecordDialog";
|
||||
import HelpContent, {hasHelpContent} from "qqq/components/misc/HelpContent";
|
||||
import QRecordSidebar from "qqq/components/misc/RecordSidebar";
|
||||
import ShareModal from "qqq/components/sharing/ShareModal";
|
||||
import DashboardWidgets from "qqq/components/widgets/DashboardWidgets";
|
||||
import BaseLayout from "qqq/layouts/BaseLayout";
|
||||
import ProcessRun from "qqq/pages/processes/ProcessRun";
|
||||
@ -71,18 +74,94 @@ const qController = Client.getInstance();
|
||||
interface Props
|
||||
{
|
||||
table?: QTableMetaData;
|
||||
record?: QRecord;
|
||||
launchProcess?: QProcessMetaData;
|
||||
}
|
||||
|
||||
RecordView.defaultProps =
|
||||
{
|
||||
table: null,
|
||||
record: null,
|
||||
launchProcess: null,
|
||||
};
|
||||
|
||||
const TABLE_VARIANT_LOCAL_STORAGE_KEY_ROOT = "qqq.tableVariant";
|
||||
|
||||
function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
export function renderSectionOfFields(key: string, fieldNames: string[], tableMetaData: QTableMetaData, helpHelpActive: boolean, record: QRecord, fieldMap?: {[name: string]: QFieldMetaData} )
|
||||
{
|
||||
return <Box key={key} display="flex" flexDirection="column" py={1} pr={2}>
|
||||
{
|
||||
fieldNames.map((fieldName: string) =>
|
||||
{
|
||||
let [field, tableForField] = tableMetaData ? TableUtils.getFieldAndTable(tableMetaData, fieldName) : fieldMap ? [fieldMap[fieldName], null] : [null, null];
|
||||
|
||||
if (field != null)
|
||||
{
|
||||
let label = field.label;
|
||||
|
||||
const helpRoles = ["VIEW_SCREEN", "READ_SCREENS", "ALL_SCREENS"];
|
||||
const showHelp = helpHelpActive || hasHelpContent(field.helpContents, helpRoles);
|
||||
const formattedHelpContent = <HelpContent helpContents={field.helpContents} roles={helpRoles} heading={label} helpContentKey={`table:${tableMetaData?.name};field:${fieldName}`} />;
|
||||
|
||||
const labelElement = <Typography variant="button" textTransform="none" fontWeight="bold" pr={1} color="rgb(52, 71, 103)" sx={{cursor: "default"}}>{label}:</Typography>;
|
||||
|
||||
return (
|
||||
<Box key={fieldName} flexDirection="row" pr={2}>
|
||||
<>
|
||||
{
|
||||
showHelp && formattedHelpContent ? <Tooltip title={formattedHelpContent}>{labelElement}</Tooltip> : labelElement
|
||||
}
|
||||
<div style={{display: "inline-block", width: 0}}> </div>
|
||||
<Typography variant="button" textTransform="none" fontWeight="regular" color="rgb(123, 128, 154)">
|
||||
{ValueUtils.getDisplayValue(field, record, "view", fieldName)}
|
||||
</Typography>
|
||||
</>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
</Box>;
|
||||
}
|
||||
|
||||
|
||||
/***************************************************************************
|
||||
**
|
||||
***************************************************************************/
|
||||
export function getVisibleJoinTables(tableMetaData: QTableMetaData): Set<string>
|
||||
{
|
||||
const visibleJoinTables = new Set<string>();
|
||||
|
||||
for (let i = 0; i < tableMetaData?.sections.length; i++)
|
||||
{
|
||||
const section = tableMetaData?.sections[i];
|
||||
if (section.isHidden || !section.fieldNames || !section.fieldNames.length)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
section.fieldNames.forEach((fieldName) =>
|
||||
{
|
||||
const [field, tableForField] = TableUtils.getFieldAndTable(tableMetaData, fieldName);
|
||||
if (tableForField && tableForField.name != tableMetaData.name)
|
||||
{
|
||||
visibleJoinTables.add(tableForField.name);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return (visibleJoinTables);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Record View Screen component.
|
||||
*******************************************************************************/
|
||||
function RecordView({table, record: overrideRecord, launchProcess}: Props): JSX.Element
|
||||
{
|
||||
const {id} = useParams();
|
||||
|
||||
@ -99,7 +178,7 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
const [adornmentFieldsMap, setAdornmentFieldsMap] = useState(new Map<string, boolean>);
|
||||
const [deleteConfirmationOpen, setDeleteConfirmationOpen] = useState(false);
|
||||
const [metaData, setMetaData] = useState(null as QInstance);
|
||||
const [record, setRecord] = useState(null as QRecord);
|
||||
const [record, setRecord] = useState(overrideRecord ?? null as QRecord);
|
||||
const [tableSections, setTableSections] = useState([] as QTableSection[]);
|
||||
const [t1Section, setT1Section] = useState(null as QTableSection);
|
||||
const [t1SectionName, setT1SectionName] = useState(null as string);
|
||||
@ -117,11 +196,14 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
const [launchingProcess, setLaunchingProcess] = useState(launchProcess);
|
||||
const [showEditChildForm, setShowEditChildForm] = useState(null as any);
|
||||
const [showAudit, setShowAudit] = useState(false);
|
||||
const [showShareModal, setShowShareModal] = useState(false);
|
||||
|
||||
const [isDeleteSubmitting, setIsDeleteSubmitting] = useState(false);
|
||||
|
||||
const openActionsMenu = (event: any) => setActionsMenu(event.currentTarget);
|
||||
const closeActionsMenu = () => setActionsMenu(null);
|
||||
|
||||
const {accentColor, setPageHeader, tableMetaData, setTableMetaData, tableProcesses, setTableProcesses, dotMenuOpen, keyboardHelpOpen, helpHelpActive, recordAnalytics} = useContext(QContext);
|
||||
const {accentColor, setPageHeader, tableMetaData, setTableMetaData, tableProcesses, setTableProcesses, dotMenuOpen, keyboardHelpOpen, helpHelpActive, recordAnalytics, userId: currentUserId} = useContext(QContext);
|
||||
|
||||
if (localStorage.getItem(tableVariantLocalStorageKey))
|
||||
{
|
||||
@ -330,31 +412,6 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
reload();
|
||||
}, [location.pathname, location.hash]);
|
||||
|
||||
const getVisibleJoinTables = (tableMetaData: QTableMetaData): Set<string> =>
|
||||
{
|
||||
const visibleJoinTables = new Set<string>();
|
||||
|
||||
for (let i = 0; i < tableMetaData?.sections.length; i++)
|
||||
{
|
||||
const section = tableMetaData?.sections[i];
|
||||
if (section.isHidden || !section.fieldNames || !section.fieldNames.length)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
section.fieldNames.forEach((fieldName) =>
|
||||
{
|
||||
const [field, tableForField] = TableUtils.getFieldAndTable(tableMetaData, fieldName);
|
||||
if (tableForField && tableForField.name != tableMetaData.name)
|
||||
{
|
||||
visibleJoinTables.add(tableForField.name);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return (visibleJoinTables);
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** get an element (or empty) to use as help content for a section
|
||||
@ -430,7 +487,18 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
let record: QRecord;
|
||||
try
|
||||
{
|
||||
record = await qController.get(tableName, id, tableVariant, null, queryJoins);
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// if the component took in a record object, then we don't need to GET it //
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
if(overrideRecord)
|
||||
{
|
||||
record = overrideRecord;
|
||||
}
|
||||
else
|
||||
{
|
||||
record = await qController.get(tableName, id, tableVariant, null, queryJoins);
|
||||
}
|
||||
|
||||
setRecord(record);
|
||||
recordAnalytics({category: "tableEvents", action: "view", label: tableMetaData?.label + " / " + record?.recordLabel});
|
||||
}
|
||||
@ -467,7 +535,7 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
|
||||
setPageHeader(record.recordLabel);
|
||||
|
||||
if (!launchingProcess)
|
||||
if (!launchingProcess && !activeModalProcess)
|
||||
{
|
||||
try
|
||||
{
|
||||
@ -508,7 +576,7 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
sectionFieldElements.set(section.name,
|
||||
<Grid id={section.name} key={section.name} item lg={widgetMetaData.gridColumns ? widgetMetaData.gridColumns : 12} xs={12} sx={{display: "flex", alignItems: "stretch", flexGrow: 1, scrollMarginTop: "100px"}}>
|
||||
<Box width="100%" flexGrow={1} alignItems="stretch">
|
||||
<DashboardWidgets key={section.name} tableName={tableMetaData.name} widgetMetaDataList={[widgetMetaData]} entityPrimaryKey={record.values.get(tableMetaData.primaryKeyField)} omitWrappingGridContainer={true} />
|
||||
<DashboardWidgets key={section.name} tableName={tableMetaData.name} widgetMetaDataList={[widgetMetaData]} record={record} entityPrimaryKey={record.values.get(tableMetaData.primaryKeyField)} omitWrappingGridContainer={true} />
|
||||
</Box>
|
||||
</Grid>
|
||||
);
|
||||
@ -519,40 +587,7 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
// for a section with field names, render the field values. //
|
||||
// for the T1 section, the "wrapper" will come out below - but for other sections, produce a wrapper too. //
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
const fields = (
|
||||
<Box key={section.name} display="flex" flexDirection="column" py={1} pr={2}>
|
||||
{
|
||||
section.fieldNames.map((fieldName: string) =>
|
||||
{
|
||||
let [field, tableForField] = TableUtils.getFieldAndTable(tableMetaData, fieldName);
|
||||
if (field != null)
|
||||
{
|
||||
let label = field.label;
|
||||
|
||||
const helpRoles = ["VIEW_SCREEN", "READ_SCREENS", "ALL_SCREENS"];
|
||||
const showHelp = helpHelpActive || hasHelpContent(field.helpContents, helpRoles);
|
||||
const formattedHelpContent = <HelpContent helpContents={field.helpContents} roles={helpRoles} heading={label} helpContentKey={`table:${tableName};field:${fieldName}`} />;
|
||||
|
||||
const labelElement = <Typography variant="button" textTransform="none" fontWeight="bold" pr={1} color="rgb(52, 71, 103)" sx={{cursor: "default"}}>{label}:</Typography>;
|
||||
|
||||
return (
|
||||
<Box key={fieldName} flexDirection="row" pr={2}>
|
||||
<>
|
||||
{
|
||||
showHelp && formattedHelpContent ? <Tooltip title={formattedHelpContent}>{labelElement}</Tooltip> : labelElement
|
||||
}
|
||||
<div style={{display: "inline-block", width: 0}}> </div>
|
||||
<Typography variant="button" textTransform="none" fontWeight="regular" color="rgb(123, 128, 154)">
|
||||
{ValueUtils.getDisplayValue(field, record, "view", fieldName)}
|
||||
</Typography>
|
||||
</>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
</Box>
|
||||
);
|
||||
const fields = renderSectionOfFields(section.name, section.fieldNames, tableMetaData, helpHelpActive, record);
|
||||
|
||||
if (section.tier === "T1")
|
||||
{
|
||||
@ -622,6 +657,7 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
const handleClickDeleteButton = () =>
|
||||
{
|
||||
setDeleteConfirmationOpen(true);
|
||||
setIsDeleteSubmitting(false);
|
||||
};
|
||||
|
||||
const handleDeleteConfirmClose = () =>
|
||||
@ -631,6 +667,7 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
|
||||
const handleDelete = (event: { preventDefault: () => void }) =>
|
||||
{
|
||||
setIsDeleteSubmitting(true);
|
||||
event?.preventDefault();
|
||||
(async () =>
|
||||
{
|
||||
@ -639,11 +676,13 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
await qController.delete(tableName, id)
|
||||
.then(() =>
|
||||
{
|
||||
setIsDeleteSubmitting(false);
|
||||
const path = pathParts.slice(0, -1).join("/");
|
||||
navigate(path, {state: {deleteSuccess: true}});
|
||||
})
|
||||
.catch((error) =>
|
||||
{
|
||||
setIsDeleteSubmitting(false);
|
||||
setDeleteConfirmationOpen(false);
|
||||
console.log("Caught:");
|
||||
console.log(error);
|
||||
@ -759,6 +798,68 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
</Menu>
|
||||
);
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** function to open the sharing modal
|
||||
*******************************************************************************/
|
||||
const openShareModal = () =>
|
||||
{
|
||||
setShowShareModal(true);
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** function to close the sharing modal
|
||||
*******************************************************************************/
|
||||
const closeShareModal = () =>
|
||||
{
|
||||
setShowShareModal(false);
|
||||
};
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** render the share button (if allowed for table)
|
||||
*******************************************************************************/
|
||||
const renderShareButton = () =>
|
||||
{
|
||||
if (tableMetaData && tableMetaData.shareableTableMetaData)
|
||||
{
|
||||
let shareDisabled = true;
|
||||
let disabledTooltipText = "";
|
||||
if(tableMetaData.shareableTableMetaData.thisTableOwnerIdFieldName && record)
|
||||
{
|
||||
const ownerId = record.values.get(tableMetaData.shareableTableMetaData.thisTableOwnerIdFieldName);
|
||||
if(ownerId != currentUserId)
|
||||
{
|
||||
disabledTooltipText = `Only the owner of a ${tableMetaData.label} may share it.`
|
||||
shareDisabled = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
disabledTooltipText = "";
|
||||
shareDisabled = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
shareDisabled = false;
|
||||
}
|
||||
|
||||
return (<Box width={standardWidth} mr={2}>
|
||||
<Tooltip title={disabledTooltipText}>
|
||||
<span>
|
||||
<MDButton id="shareButton" type="button" color="info" size="small" onClick={() => openShareModal()} fullWidth startIcon={<Icon>group_add</Icon>} disabled={shareDisabled}>
|
||||
Share
|
||||
</MDButton>
|
||||
</span>
|
||||
</Tooltip>
|
||||
</Box>);
|
||||
}
|
||||
|
||||
return (<React.Fragment />);
|
||||
};
|
||||
|
||||
|
||||
const openModalProcess = (process: QProcessMetaData = null) =>
|
||||
{
|
||||
navigate(process.name);
|
||||
@ -850,7 +951,7 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
|
||||
return (
|
||||
<BaseLayout>
|
||||
<Box>
|
||||
<Box className="recordView">
|
||||
<Grid container>
|
||||
<Grid item xs={12}>
|
||||
<Box mb={3}>
|
||||
@ -914,6 +1015,7 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
</Typography>
|
||||
<Box display="flex">
|
||||
<GotoRecordButton metaData={metaData} tableMetaData={tableMetaData} />
|
||||
{renderShareButton()}
|
||||
<QActionsMenuButton isOpen={actionsMenu} onClickHandler={openActionsMenu} />
|
||||
</Box>
|
||||
{renderActionsMenu}
|
||||
@ -962,7 +1064,7 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={handleDeleteConfirmClose}>No</Button>
|
||||
<Button onClick={handleDelete} autoFocus>
|
||||
<Button onClick={handleDelete} autoFocus disabled={isDeleteSubmitting}>
|
||||
Yes
|
||||
</Button>
|
||||
</DialogActions>
|
||||
@ -979,7 +1081,7 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
|
||||
{
|
||||
showEditChildForm &&
|
||||
<Modal open={showEditChildForm as boolean} onClose={(event, reason) => closeEditChildForm(event, reason)}>
|
||||
<Modal open={showEditChildForm !== null} onClose={(event, reason) => closeEditChildForm(event, reason)}>
|
||||
<div className="modalEditForm">
|
||||
<EntityForm
|
||||
isModal={true}
|
||||
@ -1010,6 +1112,11 @@ function RecordView({table, launchProcess}: Props): JSX.Element
|
||||
</Modal>
|
||||
}
|
||||
|
||||
{
|
||||
showShareModal && tableMetaData && record &&
|
||||
<ShareModal open={showShareModal} onClose={closeShareModal} tableMetaData={tableMetaData} record={record}></ShareModal>
|
||||
}
|
||||
|
||||
</Box>
|
||||
}
|
||||
</Box>
|
||||
|
163
src/qqq/pages/records/view/RecordViewByUniqueKey.tsx
Normal file
163
src/qqq/pages/records/view/RecordViewByUniqueKey.tsx
Normal file
@ -0,0 +1,163 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import {QRecord} from "@kingsrook/qqq-frontend-core/lib/model/QRecord";
|
||||
import {QCriteriaOperator} from "@kingsrook/qqq-frontend-core/lib/model/query/QCriteriaOperator";
|
||||
import {QFilterCriteria} from "@kingsrook/qqq-frontend-core/lib/model/query/QFilterCriteria";
|
||||
import {QQueryFilter} from "@kingsrook/qqq-frontend-core/lib/model/query/QQueryFilter";
|
||||
import {QueryJoin} from "@kingsrook/qqq-frontend-core/lib/model/query/QueryJoin";
|
||||
import {Alert, Box} from "@mui/material";
|
||||
import Grid from "@mui/material/Grid";
|
||||
import BaseLayout from "qqq/layouts/BaseLayout";
|
||||
import RecordView, {getVisibleJoinTables} from "qqq/pages/records/view/RecordView";
|
||||
import Client from "qqq/utils/qqq/Client";
|
||||
import TableUtils from "qqq/utils/qqq/TableUtils";
|
||||
import React, {useEffect, useState} from "react";
|
||||
import {useSearchParams} from "react-router-dom";
|
||||
|
||||
interface RecordViewByUniqueKeyProps
|
||||
{
|
||||
table: QTableMetaData;
|
||||
}
|
||||
|
||||
RecordViewByUniqueKey.defaultProps = {};
|
||||
|
||||
const qController = Client.getInstance();
|
||||
|
||||
/***************************************************************************
|
||||
** Wrapper around RecordView, that reads a unique key from the query string,
|
||||
** looks for a record matching that key, and shows that record.
|
||||
***************************************************************************/
|
||||
export default function RecordViewByUniqueKey({table}: RecordViewByUniqueKeyProps): JSX.Element
|
||||
{
|
||||
const tableName = table.name;
|
||||
|
||||
const [asyncLoadInited, setAsyncLoadInited] = useState(false);
|
||||
const [tableMetaData, setTableMetaData] = useState(null as QTableMetaData);
|
||||
const [doneLoading, setDoneLoading] = useState(false);
|
||||
const [record, setRecord] = useState(null as QRecord);
|
||||
const [errorMessage, setErrorMessage] = useState(null as string);
|
||||
|
||||
const [queryParams] = useSearchParams();
|
||||
|
||||
if (!asyncLoadInited)
|
||||
{
|
||||
setAsyncLoadInited(true);
|
||||
|
||||
(async () =>
|
||||
{
|
||||
const tableMetaData = await qController.loadTableMetaData(tableName);
|
||||
setTableMetaData(tableMetaData);
|
||||
|
||||
const criteria: QFilterCriteria[] = [];
|
||||
for (let [name, value] of queryParams.entries())
|
||||
{
|
||||
criteria.push(new QFilterCriteria(name, QCriteriaOperator.EQUALS, [value]));
|
||||
if(!tableMetaData.fields.has(name))
|
||||
{
|
||||
setErrorMessage(`Query-string parameter [${name}] is not a defined field on the ${tableMetaData.label} table.`);
|
||||
setDoneLoading(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let queryJoins: QueryJoin[] = null;
|
||||
const visibleJoinTables = getVisibleJoinTables(tableMetaData);
|
||||
if (visibleJoinTables.size > 0)
|
||||
{
|
||||
queryJoins = TableUtils.getQueryJoins(tableMetaData, visibleJoinTables);
|
||||
}
|
||||
|
||||
const filter = new QQueryFilter(criteria, null, null, "AND", 0, 2);
|
||||
qController.query(tableName, filter, queryJoins)
|
||||
.then((queryResult) =>
|
||||
{
|
||||
setDoneLoading(true);
|
||||
if (queryResult.length == 1)
|
||||
{
|
||||
setRecord(queryResult[0]);
|
||||
}
|
||||
else if (queryResult.length == 0)
|
||||
{
|
||||
setErrorMessage(`No ${tableMetaData.label} record was found matching the given values.`);
|
||||
}
|
||||
else if (queryResult.length > 1)
|
||||
{
|
||||
setErrorMessage(`More than one ${tableMetaData.label} record was found matching the given values.`);
|
||||
}
|
||||
})
|
||||
.catch((error) =>
|
||||
{
|
||||
setDoneLoading(true);
|
||||
console.log(error);
|
||||
if (error && error.message)
|
||||
{
|
||||
setErrorMessage(error.message);
|
||||
}
|
||||
else if (error && error.response && error.response.data && error.response.data.error)
|
||||
{
|
||||
setErrorMessage(error.response.data.error);
|
||||
}
|
||||
else
|
||||
{
|
||||
setErrorMessage("Unexpected error running query");
|
||||
}
|
||||
});
|
||||
})();
|
||||
}
|
||||
|
||||
useEffect(() =>
|
||||
{
|
||||
if (asyncLoadInited)
|
||||
{
|
||||
setAsyncLoadInited(false);
|
||||
setDoneLoading(false);
|
||||
setRecord(null);
|
||||
}
|
||||
}, [queryParams]);
|
||||
|
||||
if (!doneLoading)
|
||||
{
|
||||
return (<div>Loading...</div>);
|
||||
}
|
||||
else if (record)
|
||||
{
|
||||
return (<RecordView table={table} record={record} />);
|
||||
}
|
||||
else if (errorMessage)
|
||||
{
|
||||
return (<BaseLayout>
|
||||
<Box className="recordView">
|
||||
<Grid container>
|
||||
<Grid item xs={12}>
|
||||
<Box mb={3}>
|
||||
{
|
||||
<Alert color="error" sx={{mb: 3}}>{errorMessage}</Alert>
|
||||
}
|
||||
</Box>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Box>
|
||||
</BaseLayout>);
|
||||
}
|
||||
}
|
@ -421,6 +421,14 @@ input[type="search"]::-webkit-search-results-decoration
|
||||
font-size: 2rem !important;
|
||||
}
|
||||
|
||||
.dashboard-order-release-icon
|
||||
{
|
||||
font-size: 1.5rem !important;
|
||||
position: relative;
|
||||
top: -5px;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.dashboard-schedule-icon
|
||||
{
|
||||
font-size: 1.1rem !important;
|
||||
@ -653,6 +661,11 @@ input[type="search"]::-webkit-search-results-decoration
|
||||
min-height: unset !important;
|
||||
}
|
||||
|
||||
.MuiDataGrid-columnHeaders
|
||||
{
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
|
||||
/* new style for toggle buttons */
|
||||
.MuiToggleButtonGroup-root
|
||||
{
|
||||
@ -682,8 +695,92 @@ input[type="search"]::-webkit-search-results-decoration
|
||||
border: none;
|
||||
}
|
||||
|
||||
.entityForm h5,
|
||||
.recordView h5
|
||||
{
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.recordView .widget
|
||||
{
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.entityForm .widget
|
||||
{
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.recordView .widget .recordGridWidget
|
||||
{
|
||||
margin: -8px;
|
||||
}
|
||||
|
||||
.MuiPickersDay-root.Mui-selected, .MuiPickersDay-root.MuiPickersDay-dayWithMargin:hover
|
||||
{
|
||||
color: white;
|
||||
background-color: #0062FF !important;
|
||||
}
|
||||
|
||||
.helpContentAlert
|
||||
{
|
||||
padding: 6px 16px;
|
||||
font-size: 1rem;
|
||||
font-weight: 300;
|
||||
line-height: 1.6;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.helpContentAlert .MuiAlert-icon
|
||||
{
|
||||
display: flex;
|
||||
margin-right: 12px;
|
||||
padding: 7px 0;
|
||||
font-size: 22px;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.helpContentAlert .MuiAlert-icon .material-icons-round
|
||||
{
|
||||
display: inline-block;
|
||||
width: 1em;
|
||||
height: 1em;
|
||||
}
|
||||
|
||||
.helpContentAlert .MuiAlert-message
|
||||
{
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.helpContentAlert.success
|
||||
{
|
||||
background-color: rgb(240, 248, 241);
|
||||
color: rgb(44, 76, 46);
|
||||
}
|
||||
|
||||
.helpContentAlert.success .MuiAlert-icon .material-icons-round
|
||||
{
|
||||
color: #4CAF50;
|
||||
}
|
||||
|
||||
.helpContentAlert.warning
|
||||
{
|
||||
background-color: rgb(254, 245, 234);
|
||||
color: rgb(100, 65, 20);
|
||||
}
|
||||
|
||||
.helpContentAlert.warning .MuiAlert-icon .material-icons-round
|
||||
{
|
||||
color: #fb8c00;
|
||||
}
|
||||
|
||||
.helpContentAlert.error
|
||||
{
|
||||
background-color: rgb(254, 239, 238);
|
||||
color: rgb(98, 41, 37);
|
||||
}
|
||||
|
||||
.helpContentAlert.error .MuiAlert-icon .material-icons-round
|
||||
{
|
||||
color: #F44335;
|
||||
}
|
||||
|
@ -23,6 +23,7 @@ import {QController} from "@kingsrook/qqq-frontend-core/lib/controllers/QControl
|
||||
import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData";
|
||||
import {QFieldType} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldType";
|
||||
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
|
||||
import {FilterVariableExpression} from "@kingsrook/qqq-frontend-core/lib/model/query/FilterVariableExpression";
|
||||
import {NowExpression} from "@kingsrook/qqq-frontend-core/lib/model/query/NowExpression";
|
||||
import {NowWithOffsetExpression} from "@kingsrook/qqq-frontend-core/lib/model/query/NowWithOffsetExpression";
|
||||
import {QCriteriaOperator} from "@kingsrook/qqq-frontend-core/lib/model/query/QCriteriaOperator";
|
||||
@ -32,6 +33,7 @@ import {QQueryFilter} from "@kingsrook/qqq-frontend-core/lib/model/query/QQueryF
|
||||
import {ThisOrLastPeriodExpression} from "@kingsrook/qqq-frontend-core/lib/model/query/ThisOrLastPeriodExpression";
|
||||
import Box from "@mui/material/Box";
|
||||
import {GridSortModel} from "@mui/x-data-grid-pro";
|
||||
import {validateCriteria} from "qqq/components/query/FilterCriteriaRow";
|
||||
import TableUtils from "qqq/utils/qqq/TableUtils";
|
||||
import ValueUtils from "qqq/utils/qqq/ValueUtils";
|
||||
|
||||
@ -107,6 +109,8 @@ class FilterUtils
|
||||
let [field, fieldTable] = TableUtils.getFieldAndTable(tableMetaData, criteria.fieldName);
|
||||
|
||||
let values = criteria.values;
|
||||
let hasFilterVariable = false;
|
||||
|
||||
if (field.possibleValueSourceName)
|
||||
{
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
@ -120,7 +124,17 @@ class FilterUtils
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
if (values && values.length > 0 && values[0] !== null && values[0] !== undefined && values[0] !== "")
|
||||
{
|
||||
values = await qController.possibleValues(fieldTable.name, null, field.name, "", values);
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
// do not do this lookup if the field is a filter variable expression //
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
if (values[0].type && values[0].type == "FilterVariableExpression")
|
||||
{
|
||||
hasFilterVariable = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
values = await qController.possibleValues(fieldTable.name, null, field.name, "", values);
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////
|
||||
@ -231,6 +245,10 @@ class FilterUtils
|
||||
{
|
||||
return (new ThisOrLastPeriodExpression(value));
|
||||
}
|
||||
else if (value.type == "FilterVariableExpression")
|
||||
{
|
||||
return (new FilterVariableExpression(value));
|
||||
}
|
||||
}
|
||||
|
||||
return (null);
|
||||
@ -364,7 +382,12 @@ class FilterUtils
|
||||
for (let i = 0; i < maxLoops; i++)
|
||||
{
|
||||
const value = criteria.values[i];
|
||||
if (value.type == "NowWithOffset")
|
||||
if (value.type == "FilterVariableExpression")
|
||||
{
|
||||
const expression = new FilterVariableExpression(value);
|
||||
labels.push(expression.toString());
|
||||
}
|
||||
else if (value.type == "NowWithOffset")
|
||||
{
|
||||
const expression = new NowWithOffsetExpression(value);
|
||||
labels.push(expression.toString());
|
||||
@ -612,6 +635,58 @@ class FilterUtils
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** make a new query filter, based on the input one, but w/ values good for the
|
||||
** backend. such as, possible values as just ids, not objects w/ a label;
|
||||
** date-times formatted properly and in UTC
|
||||
*******************************************************************************/
|
||||
public static prepQueryFilterForBackend(tableMetaData: QTableMetaData, sourceFilter: QQueryFilter, pageNumber?: number, rowsPerPage?: number): QQueryFilter
|
||||
{
|
||||
const filterForBackend = new QQueryFilter([], sourceFilter.orderBys, sourceFilter.subFilters, sourceFilter.booleanOperator);
|
||||
for (let i = 0; i < sourceFilter?.criteria?.length; i++)
|
||||
{
|
||||
const criteria = sourceFilter.criteria[i];
|
||||
const {criteriaIsValid} = validateCriteria(criteria, null);
|
||||
if (criteriaIsValid)
|
||||
{
|
||||
if (criteria.operator == QCriteriaOperator.IS_BLANK || criteria.operator == QCriteriaOperator.IS_NOT_BLANK)
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////////////////////////////
|
||||
// do this to avoid submitting an empty-string argument for blank/not-blank operators... //
|
||||
///////////////////////////////////////////////////////////////////////////////////////////
|
||||
filterForBackend.criteria.push(new QFilterCriteria(criteria.fieldName, criteria.operator, []));
|
||||
}
|
||||
else
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// else push a clone of the criteria - since it may get manipulated below (convertFilterPossibleValuesToIds) //
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
const [field] = FilterUtils.getField(tableMetaData, criteria.fieldName);
|
||||
filterForBackend.criteria.push(new QFilterCriteria(criteria.fieldName, criteria.operator, FilterUtils.cleanseCriteriaValueForQQQ(criteria.values, field)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/////////////////////////////////////////
|
||||
// recursively prep subfilters as well //
|
||||
/////////////////////////////////////////
|
||||
let subFilters = [] as QQueryFilter[];
|
||||
for (let j = 0; j < sourceFilter?.subFilters?.length; j++)
|
||||
{
|
||||
subFilters.push(FilterUtils.prepQueryFilterForBackend(tableMetaData, sourceFilter.subFilters[j]));
|
||||
}
|
||||
|
||||
filterForBackend.subFilters = subFilters;
|
||||
|
||||
if (pageNumber !== undefined && rowsPerPage !== undefined)
|
||||
{
|
||||
filterForBackend.skip = pageNumber * rowsPerPage;
|
||||
filterForBackend.limit = rowsPerPage;
|
||||
}
|
||||
|
||||
return filterForBackend;
|
||||
};
|
||||
}
|
||||
|
||||
export default FilterUtils;
|
||||
|
@ -133,6 +133,11 @@ class TableUtils
|
||||
*******************************************************************************/
|
||||
public static getFieldAndTable(tableMetaData: QTableMetaData, fieldName: string): [QFieldMetaData, QTableMetaData]
|
||||
{
|
||||
if(!fieldName)
|
||||
{
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
if (fieldName.indexOf(".") > -1)
|
||||
{
|
||||
const nameParts = fieldName.split(".", 2);
|
||||
|
@ -47,6 +47,8 @@ module.exports = function (app)
|
||||
app.use("/download/*", getRequestHandler());
|
||||
app.use("/metaData/*", getRequestHandler());
|
||||
app.use("/data/*", getRequestHandler());
|
||||
app.use("/possibleValues/*", getRequestHandler());
|
||||
app.use("/possibleValues", getRequestHandler());
|
||||
app.use("/widget/*", getRequestHandler());
|
||||
app.use("/serverInfo", getRequestHandler());
|
||||
app.use("/manageSession", getRequestHandler());
|
||||
|
@ -29,6 +29,7 @@ import com.kingsrook.qqq.backend.core.model.metadata.authentication.QAuthenticat
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryBackendModule;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@ -75,7 +76,7 @@ public class TestUtils
|
||||
{
|
||||
return (new QBackendMetaData()
|
||||
.withName(DEFAULT_BACKEND_NAME)
|
||||
.withBackendType("memory"));
|
||||
.withBackendType(MemoryBackendModule.class));
|
||||
}
|
||||
|
||||
|
||||
|
@ -29,6 +29,9 @@ import com.kingsrook.qqq.backend.core.instances.QInstanceValidator;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.junit.BaseTest;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.junit.TestUtils;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.model.metadata.fieldrules.FieldRule;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.model.metadata.fieldrules.FieldRuleAction;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.model.metadata.fieldrules.FieldRuleTrigger;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@ -76,6 +79,37 @@ class MaterialDashboardTableMetaDataTest extends BaseTest
|
||||
|
||||
assertValidationFailureReasons(qInstance -> qInstance.getTable(TestUtils.TABLE_NAME_PERSON).withSupplementalMetaData(new MaterialDashboardTableMetaData().withDefaultQuickFilterFieldNames(List.of("firstName", "lastName", "firstName"))),
|
||||
"duplicated field name: firstName");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testValidateFieldRules()
|
||||
{
|
||||
assertValidationFailureReasons(qInstance -> qInstance.getTable(TestUtils.TABLE_NAME_PERSON).withSupplementalMetaData(new MaterialDashboardTableMetaData().withFieldRule(new FieldRule())),
|
||||
"without an action",
|
||||
"without a trigger",
|
||||
"without a sourceField");
|
||||
|
||||
assertValidationFailureReasons(qInstance -> qInstance.getTable(TestUtils.TABLE_NAME_PERSON).withSupplementalMetaData(new MaterialDashboardTableMetaData().withFieldRule(new FieldRule()
|
||||
.withTrigger(FieldRuleTrigger.ON_CHANGE)
|
||||
.withAction(FieldRuleAction.CLEAR_TARGET_FIELD)
|
||||
.withSourceField("notAField")
|
||||
.withTargetField("alsoNotAField")
|
||||
)),
|
||||
"unrecognized sourceField: notAField",
|
||||
"unrecognized targetField: alsoNotAField");
|
||||
|
||||
assertValidationFailureReasons(qInstance -> qInstance.getTable(TestUtils.TABLE_NAME_PERSON).withSupplementalMetaData(new MaterialDashboardTableMetaData().withFieldRule(new FieldRule()
|
||||
.withTrigger(FieldRuleTrigger.ON_CHANGE)
|
||||
.withAction(FieldRuleAction.RELOAD_WIDGET)
|
||||
.withSourceField("id")
|
||||
.withTargetWidget("notAWidget")
|
||||
)),
|
||||
"unrecognized targetWidget: notAWidget");
|
||||
|
||||
}
|
||||
|
||||
|
@ -33,6 +33,7 @@ import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.TestInfo;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.openqa.selenium.Dimension;
|
||||
import org.openqa.selenium.WebDriver;
|
||||
import org.openqa.selenium.chrome.ChromeDriver;
|
||||
@ -43,6 +44,7 @@ import static org.junit.jupiter.api.Assertions.fail;
|
||||
/*******************************************************************************
|
||||
** Base class for Selenium tests
|
||||
*******************************************************************************/
|
||||
@ExtendWith(SeleniumTestWatcher.class)
|
||||
public class QBaseSeleniumTest
|
||||
{
|
||||
protected static ChromeOptions chromeOptions;
|
||||
@ -93,6 +95,8 @@ public class QBaseSeleniumTest
|
||||
driver.manage().window().setSize(new Dimension(1700, 1300));
|
||||
qSeleniumLib = new QSeleniumLib(driver);
|
||||
|
||||
SeleniumTestWatcher.setCurrentSeleniumLib(qSeleniumLib);
|
||||
|
||||
if(useInternalJavalin())
|
||||
{
|
||||
qSeleniumJavalin = new QSeleniumJavalin();
|
||||
@ -197,10 +201,10 @@ public class QBaseSeleniumTest
|
||||
qSeleniumLib.takeScreenshotToFile(getClass().getSimpleName() + "/" + testInfo.getDisplayName());
|
||||
}
|
||||
|
||||
if(driver != null)
|
||||
{
|
||||
driver.quit();
|
||||
}
|
||||
////////////////////////////////////////////////////////////////////////////////////////
|
||||
// note - at one time we did a driver.quit here - but we're moving that into //
|
||||
// SeleniumTestWatcher, so it can dump logs if it wants to (it runs after the @After) //
|
||||
////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
if(qSeleniumJavalin != null)
|
||||
{
|
||||
|
@ -42,6 +42,8 @@ import org.openqa.selenium.StaleElementReferenceException;
|
||||
import org.openqa.selenium.WebDriver;
|
||||
import org.openqa.selenium.WebElement;
|
||||
import org.openqa.selenium.interactions.Actions;
|
||||
import org.openqa.selenium.logging.LogEntries;
|
||||
import org.openqa.selenium.logging.LogEntry;
|
||||
import org.openqa.selenium.support.ui.ExpectedConditions;
|
||||
import org.openqa.selenium.support.ui.WebDriverWait;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@ -333,7 +335,7 @@ public class QSeleniumLib
|
||||
return;
|
||||
}
|
||||
|
||||
if(elements.stream().noneMatch(e -> e.getText().toLowerCase().contains(textContains)))
|
||||
if(elements.stream().noneMatch(e -> e.getText().toLowerCase().contains(textContains.toLowerCase())))
|
||||
{
|
||||
LOG.debug("Found non-existence of element(s) matching selector [" + cssSelector + "] containing text [" + textContains + "]");
|
||||
return;
|
||||
@ -343,7 +345,7 @@ public class QSeleniumLib
|
||||
}
|
||||
while(start + (1000 * WAIT_SECONDS) > System.currentTimeMillis());
|
||||
|
||||
fail("Failed for non-existence of element matching selector [" + cssSelector + "] after [" + WAIT_SECONDS + "] seconds.");
|
||||
fail("Failed for non-existence of element matching selector [" + cssSelector + "] containing text [" + textContains + "] after [" + WAIT_SECONDS + "] seconds.");
|
||||
}
|
||||
|
||||
|
||||
@ -735,4 +737,22 @@ public class QSeleniumLib
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
public void dumpConsole()
|
||||
{
|
||||
Set<String> availableLogTypes = driver.manage().logs().getAvailableLogTypes();
|
||||
for(String logType : availableLogTypes)
|
||||
{
|
||||
LogEntries logEntries = driver.manage().logs().get(logType);
|
||||
for(LogEntry logEntry : logEntries)
|
||||
{
|
||||
System.out.println(logEntry.toJson());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -261,9 +261,7 @@ public class QueryScreenLib
|
||||
if(StringUtils.hasContent(value))
|
||||
{
|
||||
qSeleniumLib.waitForSelector(".filterValuesColumn INPUT").click();
|
||||
// todo - no, not in a listbox/LI here...
|
||||
qSeleniumLib.waitForSelectorContaining(".MuiAutocomplete-listbox LI", value).click();
|
||||
System.out.println(value);
|
||||
qSeleniumLib.waitForSelector(".filterValuesColumn INPUT").sendKeys(value);
|
||||
}
|
||||
|
||||
qSeleniumLib.clickBackdrop();
|
||||
@ -271,6 +269,21 @@ public class QueryScreenLib
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
public void setBasicBooleanFilter(String fieldLabel, String operatorLabel)
|
||||
{
|
||||
qSeleniumLib.waitForSelectorContaining("BUTTON", fieldLabel).click();
|
||||
qSeleniumLib.waitForMillis(250);
|
||||
qSeleniumLib.waitForSelector("#criteriaOperator").click();
|
||||
qSeleniumLib.waitForSelectorContaining("LI", operatorLabel).click();
|
||||
|
||||
qSeleniumLib.clickBackdrop();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
|
@ -0,0 +1,126 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qqq.frontend.materialdashboard.selenium.lib;
|
||||
|
||||
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.junit.jupiter.api.extension.TestWatcher;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
public class SeleniumTestWatcher implements TestWatcher
|
||||
{
|
||||
private static QSeleniumLib qSeleniumLib;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
public static void setCurrentSeleniumLib(QSeleniumLib qSeleniumLib)
|
||||
{
|
||||
SeleniumTestWatcher.qSeleniumLib = qSeleniumLib;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void testFailed(ExtensionContext context, Throwable cause)
|
||||
{
|
||||
if(qSeleniumLib != null)
|
||||
{
|
||||
System.out.println("Dumping browser console after failed test: " + context.getDisplayName());
|
||||
System.out.println("----------------------------------------------------------------------------");
|
||||
try
|
||||
{
|
||||
qSeleniumLib.dumpConsole();
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
System.out.println("Error dumping console:");
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("----------------------------------------------------------------------------");
|
||||
}
|
||||
|
||||
tryToQuitSelenium();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private void tryToQuitSelenium()
|
||||
{
|
||||
if(qSeleniumLib != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
qSeleniumLib.driver.quit();
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
System.err.println("Error quiting selenium driver: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void testSuccessful(ExtensionContext context)
|
||||
{
|
||||
tryToQuitSelenium();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void testAborted(ExtensionContext context, Throwable cause)
|
||||
{
|
||||
tryToQuitSelenium();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void testDisabled(ExtensionContext context, Optional<String> reason)
|
||||
{
|
||||
tryToQuitSelenium();
|
||||
}
|
||||
}
|
@ -0,0 +1,172 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2024. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qqq.frontend.materialdashboard.selenium.tests;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.selenium.lib.QBaseSeleniumTest;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.selenium.lib.QSeleniumLib;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.selenium.lib.QueryScreenLib;
|
||||
import com.kingsrook.qqq.frontend.materialdashboard.selenium.lib.javalin.QSeleniumJavalin;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.openqa.selenium.By;
|
||||
import org.openqa.selenium.Keys;
|
||||
import org.openqa.selenium.WebElement;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Test for Saved Report screen (table has some special behaviors)
|
||||
*******************************************************************************/
|
||||
public class SavedReportTest extends QBaseSeleniumTest
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
protected void addJavalinRoutes(QSeleniumJavalin qSeleniumJavalin)
|
||||
{
|
||||
super.addJavalinRoutes(qSeleniumJavalin);
|
||||
qSeleniumJavalin
|
||||
.withRouteToFile("/metaData/table/savedReport", "metaData/table/savedReport.json")
|
||||
.withRouteToFile("/widget/reportSetupWidget", "widget/reportSetupWidget.json")
|
||||
.withRouteToFile("/widget/pivotTableSetupWidget", "widget/pivotTableSetupWidget.json")
|
||||
.withRouteToFile("/data/savedReport/possibleValues/tableName", "data/savedReport/possibleValues/tableName.json")
|
||||
|
||||
.withRouteToFile("/data/person/count", "data/person/count.json")
|
||||
.withRouteToFile("/data/person/query", "data/person/index.json")
|
||||
;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testCreate()
|
||||
{
|
||||
qSeleniumLib.gotoAndWaitForBreadcrumbHeaderToContain("/userCustomizations/savedReport/create", "Creating New Saved Report");
|
||||
|
||||
//////////////////////////////////////////////////////////////
|
||||
// make sure things are disabled before a table is selected //
|
||||
//////////////////////////////////////////////////////////////
|
||||
WebElement webElement = qSeleniumLib.waitForSelectorContaining("button", "Edit Filters and Columns");
|
||||
assertEquals("true", webElement.getAttribute("disabled"));
|
||||
|
||||
qSeleniumLib.waitForSelector("#label").click();
|
||||
qSeleniumLib.waitForSelector("#label").sendKeys("My Report");
|
||||
|
||||
qSeleniumLib.waitForSelector("#tableName").click();
|
||||
qSeleniumLib.waitForSelector("#tableName").sendKeys("Person" + Keys.DOWN + Keys.ENTER);
|
||||
|
||||
//////////////////////////////////
|
||||
// make sure things enabled now //
|
||||
//////////////////////////////////
|
||||
webElement = qSeleniumLib.waitForSelectorContaining("button", "Edit Filters and Columns");
|
||||
assertNull(webElement.getAttribute("disabled"));
|
||||
|
||||
////////////////////////////////////////////////////
|
||||
// open query-screen popup, wait for query to run //
|
||||
////////////////////////////////////////////////////
|
||||
qSeleniumJavalin.beginCapture();
|
||||
qSeleniumLib.waitForSelectorContaining("button", "Edit Filters and Columns").click();
|
||||
qSeleniumJavalin.waitForCapturedPath("/data/person/count");
|
||||
qSeleniumJavalin.waitForCapturedPath("/data/person/query");
|
||||
qSeleniumJavalin.endCapture();
|
||||
|
||||
QueryScreenLib queryScreenLib = new QueryScreenLib(qSeleniumLib);
|
||||
queryScreenLib.setBasicFilter("First Name", "contains", "Darin");
|
||||
|
||||
////////////////////////
|
||||
// close query screen //
|
||||
////////////////////////
|
||||
qSeleniumLib.waitForSelectorContaining("button", "OK").click();
|
||||
|
||||
//////////////////////////////////////////////////////
|
||||
// make sure query things appear on edit screen now //
|
||||
//////////////////////////////////////////////////////
|
||||
qSeleniumLib.waitForSelectorContaining(".advancedQueryString", "First Name");
|
||||
qSeleniumLib.waitForSelectorContaining(".advancedQueryString", "contains");
|
||||
qSeleniumLib.waitForSelectorContaining(".advancedQueryString", "Darin");
|
||||
List<WebElement> columns = qSeleniumLib.waitForSelectorContaining("h5", "Columns")
|
||||
.findElement(QSeleniumLib.PARENT)
|
||||
.findElements(By.cssSelector("DIV"));
|
||||
|
||||
assertThat(columns)
|
||||
.hasSizeGreaterThanOrEqualTo(5) // at least this many
|
||||
.anyMatch(we -> we.getText().equals("Home City")); // a few fields are found
|
||||
|
||||
///////////////////
|
||||
// turn on pivot //
|
||||
///////////////////
|
||||
qSeleniumLib.waitForSelectorContaining("label", "Use Pivot Table").click();
|
||||
qSeleniumLib.waitForSelectorContaining("button", "Edit Pivot Table").click();
|
||||
qSeleniumLib.waitForSelectorContaining("h3", "Edit Pivot Table");
|
||||
|
||||
///////////////
|
||||
// add a row //
|
||||
///////////////
|
||||
qSeleniumLib.waitForSelectorContaining(".MuiModal-root button", "Add new row").click();
|
||||
WebElement row0Input = qSeleniumLib.waitForSelector("#rows-0");
|
||||
row0Input.click();
|
||||
row0Input.sendKeys("Last Name" + Keys.ENTER);
|
||||
|
||||
//////////////////
|
||||
// add a column //
|
||||
//////////////////
|
||||
qSeleniumLib.waitForSelectorContaining(".MuiModal-root button", "Add new column").click();
|
||||
WebElement column0Input = qSeleniumLib.waitForSelector("#columns-0");
|
||||
column0Input.click();
|
||||
column0Input.sendKeys("Home City" + Keys.ENTER);
|
||||
|
||||
/////////////////
|
||||
// add a value //
|
||||
/////////////////
|
||||
qSeleniumLib.waitForSelectorContaining(".MuiModal-root button", "Add new value").click();
|
||||
WebElement value0Input = qSeleniumLib.waitForSelector("#values-field-0");
|
||||
value0Input.click();
|
||||
value0Input.sendKeys("Id" + Keys.ENTER);
|
||||
|
||||
/////////////////////////////////////////
|
||||
// try to submit - but expect an error //
|
||||
/////////////////////////////////////////
|
||||
qSeleniumLib.waitForSelectorContaining("button", "OK").click();
|
||||
qSeleniumLib.waitForSelectorContaining(".MuiAlert-standard", "Missing value in 1 field.").click();
|
||||
|
||||
///////////////////////////
|
||||
// now select a function //
|
||||
///////////////////////////
|
||||
WebElement function0Input = qSeleniumLib.waitForSelector("#values-function-0");
|
||||
function0Input.click();
|
||||
function0Input.sendKeys("Count" + Keys.ENTER);
|
||||
|
||||
qSeleniumLib.waitForSelectorContaining("button", "OK").click();
|
||||
qSeleniumLib.waitForSelectorContainingToNotExist("h3", "Edit Pivot Table");
|
||||
|
||||
// qSeleniumLib.waitForever();
|
||||
}
|
||||
|
||||
}
|
@ -153,16 +153,16 @@ public class QueryScreenTest extends QBaseSeleniumTest
|
||||
|
||||
queryScreenLib.addBasicFilter("Is Employed");
|
||||
|
||||
testBasicCriteria(queryScreenLib, "Is Employed", "equals yes", null, "(?s).*Is Employed:.*yes.*", """
|
||||
testBasicBooleanCriteria(queryScreenLib, "Is Employed", "equals yes", "(?s).*Is Employed:.*yes.*", """
|
||||
{"fieldName":"isEmployed","operator":"EQUALS","values":[true]}""");
|
||||
|
||||
testBasicCriteria(queryScreenLib, "Is Employed", "equals no", null, "(?s).*Is Employed:.*no.*", """
|
||||
testBasicBooleanCriteria(queryScreenLib, "Is Employed", "equals no", "(?s).*Is Employed:.*no.*", """
|
||||
{"fieldName":"isEmployed","operator":"EQUALS","values":[false]}""");
|
||||
|
||||
testBasicCriteria(queryScreenLib, "Is Employed", "is empty", null, "(?s).*Is Employed:.*is empty.*", """
|
||||
testBasicBooleanCriteria(queryScreenLib, "Is Employed", "is empty", "(?s).*Is Employed:.*is empty.*", """
|
||||
{"fieldName":"isEmployed","operator":"IS_BLANK","values":[]}""");
|
||||
|
||||
testBasicCriteria(queryScreenLib, "Is Employed", "is not empty", null, "(?s).*Is Employed:.*is not empty.*", """
|
||||
testBasicBooleanCriteria(queryScreenLib, "Is Employed", "is not empty", "(?s).*Is Employed:.*is not empty.*", """
|
||||
{"fieldName":"isEmployed","operator":"IS_NOT_BLANK","values":[]}""");
|
||||
}
|
||||
|
||||
@ -203,10 +203,10 @@ public class QueryScreenTest extends QBaseSeleniumTest
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private void testBasicCriteria(QueryScreenLib queryScreenLib, String fieldLabel, String operatorLabel, String value, String expectButtonStringRegex, String expectFilterJsonContains)
|
||||
private void testBasicBooleanCriteria(QueryScreenLib queryScreenLib, String fieldLabel, String operatorLabel, String expectButtonStringRegex, String expectFilterJsonContains)
|
||||
{
|
||||
qSeleniumJavalin.beginCapture();
|
||||
queryScreenLib.setBasicFilter(fieldLabel, operatorLabel, value);
|
||||
queryScreenLib.setBasicBooleanFilter(fieldLabel, operatorLabel);
|
||||
queryScreenLib.waitForBasicFilterButtonMatchingRegex(expectButtonStringRegex);
|
||||
qSeleniumJavalin.waitForCapturedPathWithBodyContaining("/data/person/query", expectFilterJsonContains);
|
||||
qSeleniumJavalin.endCapture();
|
||||
|
@ -0,0 +1,16 @@
|
||||
{
|
||||
"options": [
|
||||
{
|
||||
"id": "person",
|
||||
"label": "Person"
|
||||
},
|
||||
{
|
||||
"id": "city",
|
||||
"label": "City"
|
||||
},
|
||||
{
|
||||
"id": "savedReport",
|
||||
"label": "Saved Report"
|
||||
}
|
||||
]
|
||||
}
|
@ -189,6 +189,26 @@
|
||||
"insertPermission": true,
|
||||
"editPermission": true,
|
||||
"deletePermission": true
|
||||
},
|
||||
"savedReport": {
|
||||
"name": "savedReport",
|
||||
"label": "Saved Report",
|
||||
"isHidden": false,
|
||||
"iconName": "article",
|
||||
"capabilities": [
|
||||
"TABLE_COUNT",
|
||||
"TABLE_GET",
|
||||
"TABLE_QUERY",
|
||||
"QUERY_STATS",
|
||||
"TABLE_UPDATE",
|
||||
"TABLE_INSERT",
|
||||
"TABLE_DELETE"
|
||||
],
|
||||
"readPermission": true,
|
||||
"insertPermission": true,
|
||||
"editPermission": true,
|
||||
"deletePermission": true,
|
||||
"usesVariants": false
|
||||
}
|
||||
},
|
||||
"processes": {
|
||||
@ -420,6 +440,40 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"userCustomizations": {
|
||||
"name": "userCustomizations",
|
||||
"label": "User Customizations",
|
||||
"iconName": "article",
|
||||
"widgets": [],
|
||||
"children": [
|
||||
{
|
||||
"type": "TABLE",
|
||||
"name": "savedReport",
|
||||
"label": "Saved Report",
|
||||
"iconName": "article"
|
||||
}
|
||||
],
|
||||
"childMap": {
|
||||
"savedReport": {
|
||||
"type": "TABLE",
|
||||
"name": "savedReport",
|
||||
"label": "Saved Report",
|
||||
"iconName": "article"
|
||||
}
|
||||
},
|
||||
"sections": [
|
||||
{
|
||||
"name": "userCustomizations",
|
||||
"label": "User Customizations",
|
||||
"icon": {
|
||||
"name": "badge"
|
||||
},
|
||||
"tables": [
|
||||
"savedReport"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"miscellaneous": {
|
||||
"name": "miscellaneous",
|
||||
"label": "Miscellaneous",
|
||||
@ -730,6 +784,20 @@
|
||||
}
|
||||
],
|
||||
"iconName": "data_object"
|
||||
},
|
||||
{
|
||||
"type": "APP",
|
||||
"name": "userCustomizations",
|
||||
"label": "User Customizations",
|
||||
"children": [
|
||||
{
|
||||
"type": "TABLE",
|
||||
"name": "savedReport",
|
||||
"label": "Saved Report",
|
||||
"iconName": "article"
|
||||
}
|
||||
],
|
||||
"iconName": "data_object"
|
||||
}
|
||||
],
|
||||
"branding": {
|
||||
@ -750,6 +818,28 @@
|
||||
"isCard": true,
|
||||
"storeDropdownSelections": false,
|
||||
"hasPermission": true
|
||||
},
|
||||
"reportSetupWidget": {
|
||||
"name": "reportSetupWidget",
|
||||
"label": "Filters and Columns",
|
||||
"type": "filterAndColumnsSetup",
|
||||
"isCard": true,
|
||||
"storeDropdownSelections": false,
|
||||
"showReloadButton": true,
|
||||
"showExportButton": false,
|
||||
"defaultValues": {},
|
||||
"hasPermission": true
|
||||
},
|
||||
"pivotTableSetupWidget": {
|
||||
"name": "pivotTableSetupWidget",
|
||||
"label": "Pivot Table",
|
||||
"type": "pivotTableSetup",
|
||||
"isCard": true,
|
||||
"storeDropdownSelections": false,
|
||||
"showReloadButton": true,
|
||||
"showExportButton": false,
|
||||
"defaultValues": {},
|
||||
"hasPermission": true
|
||||
}
|
||||
},
|
||||
"environmentValues": {
|
||||
|
218
src/test/resources/fixtures/metaData/table/savedReport.json
Normal file
218
src/test/resources/fixtures/metaData/table/savedReport.json
Normal file
@ -0,0 +1,218 @@
|
||||
{
|
||||
"table": {
|
||||
"name": "savedReport",
|
||||
"label": "Saved Report",
|
||||
"isHidden": false,
|
||||
"primaryKeyField": "id",
|
||||
"iconName": "article",
|
||||
"fields": {
|
||||
"queryFilterJson": {
|
||||
"name": "queryFilterJson",
|
||||
"label": "Query Filter",
|
||||
"type": "STRING",
|
||||
"isRequired": false,
|
||||
"isEditable": true,
|
||||
"isHeavy": false,
|
||||
"displayFormat": "%s"
|
||||
},
|
||||
"columnsJson": {
|
||||
"name": "columnsJson",
|
||||
"label": "Columns",
|
||||
"type": "STRING",
|
||||
"isRequired": false,
|
||||
"isEditable": true,
|
||||
"isHeavy": false,
|
||||
"displayFormat": "%s"
|
||||
},
|
||||
"inputFieldsJson": {
|
||||
"name": "inputFieldsJson",
|
||||
"label": "Input Fields",
|
||||
"type": "STRING",
|
||||
"isRequired": false,
|
||||
"isEditable": true,
|
||||
"isHeavy": false,
|
||||
"displayFormat": "%s"
|
||||
},
|
||||
"pivotTableJson": {
|
||||
"name": "pivotTableJson",
|
||||
"label": "Pivot Table",
|
||||
"type": "STRING",
|
||||
"isRequired": false,
|
||||
"isEditable": true,
|
||||
"isHeavy": false,
|
||||
"displayFormat": "%s"
|
||||
},
|
||||
"modifyDate": {
|
||||
"name": "modifyDate",
|
||||
"label": "Modify Date",
|
||||
"type": "DATE_TIME",
|
||||
"isRequired": false,
|
||||
"isEditable": false,
|
||||
"isHeavy": false,
|
||||
"displayFormat": "%s"
|
||||
},
|
||||
"label": {
|
||||
"name": "label",
|
||||
"label": "Report Name",
|
||||
"type": "STRING",
|
||||
"isRequired": true,
|
||||
"isEditable": true,
|
||||
"isHeavy": false,
|
||||
"displayFormat": "%s"
|
||||
},
|
||||
"id": {
|
||||
"name": "id",
|
||||
"label": "Id",
|
||||
"type": "INTEGER",
|
||||
"isRequired": false,
|
||||
"isEditable": false,
|
||||
"isHeavy": false,
|
||||
"displayFormat": "%s"
|
||||
},
|
||||
"userId": {
|
||||
"name": "userId",
|
||||
"label": "User Id",
|
||||
"type": "STRING",
|
||||
"isRequired": false,
|
||||
"isEditable": true,
|
||||
"isHeavy": false,
|
||||
"displayFormat": "%s"
|
||||
},
|
||||
"tableName": {
|
||||
"name": "tableName",
|
||||
"label": "Table",
|
||||
"type": "STRING",
|
||||
"isRequired": true,
|
||||
"isEditable": true,
|
||||
"isHeavy": false,
|
||||
"possibleValueSourceName": "tables",
|
||||
"displayFormat": "%s"
|
||||
},
|
||||
"createDate": {
|
||||
"name": "createDate",
|
||||
"label": "Create Date",
|
||||
"type": "DATE_TIME",
|
||||
"isRequired": false,
|
||||
"isEditable": false,
|
||||
"isHeavy": false,
|
||||
"displayFormat": "%s"
|
||||
}
|
||||
},
|
||||
"sections": [
|
||||
{
|
||||
"name": "identity",
|
||||
"label": "Identity",
|
||||
"tier": "T1",
|
||||
"fieldNames": [
|
||||
"id",
|
||||
"label",
|
||||
"tableName"
|
||||
],
|
||||
"icon": {
|
||||
"name": "badge"
|
||||
},
|
||||
"isHidden": false
|
||||
},
|
||||
{
|
||||
"name": "filtersAndColumns",
|
||||
"label": "Filters and Columns",
|
||||
"tier": "T2",
|
||||
"widgetName": "reportSetupWidget",
|
||||
"icon": {
|
||||
"name": "table_chart"
|
||||
},
|
||||
"isHidden": false
|
||||
},
|
||||
{
|
||||
"name": "pivotTable",
|
||||
"label": "Pivot Table",
|
||||
"tier": "T2",
|
||||
"widgetName": "pivotTableSetupWidget",
|
||||
"icon": {
|
||||
"name": "pivot_table_chart"
|
||||
},
|
||||
"isHidden": false
|
||||
},
|
||||
{
|
||||
"name": "data",
|
||||
"label": "Data",
|
||||
"tier": "T2",
|
||||
"fieldNames": [
|
||||
"queryFilterJson",
|
||||
"columnsJson",
|
||||
"pivotTableJson"
|
||||
],
|
||||
"icon": {
|
||||
"name": "text_snippet"
|
||||
},
|
||||
"isHidden": true
|
||||
},
|
||||
{
|
||||
"name": "hidden",
|
||||
"label": "Hidden",
|
||||
"tier": "T2",
|
||||
"fieldNames": [
|
||||
"inputFieldsJson",
|
||||
"userId"
|
||||
],
|
||||
"icon": {
|
||||
"name": "text_snippet"
|
||||
},
|
||||
"isHidden": true
|
||||
},
|
||||
{
|
||||
"name": "dates",
|
||||
"label": "Dates",
|
||||
"tier": "T3",
|
||||
"fieldNames": [
|
||||
"createDate",
|
||||
"modifyDate"
|
||||
],
|
||||
"icon": {
|
||||
"name": "calendar_month"
|
||||
},
|
||||
"isHidden": false
|
||||
}
|
||||
],
|
||||
"exposedJoins": [],
|
||||
"supplementalTableMetaData": {
|
||||
"materialDashboard": {
|
||||
"fieldRules": [
|
||||
{
|
||||
"trigger": "ON_CHANGE",
|
||||
"sourceField": "tableName",
|
||||
"action": "CLEAR_TARGET_FIELD",
|
||||
"targetField": "queryFilterJson"
|
||||
},
|
||||
{
|
||||
"trigger": "ON_CHANGE",
|
||||
"sourceField": "tableName",
|
||||
"action": "CLEAR_TARGET_FIELD",
|
||||
"targetField": "columnsJson"
|
||||
},
|
||||
{
|
||||
"trigger": "ON_CHANGE",
|
||||
"sourceField": "tableName",
|
||||
"action": "CLEAR_TARGET_FIELD",
|
||||
"targetField": "pivotTableJson"
|
||||
}
|
||||
],
|
||||
"type": "materialDashboard"
|
||||
}
|
||||
},
|
||||
"capabilities": [
|
||||
"TABLE_COUNT",
|
||||
"TABLE_GET",
|
||||
"TABLE_QUERY",
|
||||
"QUERY_STATS",
|
||||
"TABLE_UPDATE",
|
||||
"TABLE_INSERT",
|
||||
"TABLE_DELETE"
|
||||
],
|
||||
"readPermission": true,
|
||||
"insertPermission": true,
|
||||
"editPermission": true,
|
||||
"deletePermission": true,
|
||||
"usesVariants": false
|
||||
}
|
||||
}
|
@ -0,0 +1 @@
|
||||
{"type":"pivotTableSetup"}
|
@ -0,0 +1 @@
|
||||
{"type":"reportSetup"}
|
Reference in New Issue
Block a user