@webship.co/workspace-plane 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,340 @@
1
+ # The site of a Plane project of the Webship Workspace, through Django's own shell in Plane's container.
2
+ #
3
+ # Run by the Plane builder and its tool (fun-plane.sh) as
4
+ # PLANE_VERBS='<verb>…' python manage.py shell -c "exec(open('/opt/webship/plane-site.py').read())"
5
+ # in /app/backend of Plane's all-in-one container. A payload (the accounts, a login) travels on the input, never on a
6
+ # command line. What is made is made as its author (crum's impersonation), as Plane's own screens would.
7
+ #
8
+ # defaults the instance set up: its setup done, sign-ups closed, e-mail and password logins, no telemetry
9
+ # accounts make the accounts of the input (the base64 of a JSON list), or give them back their names, passwords and
10
+ # roles: an admin row is the instance's administrator; a row with a role (Admin, Member, Guest) is a member
11
+ # of the sample workspace and project in it, made with them; a row with action "lock" is kept from
12
+ # logging in
13
+ # content the sample content, where it is missing: the cycle Sprint 1, the label bug, three work items, a comment
14
+ # tidy remove for good the work items a stopped test run left (titled "Webship test …" and made by one of the
15
+ # default accounts), and the comments the default accounts deleted in the sample project; nothing else
16
+ # list what the site holds: the accounts, their memberships, the work items and the cycles
17
+ # token a new API key of the account named on the input (its login or e-mail), in the sample workspace, the
18
+ # earlier one of the Workspace revoked: "TOKEN <key>"
19
+ # version the release the site runs: "VERSION <release>"
20
+ # counts what the sample project holds, one count a line, deleted rows left out: a test run must leave them
21
+
22
+ import base64
23
+ import datetime
24
+ import json
25
+ import os
26
+ import sys
27
+
28
+ from crum import impersonate
29
+ from django.core.cache import cache
30
+ from django.utils import timezone
31
+
32
+ from plane.api.serializers import ProjectCreateSerializer
33
+ from plane.db.models import (DEFAULT_STATES, APIToken, Cycle, CycleIssue, Issue, IssueActivity, IssueAssignee,
34
+ IssueComment, IssueLabel, Label, Profile, Project, ProjectMember, State, User, Workspace,
35
+ WorkspaceMember)
36
+ from plane.license.models import Instance, InstanceAdmin, InstanceConfiguration
37
+
38
+ VERBS = os.environ.get('PLANE_VERBS', '').split()
39
+ WORKSPACE_SLUG = 'webship'
40
+ WORKSPACE_NAME = 'Webship'
41
+ PROJECT_IDENTIFIER = 'WEB'
42
+ PROJECT_NAME = 'Webship site'
43
+ CYCLE = 'Sprint 1'
44
+ # What a test run makes: titled "Webship test …", by one of the default accounts. tidy removes nothing else.
45
+ TEST_PREFIX = 'Webship test '
46
+ TEST_ACCOUNTS = ['owner', 'member', 'reader', 'stranger']
47
+ TOKEN_LABEL = 'webship-workspace'
48
+ ROLES = {'Admin': 20, 'Member': 15, 'Guest': 5}
49
+
50
+ ISSUES = [
51
+ {'name': 'The greeting script says Helo instead of Hello', 'author': 'owner', 'state': 'In Progress',
52
+ 'priority': 'high', 'assignee': 'member', 'cycle': True, 'label': True,
53
+ 'body': '<p>Run <code>./greeting.sh Ada</code>: it prints "Helo, Ada!". It should print "Hello, Ada!".</p>',
54
+ 'comment': "<p>The script is in the project's repository: <code>greeting.sh</code>.</p>"},
55
+ {'name': 'The usage line spells greeting as greting', 'author': 'member', 'state': 'Todo', 'priority': 'low',
56
+ 'assignee': None, 'cycle': False, 'label': False,
57
+ 'body': '<p>Run <code>./greeting.sh</code> with no name: it prints "Usage: greting.sh &lt;name&gt;".</p>',
58
+ 'comment': None},
59
+ {'name': 'An issue opened by someone outside the project', 'author': 'reader', 'state': 'Todo', 'priority': 'none',
60
+ 'assignee': None, 'cycle': False, 'label': False,
61
+ 'body': '<p>A guest of the project opened this work item: the tracker treats it as from outside the project.</p>',
62
+ 'comment': None},
63
+ ]
64
+
65
+
66
+ def fail(message):
67
+ sys.stderr.write(message + '\n')
68
+ sys.exit(1)
69
+
70
+
71
+ def read_rows():
72
+ raw = sys.stdin.read().strip()
73
+ if not raw:
74
+ return []
75
+ try:
76
+ return json.loads(base64.b64decode(raw).decode())
77
+ except ValueError:
78
+ fail('The accounts on the input are not the base64 of a JSON list.')
79
+
80
+
81
+ def user_by(login):
82
+ return User.objects.filter(email=login).first() or User.objects.filter(username=login).first()
83
+
84
+
85
+ def defaults():
86
+ instance = Instance.objects.first()
87
+ if instance is None:
88
+ fail('Plane has registered no instance yet: its API has not started.')
89
+ instance.is_setup_done = True
90
+ instance.is_signup_screen_visited = True
91
+ instance.is_telemetry_enabled = False
92
+ instance.is_support_required = False
93
+ instance.save()
94
+ for key, value in [('ENABLE_SIGNUP', '0'), ('ENABLE_EMAIL_PASSWORD', '1'), ('ENABLE_MAGIC_LINK_LOGIN', '0'),
95
+ ('DISABLE_WORKSPACE_CREATION', '1')]:
96
+ config, _ = InstanceConfiguration.objects.get_or_create(key=key, defaults={'category': 'AUTHENTICATION'})
97
+ config.value = value
98
+ config.save()
99
+ # The instance's answer is cached for two hours: what was set must be what the app reads now.
100
+ cache.clear()
101
+ print('defaults: the instance is set up, sign-ups closed, e-mail and password logins')
102
+
103
+
104
+ def onboarded(user, workspace=None):
105
+ profile, _ = Profile.objects.get_or_create(user=user)
106
+ profile.is_onboarded = True
107
+ profile.is_tour_completed = True
108
+ profile.is_navigation_tour_completed = True
109
+ profile.onboarding_step = {'profile_complete': True, 'workspace_create': True, 'workspace_invite': True,
110
+ 'workspace_join': True}
111
+ if workspace is not None:
112
+ profile.last_workspace_id = workspace.id
113
+ profile.save()
114
+
115
+
116
+ def workspace_and_project(owner):
117
+ workspace = Workspace.objects.filter(slug=WORKSPACE_SLUG).first()
118
+ if workspace is None:
119
+ with impersonate(owner):
120
+ workspace = Workspace.objects.create(name=WORKSPACE_NAME, slug=WORKSPACE_SLUG, owner=owner)
121
+ project = Project.objects.filter(workspace=workspace, identifier=PROJECT_IDENTIFIER).first()
122
+ if project is None:
123
+ with impersonate(owner):
124
+ serializer = ProjectCreateSerializer(data={'name': PROJECT_NAME, 'identifier': PROJECT_IDENTIFIER,
125
+ 'network': 2, 'cycle_view': True, 'module_view': False},
126
+ context={'workspace_id': workspace.id})
127
+ if not serializer.is_valid():
128
+ fail('The sample project could not be made: %s' % serializer.errors)
129
+ project = serializer.save()
130
+ State.objects.bulk_create([
131
+ State(name=s['name'], color=s['color'], project=project, sequence=s['sequence'], workspace=workspace,
132
+ group=s['group'], default=s.get('default', False), created_by=owner)
133
+ for s in DEFAULT_STATES])
134
+ print('project: %s (%s) made in the workspace %s' % (PROJECT_NAME, PROJECT_IDENTIFIER, WORKSPACE_SLUG))
135
+ return workspace, project
136
+
137
+
138
+ def accounts(rows):
139
+ instance = Instance.objects.first()
140
+ admins = [r for r in rows if r.get('role') == 'Admin' and r.get('action') != 'lock']
141
+ for row in rows:
142
+ user = user_by(row['mail']) or user_by(row['login'])
143
+ if row.get('action') == 'lock':
144
+ if user is not None:
145
+ user.is_active = False
146
+ user.save()
147
+ print('%s: kept from logging in' % row['login'])
148
+ continue
149
+ first, _, last = row['fullname'].partition(' ')
150
+ if user is None:
151
+ user = User(email=row['mail'], username=row['login'])
152
+ user.email = row['mail']
153
+ user.username = row['login']
154
+ user.display_name = row['login']
155
+ user.first_name = first
156
+ user.last_name = last
157
+ user.is_active = True
158
+ user.is_email_verified = True
159
+ user.is_password_autoset = False
160
+ user.set_password(row['password'])
161
+ user.save()
162
+ onboarded(user)
163
+ print('%s: account ready (%s)%s' % (row['login'], row['mail'], ', the instance administrator' if row.get('admin') else ''))
164
+ if row.get('admin') and instance is not None:
165
+ InstanceAdmin.objects.get_or_create(user=user, instance=instance, defaults={'role': 20, 'is_verified': True})
166
+ cache.clear()
167
+ if not any(r.get('role') for r in rows):
168
+ return
169
+ owner = user_by(admins[0]['mail']) if admins else None
170
+ if owner is None:
171
+ existing = Workspace.objects.filter(slug=WORKSPACE_SLUG).first()
172
+ owner = existing.owner if existing else None
173
+ if owner is None:
174
+ fail('The sample workspace needs an Admin among the accounts.')
175
+ workspace, project = workspace_and_project(owner)
176
+ for row in rows:
177
+ if row.get('action') == 'lock':
178
+ continue
179
+ user = user_by(row['mail'])
180
+ role = ROLES.get(row.get('role') or '')
181
+ if role is None:
182
+ WorkspaceMember.objects.filter(workspace=workspace, member=user).delete()
183
+ ProjectMember.objects.filter(project=project, member=user).delete()
184
+ print('%s: no membership of %s' % (row['login'], PROJECT_NAME))
185
+ continue
186
+ wm, _ = WorkspaceMember.objects.get_or_create(workspace=workspace, member=user, defaults={'role': role})
187
+ wm.role, wm.is_active = role, True
188
+ wm.save()
189
+ pm, _ = ProjectMember.objects.get_or_create(project=project, workspace=workspace, member=user, defaults={'role': role})
190
+ pm.role, pm.is_active = role, True
191
+ pm.save()
192
+ onboarded(user, workspace)
193
+ print('%s: %s of %s' % (row['login'], row['role'], PROJECT_NAME))
194
+
195
+
196
+ def sample_project():
197
+ workspace = Workspace.objects.filter(slug=WORKSPACE_SLUG).first()
198
+ project = workspace and Project.objects.filter(workspace=workspace, identifier=PROJECT_IDENTIFIER).first()
199
+ if not project:
200
+ fail('The sample project is not there: add the default accounts first (--add-users).')
201
+ return workspace, project
202
+
203
+
204
+ def content():
205
+ workspace, project = sample_project()
206
+ owner = User.objects.get(username='owner')
207
+ today = timezone.now()
208
+ cycle = Cycle.objects.filter(project=project, name=CYCLE).first()
209
+ if cycle is None:
210
+ with impersonate(owner):
211
+ cycle = Cycle.objects.create(project=project, workspace=workspace, name=CYCLE, owned_by=owner,
212
+ description='The current iteration of the sample project.',
213
+ start_date=today - datetime.timedelta(days=3),
214
+ end_date=today + datetime.timedelta(days=11))
215
+ label = Label.objects.filter(project=project, name='bug').first()
216
+ if label is None:
217
+ with impersonate(owner):
218
+ label = Label.objects.create(project=project, workspace=workspace, name='bug', color='#ee0701')
219
+ states = {s.name: s for s in State.objects.filter(project=project)}
220
+ for spec in ISSUES:
221
+ if Issue.objects.filter(project=project, name=spec['name']).exists():
222
+ continue
223
+ author = User.objects.get(username=spec['author'])
224
+ with impersonate(author):
225
+ issue = Issue.objects.create(project=project, workspace=workspace, name=spec['name'],
226
+ description_html=spec['body'], priority=spec['priority'],
227
+ state=states.get(spec['state']))
228
+ if spec['assignee']:
229
+ IssueAssignee.objects.create(issue=issue, assignee=User.objects.get(username=spec['assignee']),
230
+ project=project, workspace=workspace)
231
+ if spec['label']:
232
+ IssueLabel.objects.create(issue=issue, label=label, project=project, workspace=workspace)
233
+ if spec['cycle']:
234
+ CycleIssue.objects.create(issue=issue, cycle=cycle, project=project, workspace=workspace)
235
+ if spec['comment']:
236
+ IssueComment.objects.create(issue=issue, project=project, workspace=workspace, actor=author,
237
+ comment_html=spec['comment'])
238
+ print('content: %s holds %d work items, %s (%s to %s)' % (PROJECT_NAME, Issue.issue_objects.filter(project=project).count(),
239
+ CYCLE, cycle.start_date.date(), cycle.end_date.date()))
240
+
241
+
242
+ def tidy():
243
+ workspace, project = sample_project()
244
+ authors = User.objects.filter(username__in=TEST_ACCOUNTS, email__endswith='@example.com')
245
+ left = Issue.all_objects.filter(project=project, name__startswith=TEST_PREFIX, created_by__in=authors)
246
+ count = left.count()
247
+ for issue in left:
248
+ # Plane keeps the history of a work item it deletes: removed for good, its history goes first.
249
+ IssueActivity.all_objects.filter(issue=issue).delete()
250
+ issue.delete(soft=False)
251
+ # Plane keeps a deleted comment, marked; the ones the default accounts deleted go for good, their history kept.
252
+ gone = IssueComment.all_objects.filter(project=project, deleted_at__isnull=False, actor__in=authors)
253
+ removed = gone.count()
254
+ for comment in gone:
255
+ IssueActivity.all_objects.filter(issue_comment=comment).update(issue_comment=None)
256
+ comment.delete(soft=False)
257
+ print('tidy: %d work item(s) a test run left removed for good, %d comment(s) the default accounts deleted' % (count, removed))
258
+
259
+
260
+ def counts():
261
+ workspace, project = sample_project()
262
+ live = Issue.issue_objects.filter(project=project)
263
+ on_live = {'project': project, 'issue__deleted_at__isnull': True}
264
+ for name, number in [
265
+ ('work items', live.count()),
266
+ ('open work items', live.exclude(state__group__in=['completed', 'cancelled']).count()),
267
+ ('comments', IssueComment.objects.filter(**on_live).count()),
268
+ ('assignees', IssueAssignee.objects.filter(**on_live).count()),
269
+ ('labels on work items', IssueLabel.objects.filter(**on_live).count()),
270
+ ('work items in cycles', CycleIssue.objects.filter(**on_live).count()),
271
+ ('cycles', Cycle.objects.filter(project=project).count()),
272
+ ('labels', Label.objects.filter(project=project).count()),
273
+ ('states', State.objects.filter(project=project).count()),
274
+ ('project members', ProjectMember.objects.filter(project=project, is_active=True).count()),
275
+ ('workspace members', WorkspaceMember.objects.filter(workspace=workspace, is_active=True).count()),
276
+ ('users', User.objects.filter(is_bot=False).count()),
277
+ ]:
278
+ print('%s: %d' % (name, number))
279
+
280
+
281
+ def listing():
282
+ workspace = Workspace.objects.filter(slug=WORKSPACE_SLUG).first()
283
+ project = workspace and Project.objects.filter(workspace=workspace, identifier=PROJECT_IDENTIFIER).first()
284
+ instance = Instance.objects.first()
285
+ admins = set(InstanceAdmin.objects.filter(instance=instance).values_list('user_id', flat=True))
286
+ names = {20: 'Admin', 15: 'Member', 5: 'Guest'}
287
+ print('Accounts:')
288
+ for user in User.objects.filter(is_bot=False).order_by('date_joined'):
289
+ role = ''
290
+ if user.id in admins:
291
+ role = 'instance administrator'
292
+ elif project:
293
+ pm = ProjectMember.objects.filter(project=project, member=user, is_active=True).first()
294
+ role = '%s of %s' % (names.get(pm.role, pm.role), PROJECT_NAME) if pm else 'no membership'
295
+ print(' %-12s %-28s %-9s %s' % (user.username, user.email, 'active' if user.is_active else 'blocked', role))
296
+ if project:
297
+ items = Issue.issue_objects.filter(project=project)
298
+ cycles = Cycle.objects.filter(project=project).count()
299
+ print('%s (%s/%s): %d work items, %d cycle(s)' % (PROJECT_NAME, WORKSPACE_SLUG, PROJECT_IDENTIFIER, items.count(), cycles))
300
+
301
+
302
+ def token():
303
+ login = sys.stdin.readline().strip()
304
+ user = user_by(login)
305
+ workspace = Workspace.objects.filter(slug=WORKSPACE_SLUG).first()
306
+ if user is None or not user.is_active:
307
+ fail('No active account %s.' % login)
308
+ if workspace is None or not WorkspaceMember.objects.filter(workspace=workspace, member=user, is_active=True).exists():
309
+ fail('%s is no member of the workspace %s.' % (login, WORKSPACE_SLUG))
310
+ APIToken.objects.filter(user=user, label=TOKEN_LABEL).delete()
311
+ key = APIToken.objects.create(user=user, workspace=workspace, label=TOKEN_LABEL, user_type=0,
312
+ description='The Webship Workspace dashboard (cmd-tools-plane-cli.sh --connect).')
313
+ print('TOKEN %s' % key.token)
314
+
315
+
316
+ def version():
317
+ instance = Instance.objects.first()
318
+ print('VERSION %s' % ((instance and instance.current_version) or os.environ.get('PLANE_RELEASE', '')))
319
+
320
+
321
+ ROWS = read_rows() if 'accounts' in VERBS else []
322
+ for verb in VERBS:
323
+ if verb == 'defaults':
324
+ defaults()
325
+ elif verb == 'accounts':
326
+ accounts(ROWS)
327
+ elif verb == 'content':
328
+ content()
329
+ elif verb == 'tidy':
330
+ tidy()
331
+ elif verb == 'list':
332
+ listing()
333
+ elif verb == 'token':
334
+ token()
335
+ elif verb == 'version':
336
+ version()
337
+ elif verb == 'counts':
338
+ counts()
339
+ else:
340
+ fail('No verb %s: defaults, accounts, content, tidy, list, token, version, counts.' % verb)
@@ -0,0 +1,18 @@
1
+ #!/bin/sh
2
+ # The start of Plane's all-in-one container for a site of the Webship Workspace (the plugin's plane-start.sh, mounted at
3
+ # /opt/webship). The image starts from its own settings file, /app/plane.env: it copies some of the container's values
4
+ # into it (the address, the database, the queue, the store, the secret keys) and keeps its own defaults for the rest.
5
+ # The values a site sets that the image does not copy go into that file first, then the image's own start runs.
6
+ set -eu
7
+ cd /app
8
+ for key in AUTHENTICATION_RATE_LIMIT GUNICORN_WORKERS ; do
9
+ value="$(printenv "${key}" || true)"
10
+ [ -n "${value}" ] || continue
11
+ if grep -q "^${key}=" plane.env ; then
12
+ KEY="${key}" VALUE="${value}" awk 'index($0, ENVIRON["KEY"] "=") == 1 { print ENVIRON["KEY"] "=" ENVIRON["VALUE"]; next } { print }' plane.env > plane.env.tmp
13
+ mv plane.env.tmp plane.env
14
+ else
15
+ printf '%s=%s\n' "${key}" "${value}" >> plane.env
16
+ fi
17
+ done
18
+ exec /app/start.sh
@@ -0,0 +1,34 @@
1
+ @site
2
+ Feature: The work items of the site
3
+ A first feature of a Plane site of the Webship Workspace, placed by the testing setup: the site opens on its login
4
+ form, a member reads the sample project's work items and its cycle, and works a work item of its own, which goes
5
+ after the scenario. It passes on a site built with --install --add-users --sample-content; add your own features
6
+ beside it.
7
+
8
+ # A site whose instance is set up asks a visitor to log in; one that is not asks for its setup ("Get started").
9
+ Scenario: The site opens on its login form, set up
10
+ Given I am not logged in
11
+ When I go to the homepage
12
+ Then I should see "Welcome back to Plane"
13
+ And I should not see "Get started"
14
+
15
+ Scenario: A member reads the sample project
16
+ Given I am a logged in user with the "member" user
17
+ When I open the project "WEB"
18
+ Then the work item list should show "The greeting script says Helo instead of Hello"
19
+ When I open the cycle "Sprint 1" of the project "WEB"
20
+ Then the cycle should list the work item "The greeting script says Helo instead of Hello"
21
+
22
+ Scenario: A member works a work item of its own
23
+ Given there is a work item "Webship test site" in the project "WEB"
24
+ And I am a logged in user with the "member" user
25
+ When I open the work item "Webship test site"
26
+ And I set the state of the work item to "In Progress"
27
+ And I add the comment "Checked on the test site" to the work item
28
+ Then the work item should show the comment "Checked on the test site" by "member"
29
+ And the state of the work item should be "In Progress"
30
+
31
+ @js-off
32
+ Scenario: An account with no membership is refused the project
33
+ Given I am a logged in user with the "stranger" user
34
+ Then I should be refused the project "WEB"