-
Notifications
You must be signed in to change notification settings - Fork 23.1k
/
action_service.js
1228 lines (1153 loc) · 45.9 KB
/
action_service.js
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @odoo-module **/
import { cleanDomFromBootstrap } from "@web/legacy/utils";
import { browser } from "../../core/browser/browser";
import { useBus } from "../../core/bus_hook";
import { makeContext } from "../../core/context";
import { download } from "../../core/network/download";
import { evaluateExpr } from "../../core/py_js/py";
import { registry } from "../../core/registry";
import { KeepLast } from "../../core/utils/concurrency";
import { sprintf } from "../../core/utils/strings";
import { ActionDialog } from "./action_dialog";
/** @typedef {number|false} ActionId */
/** @typedef {Object} ActionDescription */
/** @typedef {"current" | "fullscreen" | "new" | "self" | "inline"} ActionMode */
/** @typedef {string} ActionTag */
/** @typedef {string} ActionXMLId */
/** @typedef {Object} Context */
/** @typedef {Function} CallableFunction */
/** @typedef {string} ViewType */
/** @typedef {ActionId|ActionXMLId|ActionTag|ActionDescription} ActionRequest */
/**
* @typedef {Object} ActionOptions
* @property {Context} [additionalContext]
* @property {boolean} [clearBreadcrumbs]
* @property {CallableFunction} [onClose]
* @property {Object} [props]
* @property {ViewType} [viewType]
*/
const { Component, hooks, tags } = owl;
const viewRegistry = registry.category("views");
const actionHandlersRegistry = registry.category("action_handlers");
const actionRegistry = registry.category("actions");
export function clearUncommittedChanges(env) {
const callbacks = [];
env.bus.trigger("CLEAR-UNCOMMITTED-CHANGES", callbacks);
return Promise.all(callbacks.map((fn) => fn()));
}
function parseActiveIds(ids) {
const activeIds = [];
if (typeof ids === "string") {
activeIds.push(...ids.split(",").map(Number));
} else if (typeof ids === "number") {
activeIds.push(ids);
}
return activeIds;
}
// -----------------------------------------------------------------------------
// Errors
// -----------------------------------------------------------------------------
export class ViewNotFoundError extends Error {}
export class ControllerNotFoundError extends Error {}
export class InvalidButtonParamsError extends Error {}
// -----------------------------------------------------------------------------
// ActionManager (Service)
// -----------------------------------------------------------------------------
// regex that matches context keys not to forward from an action to another
const CTX_KEY_REGEX = /^(?:(?:default_|search_default_|show_).+|.+_view_ref|group_by|group_by_no_leaf|active_id|active_ids|orderedBy)$/;
function makeActionManager(env) {
const keepLast = new KeepLast();
let id = 0;
let controllerStack = [];
let dialogCloseProm;
let actionCache = {};
let dialog = {};
// The state action (or default user action if none) is loaded as soon as possible
// so that the next "doAction" will have its action ready when needed.
const actionParams = _getActionParams();
if (actionParams && typeof actionParams.actionRequest === "number") {
const { actionRequest, options } = actionParams;
_loadAction(actionRequest, options.additionalContext);
}
env.bus.on("CLEAR-CACHES", null, () => {
actionCache = {};
});
// ---------------------------------------------------------------------------
// misc
// ---------------------------------------------------------------------------
/**
* Returns the last controller of the current controller stack.
*
* @returns {Controller|null}
*/
function _getCurrentController() {
const stack = controllerStack;
return stack.length ? stack[stack.length - 1] : null;
}
/**
* Given an id, xmlid, tag (key of the client action registry) or directly an
* object describing an action.
*
* @private
* @param {ActionRequest} actionRequest
* @param {Context} [context={}]
* @returns {Promise<Action>}
*/
async function _loadAction(actionRequest, context = {}) {
if (typeof actionRequest === "string" && actionRegistry.contains(actionRequest)) {
// actionRequest is a key in the actionRegistry
return {
target: "current",
tag: actionRequest,
type: "ir.actions.client",
};
}
if (typeof actionRequest === "string" || typeof actionRequest === "number") {
// actionRequest is an id or an xmlid
const additional_context = {
active_id: context.active_id,
active_ids: context.active_ids,
active_model: context.active_model,
};
const key = `${JSON.stringify(actionRequest)},${JSON.stringify(additional_context)}`;
if (!actionCache[key]) {
actionCache[key] = env.services.rpc("/web/action/load", {
action_id: actionRequest,
additional_context,
});
}
const action = await actionCache[key];
if (!action) {
return {
type: "ir.actions.client",
tag: "invalid_action",
id: actionRequest,
};
}
return Object.assign({}, action);
}
// actionRequest is an object describing the action
return actionRequest;
}
/**
* this function returns an action description
* with a unique jsId.
*/
function _preprocessAction(action, context = {}) {
action.context = makeContext(env.services.user.context, context, action.context);
if (action.domain) {
const domain = action.domain || [];
action.domain =
typeof domain === "string" ? evaluateExpr(domain, action.context) : domain;
}
action = Object.assign({}, action); // manipulate a copy
action._originalAction = JSON.stringify(action);
action.jsId = `action_${++id}`;
if (action.type === "ir.actions.act_window" || action.type === "ir.actions.client") {
action.target = action.target || "current";
}
if (action.type === "ir.actions.act_window") {
action.controllers = {};
const target = action.target;
if (target !== "inline" && !(target === "new" && action.views[0][1] === "form")) {
// FIXME: search view arch is already sent with load_action, so either remove it
// from there or load all fieldviews alongside the action for the sake of consistency
const searchViewId = action.search_view_id ? action.search_view_id[0] : false;
action.views.push([searchViewId, "search"]);
}
}
return action;
}
/**
* @private
* @param {string} viewType
* @throws {Error} if the current controller is not a view
* @returns {View | null}
*/
function _getView(viewType) {
const currentController = controllerStack[controllerStack.length - 1];
if (currentController.action.type !== "ir.actions.act_window") {
throw new Error(`switchView called but the current controller isn't a view`);
}
const view = currentController.views.find((view) => view.type === viewType);
return view || null;
}
/**
* Given a controller stack, returns the list of breadcrumb items.
*
* @private
* @param {ControllerStack} stack
* @returns {Breadcrumbs}
*/
function _getBreadcrumbs(stack) {
return stack
.filter((controller) => controller.action.tag !== "menu")
.map((controller) => {
return {
jsId: controller.jsId,
name: controller.title || controller.action.name || env._t("Undefined"),
};
});
}
/**
* @private
* @returns {ActionParams | null}
*/
function _getActionParams() {
const state = env.services.router.current.hash;
const options = { clearBreadcrumbs: true };
let actionRequest = null;
if (state.action) {
// ClientAction
if (actionRegistry.contains(state.action)) {
actionRequest = {
params: state,
tag: state.action,
type: "ir.actions.client",
};
} else {
// The action to load isn't the current one => executes it
actionRequest = state.action;
const context = { params: state };
if (state.active_id) {
context.active_id = state.active_id;
}
if (state.active_ids) {
context.active_ids = parseActiveIds(state.active_ids);
} else if (state.active_id) {
context.active_ids = [state.active_id];
}
Object.assign(options, {
additionalContext: context,
viewType: state.view_type,
});
if (state.id) {
options.props = { resId: state.id };
}
}
} else if (state.model) {
if (state.id) {
actionRequest = {
res_model: state.model,
res_id: state.id,
type: "ir.actions.act_window",
views: [[state.view_id ? state.view_id : false, "form"]],
};
} else if (state.view_type) {
// This is a window action on a multi-record view => restores it from
// the session storage
const storedAction = browser.sessionStorage.getItem("current_action");
const lastAction = JSON.parse(storedAction || "{}");
if (lastAction.res_model === state.model) {
actionRequest = lastAction;
options.viewType = state.view_type;
}
}
}
// If no action => falls back on the user default action (if any).
if (!actionRequest && env.services.user.home_action_id) {
actionRequest = env.services.user.home_action_id;
}
return actionRequest ? { actionRequest, options } : null;
}
/**
* @param {ClientAction | ActWindowAction} action
* @param {Object} props
* @returns {ActionProps}
*/
function _getActionProps(action, props) {
return Object.assign({}, props, { action, actionId: action.id });
}
/**
* @param {Action} action
* @returns {ActionMode}
*/
function _getActionMode(action) {
if (action.target === "new") {
// No possible override for target="new"
return "new";
}
if (action.type === "ir.actions.client") {
const clientAction = actionRegistry.get(action.tag);
if (clientAction.target) {
// Target is forced by the definition of the client action
return clientAction.target;
}
}
if (controllerStack.some((c) => c.action.target === "fullscreen")) {
// Force fullscreen when one of the controllers is set to fullscreen
return "fullscreen";
}
// Default: current
return "current";
}
/**
* @private
* @returns {SwitchViewParams | null}
*/
function _getSwitchViewParams() {
const state = env.services.router.current.hash;
if (state.action && !actionRegistry.contains(state.action)) {
const currentController = controllerStack[controllerStack.length - 1];
const currentActionId =
currentController && currentController.action && currentController.action.id;
// Window Action: determines model, viewType etc....
if (
currentController &&
currentController.action.type === "ir.actions.act_window" &&
currentActionId === state.action
) {
const props = { resId: state.id || false };
const viewType = state.view_type || currentController.view.type;
return { viewType, props };
}
}
return null;
}
/**
* @param {BaseView} view
* @param {ActWindowAction} action
* @param {BaseView[]} views
* @param {Object} props
* @returns {ViewProps}
*/
function _getViewProps(view, action, views, props = {}) {
const target = action.target;
const viewSwitcherEntries = views
.filter((v) => v.multiRecord === view.multiRecord)
.map((v) => {
return {
// FIXME: missing accesskey
icon: v.icon,
name: v.display_name,
type: v.type,
multiRecord: v.multiRecord,
};
});
const flags = action.flags || {};
const viewProps = Object.assign(_getActionProps(action, props), {
actionFlags: Object.assign({}, flags, flags[view.type]),
context: action.context,
domain: action.domain || [],
resModel: action.res_model,
type: view.type,
views: action.views,
viewSwitcherEntries,
withActionMenus: target !== "new" && target !== "inline",
withFilters: action.views.some((v) => v[1] === "search"),
});
if (action.res_id) {
viewProps.resId = action.res_id;
}
return viewProps;
}
/**
* Computes the position of the controller in the nextStack according to options
* @param {Object} options
* @param {boolean} [options.clearBreadcrumbs=false]
* @param {'replaceLast' | 'replaceLastAction'} [options.stackPosition]
* @param {number} [options.index]
*/
function _computeStackIndex(options) {
let index = null;
if (options.clearBreadcrumbs) {
index = 0;
} else if (options.stackPosition === "replaceCurrentAction") {
const currentController = controllerStack[controllerStack.length - 1];
if (currentController) {
index = controllerStack.findIndex(
(ct) => ct.action.jsId === currentController.action.jsId
);
}
} else if (options.stackPosition === "replacePreviousAction") {
let last;
for (let i = controllerStack.length - 1; i >= 0; i--) {
const action = controllerStack[i].action.jsId;
if (!last) {
last = action;
}
if (action !== last) {
last = action;
break;
}
}
if (last) {
index = controllerStack.findIndex((ct) => ct.action.jsId === last);
}
// TODO: throw if there is no previous action?
} else if ("index" in options) {
index = options.index;
} else {
index = controllerStack.length;
}
return index;
}
/**
* Triggers a re-rendering with respect to the given controller.
*
* @private
* @param {Controller} controller
* @param {UpdateStackOptions} options
* @param {boolean} [options.clearBreadcrumbs=false]
* @param {number} [options.index]
* @returns {Promise<Number>}
*/
async function _updateUI(controller, options = {}) {
let resolve;
let reject;
let dialogCloseResolve;
const currentActionProm = new Promise((_res, _rej) => {
resolve = _res;
reject = _rej;
});
const action = controller.action;
class ControllerComponent extends Component {
setup() {
this.Component = controller.Component;
this.componentRef = hooks.useRef("component");
this.registerCallback = null;
if (action.target !== "new") {
let beforeLeaveFn;
this.registerCallback = (type, fn) => {
switch (type) {
case "export":
controller.getState = fn;
break;
case "beforeLeave":
beforeLeaveFn = fn;
break;
}
};
useBus(env.bus, "CLEAR-UNCOMMITTED-CHANGES", (callbacks) => {
if (beforeLeaveFn) {
callbacks.push(beforeLeaveFn);
}
});
}
}
catchError(error) {
// The above component should truely handle the error
reject(error);
// Re-throw in case it is a programming error
if (error && error.name) {
throw error;
}
}
mounted() {
if (action.target === "new") {
dialogCloseProm = new Promise((_r) => {
dialogCloseResolve = _r;
}).then(() => {
dialogCloseProm = undefined;
});
} else {
// LEGACY CODE COMPATIBILITY: remove when controllers will be written in owl
// we determine here which actions no longer occur in the nextStack,
// and we manually destroy all their controller's widgets
const nextStackActionIds = nextStack.map((c) => c.action.jsId);
const toDestroy = new Set();
for (const c of controllerStack) {
if (!nextStackActionIds.includes(c.action.jsId)) {
if (c.action.type === "ir.actions.act_window") {
for (const viewType in c.action.controllers) {
toDestroy.add(c.action.controllers[viewType]);
}
} else {
toDestroy.add(c);
}
}
}
for (const c of toDestroy) {
if (c.exportedState) {
c.exportedState.__legacy_widget__.destroy();
}
}
// END LEGACY CODE COMPATIBILITY
controllerStack = nextStack; // the controller is mounted, commit the new stack
// wait Promise callbacks to be executed
pushState(controller);
browser.sessionStorage.setItem("current_action", action._originalAction);
}
resolve();
env.bus.trigger("ACTION_MANAGER:UI-UPDATED", _getActionMode(action));
}
willUnmount() {
if (action.target === "new" && dialogCloseResolve) {
dialogCloseResolve();
}
}
onHistoryBack() {
const previousController = controllerStack[controllerStack.length - 2];
if (previousController && !dialogCloseProm) {
restore(previousController.jsId);
} else {
_executeCloseAction();
}
}
onTitleUpdated(ev) {
controller.title = ev.detail;
}
}
ControllerComponent.template = tags.xml`<t t-component="Component" t-props="props"
registerCallback="registerCallback"
t-ref="component"
t-on-history-back="onHistoryBack"
t-on-controller-title-updated.stop="onTitleUpdated"/>`;
ControllerComponent.Component = controller.Component;
if (action.target === "new") {
cleanDomFromBootstrap();
const actionDialogProps = {
// TODO add size
ActionComponent: ControllerComponent,
actionProps: controller.props,
};
if (action.name) {
actionDialogProps.title = action.name;
}
const { onClose } = dialog;
const removeOldDialog = dialog.remove;
if (removeOldDialog) {
dialog = {};
removeOldDialog();
}
const removeDialog = env.services.dialog.add(ActionDialog, actionDialogProps, {
onClose: () => {
if (dialog.remove) {
if (dialog.onClose) {
dialog.onClose();
}
dialog = {};
}
},
});
dialog = {
remove: removeDialog,
onClose: onClose || options.onClose,
};
return currentActionProm;
}
const currentController = _getCurrentController();
if (currentController && currentController.getState) {
currentController.exportedState = currentController.getState();
}
if (controller.exportedState) {
controller.props.state = controller.exportedState;
}
const index = _computeStackIndex(options);
const controllerArray = [controller];
if (options.lazyController) {
controllerArray.unshift(options.lazyController);
}
const nextStack = controllerStack.slice(0, index).concat(controllerArray);
controller.props.breadcrumbs = _getBreadcrumbs(nextStack.slice(0, nextStack.length - 1));
const closingProm = _executeCloseAction();
env.bus.trigger("ACTION_MANAGER:UPDATE", {
id: ++id,
Component: ControllerComponent,
componentProps: controller.props,
});
return Promise.all([currentActionProm, closingProm]).then((r) => r[0]);
}
// ---------------------------------------------------------------------------
// ir.actions.act_url
// ---------------------------------------------------------------------------
/**
* Executes actions of type 'ir.actions.act_url', i.e. redirects to the
* given url.
*
* @private
* @param {ActURLAction} action
*/
function _executeActURLAction(action) {
if (action.target === "self") {
env.services.router.redirect(action.url);
} else {
const w = browser.open(action.url, "_blank");
if (!w || w.closed || typeof w.closed === "undefined") {
const msg = env._t(
"A popup window has been blocked. You may need to change your " +
"browser settings to allow popup windows for this page."
);
env.services.notification.add(msg, {
sticky: true,
type: "warning",
});
}
}
}
// ---------------------------------------------------------------------------
// ir.actions.act_window
// ---------------------------------------------------------------------------
/**
* Executes an action of type 'ir.actions.act_window'.
*
* @private
* @param {ActWindowAction} action
* @param {ActionOptions} options
*/
function _executeActWindowAction(action, options) {
const views = [];
for (const [, type] of action.views) {
if (viewRegistry.contains(type)) {
views.push(viewRegistry.get(type));
}
}
if (!views.length) {
throw new Error(`No view found for act_window action ${action.id}`);
}
let view = options.viewType && views.find((v) => v.type === options.viewType);
let lazyView;
if (view && !view.multiRecord) {
lazyView = views[0].multiRecord ? views[0] : undefined;
} else if (!view) {
view = views[0];
}
if (env.isSmall) {
if (!view.isMobileFriendly) {
view = _findMobileView(views, view.multiRecord) || view;
}
if (lazyView && !lazyView.isMobileFriendly) {
lazyView = _findMobileView(views, lazyView.multiRecord) || lazyView;
}
}
const controller = {
jsId: `controller_${++id}`,
Component: view,
action,
view,
views,
props: _getViewProps(view, action, views, options.props),
};
action.controllers[view.type] = controller;
const updateUIOptions = {
clearBreadcrumbs: options.clearBreadcrumbs,
onClose: options.onClose,
stackPosition: options.stackPosition,
};
if (lazyView) {
updateUIOptions.lazyController = {
jsId: `controller_${++id}`,
Component: lazyView,
action,
view: lazyView,
views,
props: _getViewProps(lazyView, action, views),
};
}
return _updateUI(controller, updateUIOptions);
}
/**
* Helper function to find the first mobile-friendly view, if any.
*
* @private
* @param {Array} views an array of views
* @param {boolean} multiRecord true if we search for a multiRecord view
* @returns {Object|undefined} first mobile-friendly view found
*/
function _findMobileView(views, multiRecord) {
return views.find((view) => view.isMobileFriendly && view.multiRecord === multiRecord);
}
// ---------------------------------------------------------------------------
// ir.actions.client
// ---------------------------------------------------------------------------
/**
* Executes an action of type 'ir.actions.client'.
*
* @private
* @param {ClientAction} action
* @param {ActionOptions} options
*/
async function _executeClientAction(action, options) {
const clientAction = actionRegistry.get(action.tag);
if (clientAction.prototype instanceof Component) {
if (action.target !== "new" && clientAction.target) {
action.target = clientAction.target;
}
const controller = {
jsId: `controller_${++id}`,
Component: clientAction,
action,
props: _getActionProps(action, options.props),
};
return _updateUI(controller, {
clearBreadcrumbs: options.clearBreadcrumbs,
stackPosition: options.stackPosition,
onClose: options.onClose,
});
} else {
const next = await clientAction(env, action);
if (next) {
return doAction(next, options);
}
}
}
// ---------------------------------------------------------------------------
// ir.actions.report
// ---------------------------------------------------------------------------
// messages that might be shown to the user dependening on the state of wkhtmltopdf
const link = '<br><br><a href="http://wkhtmltopdf.org/" target="_blank">wkhtmltopdf.org</a>';
const WKHTMLTOPDF_MESSAGES = {
broken:
env._t(
"Your installation of Wkhtmltopdf seems to be broken. The report will be shown " +
"in html."
) + link,
install:
env._t(
"Unable to find Wkhtmltopdf on this system. The report will be shown in " + "html."
) + link,
upgrade:
env._t(
"You should upgrade your version of Wkhtmltopdf to at least 0.12.0 in order to " +
"get a correct display of headers and footers as well as support for " +
"table-breaking between pages."
) + link,
workers: env._t(
"You need to start Odoo with at least two workers to print a pdf version of " +
"the reports."
),
};
// only check the wkhtmltopdf state once, so keep the rpc promise
let wkhtmltopdfStateProm;
/**
* Generates the report url given a report action.
*
* @private
* @param {ReportAction} action
* @param {ReportType} type
* @returns {string}
*/
function _getReportUrl(action, type) {
let url = `/report/${type}/${action.report_name}`;
const actionContext = action.context || {};
if (action.data && JSON.stringify(action.data) !== "{}") {
// build a query string with `action.data` (it's the place where reports
// using a wizard to customize the output traditionally put their options)
const options = encodeURIComponent(JSON.stringify(action.data));
const context = encodeURIComponent(JSON.stringify(actionContext));
url += `?options=${options}&context=${context}`;
} else {
if (actionContext.active_ids) {
url += `/${actionContext.active_ids.join(",")}`;
}
if (type === "html") {
const context = encodeURIComponent(JSON.stringify(env.services.user.context));
url += `?context=${context}`;
}
}
return url;
}
/**
* Launches download action of the report
*
* @private
* @param {ReportAction} action
* @param {ActionOptions} options
* @returns {Promise}
*/
async function _triggerDownload(action, options, type) {
const url = _getReportUrl(action, type);
env.services.ui.block();
try {
await download({
url: "/report/download",
data: {
data: JSON.stringify([url, action.report_type]),
context: JSON.stringify(env.services.user.context),
},
});
} finally {
env.services.ui.unblock();
}
const onClose = options.onClose;
if (action.close_on_report_download) {
return doAction({ type: "ir.actions.act_window_close" }, { onClose });
} else if (onClose) {
onClose();
}
}
function _executeReportClientAction(action, options) {
const props = Object.assign({}, options.props, {
data: action.data,
display_name: action.display_name,
name: action.name,
report_file: action.report_file,
report_name: action.report_name,
report_url: _getReportUrl(action, "html"),
});
const clientActionOptions = Object.assign({}, options, {
context: action.context,
props,
});
return doAction("report.client_action", clientActionOptions);
}
/**
* Executes actions of type 'ir.actions.report'.
*
* @private
* @param {ReportAction} action
* @param {ActionOptions} options
*/
async function _executeReportAction(action, options) {
const handlers = registry.category("ir.actions.report handlers").getAll();
for (const handler of handlers) {
const result = await handler(action, options, env);
if (result) {
return result;
}
}
if (action.report_type === "qweb-html") {
return _executeReportClientAction(action, options);
} else if (action.report_type === "qweb-pdf") {
// check the state of wkhtmltopdf before proceeding
if (!wkhtmltopdfStateProm) {
wkhtmltopdfStateProm = env.services.rpc("/report/check_wkhtmltopdf");
}
const state = await wkhtmltopdfStateProm;
// display a notification according to wkhtmltopdf's state
if (state in WKHTMLTOPDF_MESSAGES) {
env.services.notification.add(WKHTMLTOPDF_MESSAGES[state], {
sticky: true,
title: env._t("Report"),
});
}
if (state === "upgrade" || state === "ok") {
// trigger the download of the PDF report
return _triggerDownload(action, options, "pdf");
} else {
// open the report in the client action if generating the PDF is not possible
return _executeReportClientAction(action, options);
}
} else if (action.report_type === "qweb-text") {
return _triggerDownload(action, options, "text");
} else {
console.error(
`The ActionManager can't handle reports of type ${action.report_type}`,
action
);
}
}
// ---------------------------------------------------------------------------
// ir.actions.server
// ---------------------------------------------------------------------------
/**
* Executes an action of type 'ir.actions.server'.
*
* @private
* @param {ServerAction} action
* @param {ActionOptions} options
* @returns {Promise<void>}
*/
async function _executeServerAction(action, options) {
const runProm = env.services.rpc("/web/action/run", {
action_id: action.id,
context: action.context || {},
});
let nextAction = await keepLast.add(runProm);
nextAction = nextAction || { type: "ir.actions.act_window_close" };
return doAction(nextAction, options);
}
async function _executeCloseAction(params = {}) {
cleanDomFromBootstrap();
let onClose;
const removeDialog = dialog.remove;
if (removeDialog) {
onClose = dialog.onClose;
dialog = {};
removeDialog();
} else {
onClose = params.onClose;
}
if (onClose) {
await onClose(params.onCloseInfo);
}
return dialogCloseProm;
}
// ---------------------------------------------------------------------------
// public API
// ---------------------------------------------------------------------------
/**
* Main entry point of a 'doAction' request. Loads the action and executes it.
*
* @param {ActionRequest} actionRequest
* @param {ActionOptions} options
* @returns {Promise<number | undefined | void>}
*/
async function doAction(actionRequest, options = {}) {
const actionProm = _loadAction(actionRequest, options.additionalContext);
let action = await keepLast.add(actionProm);
action = _preprocessAction(action, options.additionalContext);
switch (action.type) {
case "ir.actions.act_url":
return _executeActURLAction(action);
case "ir.actions.act_window":
if (action.target !== "new") {
await clearUncommittedChanges(env);
}
return _executeActWindowAction(action, options);
case "ir.actions.act_window_close":
return _executeCloseAction({ onClose: options.onClose, onCloseInfo: action.infos });
case "ir.actions.client":
if (action.target !== "new") {
await clearUncommittedChanges(env);
}
return _executeClientAction(action, options);
case "ir.actions.report":
return _executeReportAction(action, options);
case "ir.actions.server":
return _executeServerAction(action, options);
default: {
let handler = actionHandlersRegistry.get(action.type, null);
if (handler !== null) {
return handler({ env, action, options });
}
throw new Error(
`The ActionManager service can't handle actions of type ${action.type}`
);
}
}
}
/**
* Executes an action on top of the current one (typically, when a button in a
* view is clicked). The button may be of type 'object' (call a given method
* of a given model) or 'action' (execute a given action). Alternatively, the
* button may have the attribute 'special', and in this case an
* 'ir.actions.act_window_close' is executed.
*
* @param {DoActionButtonParams} params
* @returns {Promise<void>}
*/
async function doActionButton(params) {
// determine the action to execute according to the params
let action;
const context = makeContext(params.context, params.buttonContext);
if (params.special) {
action = { type: "ir.actions.act_window_close", infos: { special: true } };
} else if (params.type === "object") {
// call a Python Object method, which may return an action to execute
let args = params.resId ? [[params.resId]] : [params.resIds];
if (params.args) {
let additionalArgs;
try {
// warning: quotes and double quotes problem due to json and xml clash
// maybe we should force escaping in xml or do a better parse of the args array