variables.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { variableAdapters } from 'app/features/variables/adapters';
  2. import { hasOptions } from 'app/features/variables/guard';
  3. import { VariableModel } from 'app/features/variables/types';
  4. import { Report } from '../../types';
  5. /**
  6. * Convert variable values to CSV and remove all empty keys before sending to backend
  7. * @param variables
  8. */
  9. export const variablesToCsv = (variables?: VariableModel[]) => {
  10. if (!variables?.length) {
  11. return {};
  12. }
  13. return Object.fromEntries(
  14. variables.map((variable) => {
  15. const { getValueForUrl } = variableAdapters.get(variable.type);
  16. const value = getValueForUrl(variable);
  17. return [variable.name, Array.isArray(value) ? value.join(',') : value];
  18. })
  19. );
  20. };
  21. export const applyDefaultVariables = (variables: VariableModel[], reportVariables?: Report['templateVars']) => {
  22. if (!reportVariables || !Object.keys(reportVariables).length) {
  23. return variables;
  24. }
  25. return variables.map((variable) => {
  26. const reportVariable = reportVariables[variable.name];
  27. if (!reportVariable || !hasOptions(variable)) {
  28. return variable;
  29. }
  30. const split = reportVariable.split(',');
  31. const values = split
  32. .map((str) => variable.options.find((opt) => opt.value === str) || { text: str, value: str })
  33. .filter(Boolean);
  34. return {
  35. ...variable,
  36. current: { ...variable.current, text: values.map((val) => val?.text), value: values.map((val) => val?.value) },
  37. options: variable.options.map((option) => ({
  38. ...option,
  39. selected: typeof option.value === 'string' && split.includes(option.value),
  40. })),
  41. };
  42. });
  43. };
  44. export const collectVariables = () => {
  45. const variablePrefix = 'var-';
  46. const urlParams = new URLSearchParams(window.location.search);
  47. const variables: Record<string, string[]> = {};
  48. for (const [key, value] of urlParams.entries()) {
  49. if (key.startsWith(variablePrefix)) {
  50. const newKey = key.replace(variablePrefix, '');
  51. variables[newKey] = [...(variables[newKey] || []), value];
  52. }
  53. }
  54. return Object.fromEntries(Object.entries(variables).map(([key, value]) => [key, value.join(',')]));
  55. };