Skip to content

Commit

Permalink
added delete org by admin functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
elraphty committed Nov 15, 2023
1 parent 26ed841 commit c51b46e
Show file tree
Hide file tree
Showing 10 changed files with 89 additions and 17 deletions.
12 changes: 10 additions & 2 deletions db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -1005,7 +1005,7 @@ func (db database) GetOrganizations(r *http.Request) []Organization {
offset, limit, sortBy, direction, search := utils.GetPaginationParams(r)

// return if like owner_alias, unique_name, or equals pubkey
db.db.Offset(offset).Limit(limit).Order(sortBy+" "+direction+" ").Where("LOWER(name) LIKE ?", "%"+search+"%").Find(&ms)
db.db.Offset(offset).Limit(limit).Order(sortBy+" "+direction+" ").Where("LOWER(name) LIKE ?", "%"+search+"%").Where("deleted != ?", false).Find(&ms)
return ms
}

Expand Down Expand Up @@ -1105,7 +1105,7 @@ func (db database) GetUserRoles(uuid string, pubkey string) []UserRoles {

func (db database) GetUserCreatedOrganizations(pubkey string) []Organization {
ms := []Organization{}
db.db.Where("owner_pub_key = ?", pubkey).Find(&ms)
db.db.Where("owner_pub_key = ?", pubkey).Where("deleted != ?", true).Find(&ms)
return ms
}

Expand Down Expand Up @@ -1300,3 +1300,11 @@ func (db database) DeleteUserInvoiceData(payment_request string) UserInvoiceData
db.db.Where("payment_request = ?", payment_request).Delete(&ms)
return ms
}

func (db database) ChangeOrganizationDeleteStatus(org_uuid string, status bool) Organization {
ms := Organization{}
db.db.Model(&ms).Where("uuid", org_uuid).Updates(map[string]interface{}{
"deleted": status,
})
return ms
}
1 change: 1 addition & 0 deletions db/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,7 @@ type Organization struct {
Created *time.Time `json:"created"`
Updated *time.Time `json:"updated"`
Show bool `json:"show"`
Deleted bool `gorm:"default:false" json:"deleted"`
BountyCount int64 `json:"bounty_count,omitempty"`
Budget uint `json:"budget,omitempty"`
}
Expand Down
13 changes: 9 additions & 4 deletions frontend/app/src/people/widgetViews/OrganizationDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const OrganizationDetails = (props: {
close: () => void;
org: Organization | undefined;
resetOrg: (Organization) => void;
getOrganizations: () => Promise<void>;
}) => {
const { main, ui } = useStores();

Expand Down Expand Up @@ -79,7 +80,7 @@ const OrganizationDetails = (props: {
const addWithdrawDisabled =
!isOrganizationAdmin && !userHasRole(main.bountyRoles, userRoles, 'WITHDRAW BUDGET');

const { org } = props;
const { org, close, getOrganizations } = props;
const uuid = org?.uuid || '';

function addToast(title: string, color: 'danger' | 'success') {
Expand Down Expand Up @@ -237,11 +238,15 @@ const OrganizationDetails = (props: {
};

const onDeleteOrg = async () => {
const res = { status: 200 };
const res = await main.organizationDelete(uuid);
if (res.status === 200) {
addToast('Still need to implement this', 'danger');
addToast('Deleted organization', 'success');
if (ui.meInfo) {
getOrganizations();
close();
}
} else {
addToast('Error: could not create organization', 'danger');
addToast('Error: could not delete organization', 'danger');
}
};

Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/people/widgetViews/OrganizationView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ const Organizations = (props: { person: Person }) => {
close={closeDetails}
org={organization}
resetOrg={(newOrg: Organization) => setOrganization(newOrg)}
getOrganizations={getUserOrganizations}
/>
)}
{!detailsOpen && (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Formik } from 'formik';
import { validator } from 'components/form/utils';
import { widgetConfigs } from 'people/utils/Constants';
import { FormField } from 'components/form/utils';
import { useStores } from 'store';
import Input from '../../../components/form/inputs';
import { Button, Modal } from '../../../components/common';
import { colors } from '../../../config/colors';
Expand Down Expand Up @@ -138,6 +139,8 @@ const HLine = styled.div`
`;

const EditOrgModal = (props: EditOrgModalProps) => {
const { ui } = useStores();

const isMobile = useIsMobile();
const { isOpen, close, onSubmit, onDelete, org } = props;
const [showDeleteModal, setShowDeleteModal] = useState<boolean>(false);
Expand All @@ -154,6 +157,8 @@ const EditOrgModal = (props: EditOrgModalProps) => {
const [selectedImage, setSelectedImage] = useState<string>(org?.img || '');
const fileInputRef = useRef<HTMLInputElement | null>(null);

const isOrganizationAdmin = props.org?.owner_pubkey === ui.meInfo?.owner_pubkey;

const handleFileInputChange = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files && e.target.files[0];
if (file) {
Expand Down Expand Up @@ -312,7 +317,7 @@ const EditOrgModal = (props: EditOrgModalProps) => {
</EditOrgColumns>
<HLine style={{ width: '551px', transform: 'translate(-48px, 0px' }} />
<Button
disabled={false}
disabled={!isOrganizationAdmin}
onClick={() => {
setShowDeleteModal(true);
}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ const s_RolesCategories = [
const RolesModal = (props: UserRolesModalProps) => {
const { main } = useStores();
const isMobile = useIsMobile();
const { isOpen, close, user, uuid } = props;
const { isOpen, close, user, uuid, addToast } = props;

const roleData = main.bountyRoles.map((role: any) => ({
name: role.name,
Expand Down Expand Up @@ -183,7 +183,7 @@ const RolesModal = (props: UserRolesModalProps) => {
if (res.status === 200) {
await main.getUserRoles(uuid, user.owner_pubkey);
} else {
// addToast('Error: could not add user roles', 'danger');
addToast('Error: could not add user roles', 'danger');
}
close();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export interface EditOrgModalProps extends ModalProps {

export interface UserRolesModalProps extends ModalProps {
submitRoles: (roles: BountyRoles[]) => void;
addToast: (title: string, color: 'danger' | 'success') => void;
}

export interface PaymentHistoryModalProps extends ModalProps {
Expand Down
20 changes: 20 additions & 0 deletions frontend/app/src/store/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ export interface Organization {
show: boolean;
bounty_count?: number;
budget?: number;
deleted?: boolean;
}

export interface BountyRoles {
Expand Down Expand Up @@ -2187,6 +2188,25 @@ export class MainStore {
console.error('Error pollInvoice', e);
}
}

async organizationDelete(org_uuid: string): Promise<any> {
try {
if (!uiStore.meInfo) return 0;
const info = uiStore.meInfo;
const r: any = await fetch(`${TribesURL}/organizations/delete/${org_uuid}`, {
method: 'DELETE',
mode: 'cors',
headers: {
'x-jwt': info.tribe_jwt,
'Content-Type': 'application/json'
}
});

return r;
} catch (e) {
console.error('organizationDelete', e);
}
}
}

export const mainStore = new MainStore();
46 changes: 38 additions & 8 deletions handlers/organizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,15 +393,18 @@ func GetUserOrganizations(w http.ResponseWriter, r *http.Request) {
bountyCount := db.DB.GetOrganizationBountyCount(uuid)
hasRole := db.UserHasAccess(user.OwnerPubKey, uuid, db.ViewReport)

if hasRole {
budget := db.DB.GetOrganizationBudget(uuid)
organization.Budget = budget.TotalBudget
} else {
organization.Budget = 0
}
organization.BountyCount = bountyCount
// don't add deleted organizations to the list
if !organization.Deleted {
if hasRole {
budget := db.DB.GetOrganizationBudget(uuid)
organization.Budget = budget.TotalBudget
} else {
organization.Budget = 0
}
organization.BountyCount = bountyCount

organizations = append(organizations, organization)
organizations = append(organizations, organization)
}
}

w.WriteHeader(http.StatusOK)
Expand Down Expand Up @@ -544,3 +547,30 @@ func GetInvoicesCount(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(invoiceCount)
}

func DeleteOrganization(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string)
uuid := chi.URLParam(r, "uuid")

if pubKeyFromAuth == "" {
fmt.Println("no pubkey from auth")
w.WriteHeader(http.StatusUnauthorized)
return
}

organization := db.DB.GetOrganizationByUuid(uuid)

if pubKeyFromAuth != organization.OwnerPubKey {
msg := "only org admin can delete an organization"
fmt.Println(msg)
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(msg)
return
}

// soft delete organization
org := db.DB.ChangeOrganizationDeleteStatus(uuid, true)
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(org)
}
1 change: 1 addition & 0 deletions routes/organizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func OrganizationRoutes() chi.Router {
r.Get("/payments/{uuid}", handlers.GetPaymentHistory)
r.Get("/poll/invoices/{uuid}", handlers.PollBudgetInvoices)
r.Get("/invoices/count/{uuid}", handlers.GetInvoicesCount)
r.Delete("/delete/{uuid}", handlers.DeleteOrganization)
})
return r
}

0 comments on commit c51b46e

Please sign in to comment.