event_editor.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import _ from 'lodash';
  2. import moment from 'moment';
  3. import { coreModule } from 'app/core/core';
  4. import { MetricsPanelCtrl } from 'app/plugins/sdk';
  5. import { AnnotationEvent } from '@grafana/ui';
  6. export class EventEditorCtrl {
  7. panelCtrl: MetricsPanelCtrl;
  8. event: AnnotationEvent;
  9. timeRange: { from: number; to: number };
  10. form: any;
  11. close: any;
  12. timeFormated: string;
  13. /** @ngInject */
  14. constructor(private annotationsSrv) {
  15. this.event.panelId = this.panelCtrl.panel.id;
  16. this.event.dashboardId = this.panelCtrl.dashboard.id;
  17. // Annotations query returns time as Unix timestamp in milliseconds
  18. this.event.time = tryEpochToMoment(this.event.time);
  19. if (this.event.isRegion) {
  20. this.event.timeEnd = tryEpochToMoment(this.event.timeEnd);
  21. }
  22. this.timeFormated = this.panelCtrl.dashboard.formatDate(this.event.time);
  23. }
  24. save() {
  25. if (!this.form.$valid) {
  26. return;
  27. }
  28. const saveModel = _.cloneDeep(this.event);
  29. saveModel.time = saveModel.time.valueOf();
  30. saveModel.timeEnd = 0;
  31. if (saveModel.isRegion) {
  32. saveModel.timeEnd = this.event.timeEnd.valueOf();
  33. if (saveModel.timeEnd < saveModel.time) {
  34. console.log('invalid time');
  35. return;
  36. }
  37. }
  38. if (saveModel.id) {
  39. this.annotationsSrv
  40. .updateAnnotationEvent(saveModel)
  41. .then(() => {
  42. this.panelCtrl.refresh();
  43. this.close();
  44. })
  45. .catch(() => {
  46. this.panelCtrl.refresh();
  47. this.close();
  48. });
  49. } else {
  50. this.annotationsSrv
  51. .saveAnnotationEvent(saveModel)
  52. .then(() => {
  53. this.panelCtrl.refresh();
  54. this.close();
  55. })
  56. .catch(() => {
  57. this.panelCtrl.refresh();
  58. this.close();
  59. });
  60. }
  61. }
  62. delete() {
  63. return this.annotationsSrv
  64. .deleteAnnotationEvent(this.event)
  65. .then(() => {
  66. this.panelCtrl.refresh();
  67. this.close();
  68. })
  69. .catch(() => {
  70. this.panelCtrl.refresh();
  71. this.close();
  72. });
  73. }
  74. }
  75. function tryEpochToMoment(timestamp) {
  76. if (timestamp && _.isNumber(timestamp)) {
  77. const epoch = Number(timestamp);
  78. return moment(epoch);
  79. } else {
  80. return timestamp;
  81. }
  82. }
  83. export function eventEditor() {
  84. return {
  85. restrict: 'E',
  86. controller: EventEditorCtrl,
  87. bindToController: true,
  88. controllerAs: 'ctrl',
  89. templateUrl: 'public/app/features/annotations/partials/event_editor.html',
  90. scope: {
  91. panelCtrl: '=',
  92. event: '=',
  93. close: '&',
  94. },
  95. };
  96. }
  97. coreModule.directive('eventEditor', eventEditor);