summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/sidebar/sidebar_mediator.js
blob: d86557e870a174c2e077bb5780cdb89c8c47b7cf (plain)
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
import { visitUrl } from '../lib/utils/url_utility';
import Flash from '../flash';
import Service from './services/sidebar_service';
import Store from './stores/sidebar_store';

export default class SidebarMediator {
  constructor(options) {
    if (!SidebarMediator.singleton) {
      this.initSingleton(options);
    }
    return SidebarMediator.singleton;
  }

  initSingleton(options) {
    this.store = new Store(options);
    this.service = new Service({
      endpoint: options.endpoint,
      toggleSubscriptionEndpoint: options.toggleSubscriptionEndpoint,
      moveIssueEndpoint: options.moveIssueEndpoint,
      projectsAutocompleteEndpoint: options.projectsAutocompleteEndpoint,
    });
    SidebarMediator.singleton = this;
  }

  assignYourself() {
    this.store.addAssignee(this.store.currentUser);
  }

  saveAssignees(field) {
    const selected = this.store.assignees.map(u => u.id);

    // If there are no ids, that means we have to unassign (which is id = 0)
    // And it only accepts an array, hence [0]
    return this.service.update(field, selected.length === 0 ? [0] : selected);
  }

  setMoveToProjectId(projectId) {
    this.store.setMoveToProjectId(projectId);
  }

  fetch() {
    return this.service.get()
      .then(response => response.json())
      .then((data) => {
        this.processFetchedData(data);
      })
      .catch(() => new Flash('Error occurred when fetching sidebar data'));
  }

  processFetchedData(data) {
    this.store.setAssigneeData(data);
    this.store.setTimeTrackingData(data);
    this.store.setParticipantsData(data);
    this.store.setSubscriptionsData(data);
  }

  toggleSubscription() {
    this.store.setFetchingState('subscriptions', true);
    return this.service.toggleSubscription()
      .then(() => {
        this.store.setSubscribedState(!this.store.subscribed);
        this.store.setFetchingState('subscriptions', false);
      })
      .catch((err) => {
        this.store.setFetchingState('subscriptions', false);
        throw err;
      });
  }

  fetchAutocompleteProjects(searchTerm) {
    return this.service.getProjectsAutocomplete(searchTerm)
      .then(response => response.json())
      .then((data) => {
        this.store.setAutocompleteProjects(data);
        return this.store.autocompleteProjects;
      });
  }

  moveIssue() {
    return this.service.moveIssue(this.store.moveToProjectId)
      .then(response => response.json())
      .then((data) => {
        if (location.pathname !== data.web_url) {
          visitUrl(data.web_url);
        }
      });
  }
}