-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
GTAPModal.jsx
519 lines (484 loc) · 15.2 KB
/
GTAPModal.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/* eslint-disable react/prop-types */
import React from "react";
import { withRouter } from "react-router";
import { connect } from "react-redux";
import { push } from "react-router-redux";
import MappingEditor from "./MappingEditor";
import QuestionPicker from "metabase/containers/QuestionPicker";
import QuestionParameterTargetWidget from "../containers/QuestionParameterTargetWidget";
import Button from "metabase/components/Button";
import ActionButton from "metabase/components/ActionButton";
import LoadingAndErrorWrapper from "metabase/components/LoadingAndErrorWrapper";
import Select, { Option } from "metabase/components/Select";
import Radio from "metabase/components/Radio";
import Icon from "metabase/components/Icon";
import Tooltip from "metabase/components/Tooltip";
import { GTAPApi } from "metabase/services";
import { UNKNOWN_ERROR_MESSAGE } from "metabase/components/form/FormMessage";
import EntityObjectLoader from "metabase/entities/containers/EntityObjectLoader";
import QuestionLoader from "metabase/containers/QuestionLoader";
import Dimension from "metabase-lib/lib/Dimension";
import _ from "underscore";
import { jt, t } from "ttag";
import { getParentPath } from "metabase/hoc/ModalRoute";
const mapStateToProps = () => ({});
const mapDispatchToProps = {
push,
};
type GTAP = {
table_id: ?number,
group_id: ?number,
card_id: ?number,
attribute_remappings: { [attribute: string]: any },
};
type Props = {
params: { [name: string]: string },
push: (url: string) => void,
};
type State = {
gtap: ?GTAP,
attributesOptions: ?(string[]),
simple: boolean,
error: ?string,
};
@withRouter
@connect(
mapStateToProps,
mapDispatchToProps,
)
export default class GTAPModal extends React.Component {
props: Props;
state: State = {
gtap: null,
attributesOptions: null,
simple: true,
error: null,
};
async UNSAFE_componentWillMount() {
const { params } = this.props;
GTAPApi.attributes().then(attributesOptions =>
this.setState({ attributesOptions }),
);
const groupId = parseInt(params.groupId);
const tableId = parseInt(params.tableId);
const gtaps = await GTAPApi.list();
let gtap = _.findWhere(gtaps, { group_id: groupId, table_id: tableId });
if (!gtap) {
gtap = {
table_id: tableId,
group_id: groupId,
card_id: null,
attribute_remappings: { "": null },
};
}
if (Object.keys(gtap.attribute_remappings).length === 0) {
gtap.attribute_remappings = { "": null };
}
this.setState({ gtap, simple: gtap.card_id == null });
}
close = () => {
const { push, route, location } = this.props;
return push(getParentPath(route, location));
};
_getCanonicalGTAP() {
const { gtap, simple } = this.state;
if (!gtap) {
return null;
}
return {
...gtap,
card_id: simple ? null : gtap.card_id,
attribute_remappings: _.pick(
gtap.attribute_remappings,
(value, key) => value && key,
),
};
}
save = async () => {
const gtap = this._getCanonicalGTAP();
if (!gtap) {
throw new Error("No GTAP");
}
try {
if (gtap.id != null) {
await GTAPApi.update(gtap);
} else {
await GTAPApi.create(gtap);
}
} catch (error) {
console.error("Error saving GTAP", error);
const message = error
? error.data
? error.data.message || JSON.stringify(error.data)
: JSON.stringify(error)
: UNKNOWN_ERROR_MESSAGE;
this.setState({ error: message });
throw new Error(message);
}
this.close();
};
isValid() {
const gtap = this._getCanonicalGTAP();
const { simple } = this.state;
if (!gtap) {
return false;
} else if (simple) {
return Object.entries(gtap.attribute_remappings).length > 0;
} else {
return gtap.card_id != null;
}
}
render() {
const { gtap, simple, attributesOptions } = this.state;
const valid = this.isValid();
const canonicalGTAP = this._getCanonicalGTAP();
const remainingAttributesOptions =
gtap && attributesOptions
? attributesOptions.filter(
attribute => !(attribute in gtap.attribute_remappings),
)
: [];
const hasAttributesOptions =
attributesOptions && attributesOptions.length > 0;
const hasValidMappings =
Object.keys((canonicalGTAP || {}).attribute_remappings || {}).length > 0;
return (
<div>
<h2 className="p3">{t`Grant sandboxed access to this table`}</h2>
<LoadingAndErrorWrapper loading={!gtap}>
{() =>
gtap && (
<div>
<div className="px3 pb3">
<div className="pb3">
{t`When users in this group view this table they'll see a version of it that's filtered by their user attributes, or a custom view of it based on a saved question.`}
</div>
<h4 className="pb1">
{t`How do you want to filter this table for users in this group?`}
</h4>
<Radio
value={simple}
options={[
{ name: "Filter by a column in the table", value: true },
{
name:
"Use a saved question to create a custom view for this table",
value: false,
},
]}
onChange={simple => this.setState({ simple })}
vertical
/>
</div>
{!simple && (
<div className="px3 pb3">
<div className="pb2">
{t`Pick a saved question that returns the custom view of this table that these users should see.`}
</div>
<QuestionPicker
value={gtap.card_id}
onChange={card_id =>
this.setState({ gtap: { ...gtap, card_id } })
}
/>
</div>
)}
{gtap &&
attributesOptions &&
// show if in simple mode, or the admin has selected a card
(simple || gtap.card_id != null) &&
(hasAttributesOptions || hasValidMappings ? (
<div className="p3 border-top border-bottom">
{!simple && (
<div className="pb2">
{t`You can optionally add additional filters here based on user attributes. These filters will be applied on top of any filters that are already in this saved question.`}
</div>
)}
<AttributeMappingEditor
value={gtap.attribute_remappings}
onChange={attribute_remappings =>
this.setState({
gtap: { ...gtap, attribute_remappings },
})
}
simple={simple}
gtap={gtap}
attributesOptions={remainingAttributesOptions}
/>
</div>
) : (
<div className="px3">
<AttributeOptionsEmptyState
title={
simple
? t`For this option to work, your users need to have some attributes`
: t`To add additional filters, your users need to have some attributes`
}
/>
</div>
))}
</div>
)
}
</LoadingAndErrorWrapper>
<div className="p3">
{valid && canonicalGTAP && (
<div className="pb1">
<GTAPSummary gtap={canonicalGTAP} />
</div>
)}
<div className="flex align-center justify-end">
<Button onClick={this.close}>{t`Cancel`}</Button>
<ActionButton
className="ml1"
actionFn={this.save}
primary
disabled={!valid}
>
{t`Save`}
</ActionButton>
</div>
{this.state.error && (
<div className="flex align-center my2 text-error">
{this.state.error}
</div>
)}
</div>
</div>
);
}
}
const AttributePicker = ({ value, onChange, attributesOptions }) => (
<div style={{ minWidth: 200 }}>
<Select
value={value}
onChange={e => onChange(e.target.value)}
placeholder={
attributesOptions.length === 0
? t`No user attributes`
: t`Pick a user attribute`
}
disabled={attributesOptions.length === 0}
>
{attributesOptions.map(attributesOption => (
<Option key={attributesOption} value={attributesOption}>
{attributesOption}
</Option>
))}
</Select>
</div>
);
const QuestionTargetPicker = ({ value, onChange, questionId }) => (
<div style={{ minWidth: 200 }}>
<QuestionParameterTargetWidget
questionId={questionId}
target={value}
onChange={onChange}
placeholder={t`Pick a parameter`}
/>
</div>
);
const rawDataQuestionForTable = tableId => ({
dataset_query: {
type: "query",
query: { "source-table": tableId },
},
});
const TableTargetPicker = ({ value, onChange, tableId }) => (
<div style={{ minWidth: 200 }}>
<QuestionParameterTargetWidget
questionObject={rawDataQuestionForTable(tableId)}
target={value}
onChange={onChange}
placeholder={t`Pick a column`}
/>
</div>
);
const SummaryRow = ({ icon, content }) => (
<div className="flex align-center">
<Icon className="p1" name={icon} />
<span>{content}</span>
</div>
);
const GTAPSummary = ({ gtap }: { gtap: GTAP }) => {
return (
<div>
<div className="px1 pb2 text-uppercase text-small text-grey-4">
Summary
</div>
<SummaryRow
icon="group"
content={jt`Users in ${<GroupName groupId={gtap.group_id} />} can view`}
/>
<SummaryRow
icon="table"
content={
gtap.card_id
? jt`rows in the ${(
<QuestionName questionId={gtap.card_id} />
)} question`
: jt`rows in the ${<TableName tableId={gtap.table_id} />} table`
}
/>
{Object.entries(gtap.attribute_remappings).map(
([attribute, target], index) => (
<SummaryRow
key={attribute}
icon="funneloutline"
content={
index === 0
? jt`where ${(
<TargetName gtap={gtap} target={target} />
)} equals ${<span className="text-code">{attribute}</span>}`
: jt`and ${(
<TargetName gtap={gtap} target={target} />
)} equals ${<span className="text-code">{attribute}</span>}`
}
/>
),
)}
</div>
);
};
// TODO: use EntityName component
const GroupName = ({ groupId }) => (
<EntityObjectLoader
entityType="groups"
entityId={groupId}
properties={["name"]}
loadingAndErrorWrapper={false}
>
{({ object }) => <strong>{object && object.name}</strong>}
</EntityObjectLoader>
);
// TODO: use EntityName component
const QuestionName = ({ questionId }) => (
<EntityObjectLoader
entityType="questions"
entityId={questionId}
properties={["name"]}
loadingAndErrorWrapper={false}
>
{({ object }) => <strong>{object && object.name}</strong>}
</EntityObjectLoader>
);
// TODO: use EntityName component
const TableName = ({ tableId }) => (
<EntityObjectLoader
entityType="tables"
entityId={tableId}
properties={["display_name"]}
loadingAndErrorWrapper={false}
>
{({ object }) => <strong>{object && object.display_name}</strong>}
</EntityObjectLoader>
);
const TargetName = ({ gtap, target }: { gtap: GTAP, target: any }) => {
if (Array.isArray(target)) {
if (
(target[0] === "variable" || target[0] === "dimension") &&
target[1][0] === "template-tag"
) {
return (
<span>
<strong>{target[1][1]}</strong> variable
</span>
);
} else if (target[0] === "dimension") {
return (
<QuestionLoader
questionId={gtap.card_id}
questionObject={
gtap.card_id == null ? rawDataQuestionForTable(gtap.table_id) : null
}
>
{({ question }) =>
question && (
<span>
<strong>
{Dimension.parseMBQL(target[1], question.metadata()).render()}
</strong>{" "}
field
</span>
)
}
</QuestionLoader>
);
}
}
return <emphasis>[Unknown target]</emphasis>;
};
const AttributeOptionsEmptyState = ({ title }) => (
<div className="flex align-center rounded bg-slate-extra-light p2">
<img
src="app/assets/img/attributes_illustration.png"
srcSet="
app/assets/img/attributes_illustration.png 1x,
app/assets/img/attributes_illustration@2x.png 2x,
"
className="mr2"
/>
<div>
<h3 className="pb1">{title}</h3>
<div>{t`You can add attributes automatically by setting up an SSO that uses SAML, or you can enter them manually by going to the People section and clicking on the … menu on the far right.`}</div>
</div>
</div>
);
const AttributeMappingEditor = ({
value,
onChange,
simple,
attributesOptions,
gtap,
}) => (
<MappingEditor
style={{ width: "100%" }}
value={value}
onChange={onChange}
keyPlaceholder={t`Pick a user attribute`}
keyHeader={
<div className="text-uppercase text-small text-grey-4 flex align-center">
{t`User attribute`}
<Tooltip
tooltip={t`We can automatically get your users’ attributes if you’ve set up SSO, or you can add them manually from the "…" menu in the People section of the Admin Panel.`}
>
<Icon className="ml1" name="infooutlined" />
</Tooltip>
</div>
}
renderKeyInput={({ value, onChange }) => (
<AttributePicker
value={value}
onChange={onChange}
attributesOptions={(value ? [value] : []).concat(attributesOptions)}
/>
)}
render
valuePlaceholder={simple ? t`Pick a column` : t`Pick a parameter`}
valueHeader={
<div className="text-uppercase text-small text-grey-4">
{simple ? t`Column` : t`Parameter or variable`}
</div>
}
renderValueInput={({ value, onChange }) =>
simple && gtap.table_id != null ? (
<TableTargetPicker
value={value}
onChange={onChange}
tableId={gtap.table_id}
/>
) : !simple && gtap.card_id != null ? (
<QuestionTargetPicker
value={value}
onChange={onChange}
questionId={gtap.card_id}
/>
) : null
}
divider={<span className="px2 text-bold">{t`equals`}</span>}
addText={t`Add a filter`}
canAdd={attributesOptions.length > 0}
canDelete={true}
swapKeyAndValue
/>
);