From ed59869528ce4374c9e7a2b40e134bdd19888d31 Mon Sep 17 00:00:00 2001
From: Ignacio Otero <nacho.ote@gmail.com>
Date: Wed, 6 Oct 2021 17:58:45 -0300
Subject: [PATCH] Terminada la funcionalidad de dar/quitar permisos de
 Administrador

---
 src/Controllers/UserCotroller.ts |  54 +++++++++++++
 src/Services/UserService.ts      | 135 +++++++++++++++++++++++++++++++
 2 files changed, 189 insertions(+)

diff --git a/src/Controllers/UserCotroller.ts b/src/Controllers/UserCotroller.ts
index f931b18..0432dd6 100644
--- a/src/Controllers/UserCotroller.ts
+++ b/src/Controllers/UserCotroller.ts
@@ -38,6 +38,28 @@ const listApproved = async (req: Request, res: Response): Promise<Response> => {
   }
 };
 
+const listClients = async (req: Request, res: Response): Promise<Response> => {
+  try {
+    const users: Paginator<User> = await UserService
+      .listClients(Number(req.query.limit), Number(req.query.offset), String(req.query.search));
+    return res.status(200).send(users);
+  } catch (error) {
+    const e = error as Error;
+    return res.status(400).json({ error: e.message });
+  }
+};
+
+const listAdmins = async (req: Request, res: Response): Promise<Response> => {
+  try {
+    const users: Paginator<User> = await UserService
+      .listAdmins(Number(req.query.limit), Number(req.query.offset), String(req.query.search));
+    return res.status(200).send(users);
+  } catch (error) {
+    const e = error as Error;
+    return res.status(400).json({ error: e.message });
+  }
+};
+
 const create = async (req: Request, res: Response): Promise<Response> => {
   try {
     const user: User = await UserService.create(req.body);
@@ -88,6 +110,26 @@ const cancel = async (req: Request, res: Response): Promise<Response> => {
   }
 };
 
+const giveAdminPermission = async (req: Request, res: Response): Promise<Response> => {
+  try {
+    const user: User = await UserService.giveAdminPermission(Number(req.params.id));
+    return res.status(200).send(user);
+  } catch (error) {
+    const e = error as Error;
+    return res.status(400).json({ error: e.message });
+  }
+};
+
+const removeAdminPermission = async (req: Request, res: Response): Promise<Response> => {
+  try {
+    const user: User = await UserService.removeAdminPermission(Number(req.params.id));
+    return res.status(200).send(user);
+  } catch (error) {
+    const e = error as Error;
+    return res.status(400).json({ error: e.message });
+  }
+};
+
 const active = async (req: Request, res: Response): Promise<Response> => {
   try {
     const user: User = await UserService.active(Number(req.params.id));
@@ -108,6 +150,12 @@ router.route('/pending')
 router.route('/approved')
   .get(listApproved);
 
+router.route('/clients')
+  .get(listClients);
+
+router.route('/admins')
+  .get(listAdmins);
+
 router.route('/:id')
   .put(update)
   .patch(active);
@@ -124,4 +172,10 @@ router.route('/:id/active')
 router.route('/:id/cancel')
   .put(cancel);
 
+router.route('/:id/admin')
+  .put(giveAdminPermission);
+
+router.route('/:id/client')
+  .put(removeAdminPermission);
+
 export default router;
diff --git a/src/Services/UserService.ts b/src/Services/UserService.ts
index e58d4ea..15149c6 100644
--- a/src/Services/UserService.ts
+++ b/src/Services/UserService.ts
@@ -80,6 +80,84 @@ const listApproved = async (limit: number, offset: number,
   });
 };
 
+const listClients = async (limit: number, offset: number,
+  search: string): Promise<Paginator<User>> => {
+  let options = {};
+  if (limit >= 1 && offset >= 0) {
+    if (search && search !== '') {
+      options = {
+        where: {
+          status: status.approved,
+          type: profiles.client,
+          [Op.or]: [
+            { name: { [Op.substring]: search } },
+            { email: { [Op.substring]: search } },
+          ],
+        },
+        limit,
+        offset,
+      };
+    } else {
+      options = {
+        where: {
+          status: status.approved,
+          type: profiles.client,
+        },
+        limit,
+        offset,
+      };
+    }
+  }
+  return User.findAndCountAll({
+    attributes: [
+      'id', 'name', 'email', 'organization', 'type', 'status', 'active', 'createdAt',
+    ],
+    order: [
+      ['createdAt', 'ASC'],
+    ],
+    ...options,
+  });
+};
+
+const listAdmins = async (limit: number, offset: number,
+  search: string): Promise<Paginator<User>> => {
+  let options = {};
+  if (limit >= 1 && offset >= 0) {
+    if (search && search !== '') {
+      options = {
+        where: {
+          status: status.approved,
+          type: profiles.administrator,
+          [Op.or]: [
+            { name: { [Op.substring]: search } },
+            { email: { [Op.substring]: search } },
+          ],
+        },
+        limit,
+        offset,
+      };
+    } else {
+      options = {
+        where: {
+          status: status.approved,
+          type: profiles.administrator,
+        },
+        limit,
+        offset,
+      };
+    }
+  }
+  return User.findAndCountAll({
+    attributes: [
+      'id', 'name', 'email', 'organization', 'type', 'status', 'active', 'createdAt',
+    ],
+    order: [
+      ['createdAt', 'ASC'],
+    ],
+    ...options,
+  });
+};
+
 const listAll = async (limit: number, offset: number): Promise<Paginator<User>> => {
   let options = {};
   if (limit >= 1 && offset >= 0) {
@@ -231,6 +309,59 @@ const cancel = async (userId: number): Promise<User> => User.findOne({
   } else {
     return user.update({
       status: status.pending,
+      type: profiles.client,
+      updatedAt: new Date(),
+    }).catch((error: Error) => {
+      console.log(error);
+      throw new Error('user update error');
+    });
+  }
+}).catch((error: Error) => {
+  console.log(error);
+  throw new Error('find user error');
+});
+
+const giveAdminPermission = async (userId: number): Promise<User> => User.findOne({
+  attributes: [
+    'id', 'name',
+    'email', 'type',
+    'createdAt',
+  ],
+  where: {
+    id: userId,
+  },
+}).then(async (user: User) => {
+  if (!user) {
+    throw new Error('user not found');
+  } else {
+    return user.update({
+      type: profiles.administrator,
+      updatedAt: new Date(),
+    }).catch((error: Error) => {
+      console.log(error);
+      throw new Error('user update error');
+    });
+  }
+}).catch((error: Error) => {
+  console.log(error);
+  throw new Error('find user error');
+});
+
+const removeAdminPermission = async (userId: number): Promise<User> => User.findOne({
+  attributes: [
+    'id', 'name',
+    'email', 'type',
+    'createdAt',
+  ],
+  where: {
+    id: userId,
+  },
+}).then(async (user: User) => {
+  if (!user) {
+    throw new Error('user not found');
+  } else {
+    return user.update({
+      type: profiles.client,
       updatedAt: new Date(),
     }).catch((error: Error) => {
       console.log(error);
@@ -266,10 +397,14 @@ export default {
   listAll,
   listPending,
   listApproved,
+  listClients,
+  listAdmins,
   create,
   update,
   password,
   approve,
   cancel,
   active,
+  giveAdminPermission,
+  removeAdminPermission,
 };
-- 
GitLab