(defmodule nemoptera_org
(export all))
(defun list-all ()
(case (nemoptera_db:q
"SELECT o.id, o.name, o.description, COUNT(r.id)
FROM organizations o LEFT JOIN repositories r ON r.organization_id=o.id
GROUP BY o.id ORDER BY o.name COLLATE NOCASE;" '())
(rows (when (is_list rows))
(lists:map
(lambda (row)
(let (((tuple id name description count) (nemoptera_db:as-tuple row)))
(maps:from_list
(list (tuple 'id id)
(tuple 'name (nemoptera_text:to-str name))
(tuple 'description (nemoptera_text:to-str description))
(tuple 'count (nemoptera_text:to-int count 0))))))
rows))
(_ '())))
(defun fetch (id)
(case (nemoptera_db:q "SELECT id, name, description, created_at FROM organizations WHERE id=?;" (list id))
(`((,oid ,name ,description ,created))
`#(ok ,(maps:from_list
(list (tuple 'id oid)
(tuple 'name (nemoptera_text:to-str name))
(tuple 'description (nemoptera_text:to-str description))
(tuple 'created_at (nemoptera_text:to-str created))))))
(_ `#(error "Organization not found."))))
(defun create (name description)
(case (nemoptera_validate:check-org-name name 0)
('ok
(case (nemoptera_db:q "INSERT INTO organizations(name,description,created_at) VALUES(?,?,?);"
(list name description (nemoptera_text:now-iso)))
(`#(error ,reason) `#(error ,(nemoptera_text:clip (io_lib:format "~p" (list reason)) 300)))
(`#(EXIT ,reason) `#(error ,(nemoptera_text:clip (io_lib:format "~p" (list reason)) 300)))
(_ `#(ok ,(nemoptera_db:insert-id)))))
(error error)))
(defun update (id name description)
(case (fetch id)
(`#(ok ,org)
(case (nemoptera_validate:check-org-name name id)
('ok
(let ((old (maps:get 'name org)))
(nemoptera_db:q "UPDATE organizations SET name=?, description=? WHERE id=?;"
(list name description id))
(if (=:= old name)
'ok
(restart-members id old name))
'ok))
(error error)))
(error error)))
(defun restart-members (id old-name new-name)
(case (nemoptera_db:q "SELECT name, fossil_path FROM repositories WHERE organization_id=?;" (list id))
(rows (when (is_list rows))
(lists:foreach
(lambda (row)
(let (((tuple slug path) (nemoptera_db:as-tuple row)))
(nemoptera_mgr:stop-repo old-name slug)
(nemoptera_mgr:start-repo new-name (nemoptera_text:to-str slug) (nemoptera_text:to-str path))))
rows))
(_ 'ok)))
(defun delete (id)
(case (nemoptera_db:q "SELECT COUNT(*) FROM repositories WHERE organization_id=?;" (list id))
(`((,count))
(if (> (nemoptera_text:to-int count 1) 0)
`#(error "Move or delete the repositories in this organization first.")
(progn
(nemoptera_db:q "DELETE FROM organizations WHERE id=?;" (list id))
'ok)))
(_ `#(error "Organization not found."))))