plz / org.v
86 lines · 77 sloc · 1.94 KB · 4de5ced2a76bc53b998b59aafbda96221ab37dfe
Raw
1// Copyright (c) 2019-2026 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by a GPL license that can be found in the LICENSE file.
3module main
4
5import time
6
7struct Org {
8 id int @[primary; sql: serial]
9 name string @[unique]
10 contact_email string
11 kind string
12 created_at time.Time
13 created_by int
14}
15
16struct OrgMember {
17 id int @[primary; sql: serial]
18 org_id int @[unique: 'org_member']
19 user_id int @[unique: 'org_member']
20 role string
21}
22
23pub fn (mut app App) add_org(name string, contact_email string, kind string, created_by int) !int {
24 new_org := Org{
25 name: name
26 contact_email: contact_email
27 kind: kind
28 created_at: time.now()
29 created_by: created_by
30 }
31 sql app.db {
32 insert new_org into Org
33 }!
34 row := app.get_org_by_name(name) or { return error('failed to load newly created org') }
35 return row.id
36}
37
38pub fn (app App) get_org_by_name(name string) ?Org {
39 rows := sql app.db {
40 select from Org where name == name limit 1
41 } or { [] }
42 if rows.len == 0 {
43 return none
44 }
45 return rows.first()
46}
47
48pub fn (app App) get_org_by_id(id int) ?Org {
49 rows := sql app.db {
50 select from Org where id == id limit 1
51 } or { [] }
52 if rows.len == 0 {
53 return none
54 }
55 return rows.first()
56}
57
58pub fn (mut app App) add_org_member(org_id int, user_id int, role string) ! {
59 member := OrgMember{
60 org_id: org_id
61 user_id: user_id
62 role: role
63 }
64 sql app.db {
65 insert member into OrgMember
66 }!
67}
68
69pub fn (app App) find_orgs_for_user(user_id int) []Org {
70 members := sql app.db {
71 select from OrgMember where user_id == user_id
72 } or { [] }
73 mut orgs := []Org{cap: members.len}
74 for m in members {
75 org := app.get_org_by_id(m.org_id) or { continue }
76 orgs << org
77 }
78 return orgs
79}
80
81pub fn (app App) is_org_member(org_id int, user_id int) bool {
82 count := sql app.db {
83 select count from OrgMember where org_id == org_id && user_id == user_id
84 } or { 0 }
85 return count > 0
86}
87