user-collection.service.ts 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. import { Injectable } from '@nestjs/common';
  2. import {
  3. USER_COLL_DEST_SAME,
  4. USER_COLL_IS_PARENT_COLL,
  5. USER_COLL_NOT_FOUND,
  6. USER_COLL_NOT_SAME_TYPE,
  7. USER_COLL_NOT_SAME_USER,
  8. USER_COLL_REORDERING_FAILED,
  9. USER_COLL_SAME_NEXT_COLL,
  10. USER_COLL_SHORT_TITLE,
  11. USER_COLL_ALREADY_ROOT,
  12. USER_NOT_FOUND,
  13. USER_NOT_OWNER,
  14. USER_COLL_INVALID_JSON,
  15. } from 'src/errors';
  16. import { PrismaService } from 'src/prisma/prisma.service';
  17. import { AuthUser } from 'src/types/AuthUser';
  18. import * as E from 'fp-ts/Either';
  19. import * as O from 'fp-ts/Option';
  20. import { PubSubService } from 'src/pubsub/pubsub.service';
  21. import { Prisma, UserCollection, ReqType as DBReqType } from '@prisma/client';
  22. import {
  23. UserCollection as UserCollectionModel,
  24. UserCollectionExportJSONData,
  25. } from './user-collections.model';
  26. import { ReqType } from 'src/types/RequestTypes';
  27. import { isValidLength, stringToJson } from 'src/utils';
  28. import { CollectionFolder } from 'src/types/CollectionFolder';
  29. @Injectable()
  30. export class UserCollectionService {
  31. constructor(
  32. private readonly prisma: PrismaService,
  33. private readonly pubsub: PubSubService,
  34. ) {}
  35. TITLE_LENGTH = 1;
  36. /**
  37. * Typecast a database UserCollection to a UserCollection model
  38. * @param userCollection database UserCollection
  39. * @returns UserCollection model
  40. */
  41. private cast(collection: UserCollection) {
  42. return <UserCollectionModel>{
  43. ...collection,
  44. userID: collection.userUid,
  45. };
  46. }
  47. /**
  48. * Returns the count of child collections present for a given collectionID
  49. * * The count returned is highest OrderIndex + 1
  50. *
  51. * @param collectionID The Collection ID
  52. * @returns Number of Child Collections
  53. */
  54. private async getChildCollectionsCount(collectionID: string) {
  55. const childCollectionCount = await this.prisma.userCollection.findMany({
  56. where: { parentID: collectionID },
  57. orderBy: {
  58. orderIndex: 'desc',
  59. },
  60. });
  61. if (!childCollectionCount.length) return 0;
  62. return childCollectionCount[0].orderIndex;
  63. }
  64. /**
  65. * Returns the count of root collections present for a given userUID
  66. * * The count returned is highest OrderIndex + 1
  67. *
  68. * @param userID The User UID
  69. * @returns Number of Root Collections
  70. */
  71. private async getRootCollectionsCount(userID: string) {
  72. const rootCollectionCount = await this.prisma.userCollection.findMany({
  73. where: { userUid: userID, parentID: null },
  74. orderBy: {
  75. orderIndex: 'desc',
  76. },
  77. });
  78. if (!rootCollectionCount.length) return 0;
  79. return rootCollectionCount[0].orderIndex;
  80. }
  81. /**
  82. * Check to see if Collection belongs to User
  83. *
  84. * @param collectionID The collection ID
  85. * @param userID The User ID
  86. * @returns An Option of a Boolean
  87. */
  88. private async isOwnerCheck(collectionID: string, userID: string) {
  89. try {
  90. await this.prisma.userCollection.findFirstOrThrow({
  91. where: {
  92. id: collectionID,
  93. userUid: userID,
  94. },
  95. });
  96. return O.some(true);
  97. } catch (error) {
  98. return O.none;
  99. }
  100. }
  101. /**
  102. * Get User of given Collection ID
  103. *
  104. * @param collectionID The collection ID
  105. * @returns User of given Collection ID
  106. */
  107. async getUserOfCollection(collectionID: string) {
  108. try {
  109. const userCollection = await this.prisma.userCollection.findUniqueOrThrow(
  110. {
  111. where: {
  112. id: collectionID,
  113. },
  114. include: {
  115. user: true,
  116. },
  117. },
  118. );
  119. return E.right(userCollection.user);
  120. } catch (error) {
  121. return E.left(USER_NOT_FOUND);
  122. }
  123. }
  124. /**
  125. * Get parent of given Collection ID
  126. *
  127. * @param collectionID The collection ID
  128. * @returns Parent UserCollection of given Collection ID
  129. */
  130. async getParentOfUserCollection(collectionID: string) {
  131. const { parent } = await this.prisma.userCollection.findUnique({
  132. where: {
  133. id: collectionID,
  134. },
  135. include: {
  136. parent: true,
  137. },
  138. });
  139. return parent;
  140. }
  141. /**
  142. * Get child collections of given Collection ID
  143. *
  144. * @param collectionID The collection ID
  145. * @param cursor collectionID for pagination
  146. * @param take Number of items we want returned
  147. * @param type Type of UserCollection
  148. * @returns A list of child collections
  149. */
  150. async getChildrenOfUserCollection(
  151. collectionID: string,
  152. cursor: string | null,
  153. take: number,
  154. type: ReqType,
  155. ) {
  156. return this.prisma.userCollection.findMany({
  157. where: {
  158. parentID: collectionID,
  159. type: type,
  160. },
  161. orderBy: {
  162. orderIndex: 'asc',
  163. },
  164. take: take, // default: 10
  165. skip: cursor ? 1 : 0,
  166. cursor: cursor ? { id: cursor } : undefined,
  167. });
  168. }
  169. /**
  170. * Get collection details
  171. *
  172. * @param collectionID The collection ID
  173. * @returns An Either of the Collection details
  174. */
  175. async getUserCollection(collectionID: string) {
  176. try {
  177. const userCollection = await this.prisma.userCollection.findUniqueOrThrow(
  178. {
  179. where: {
  180. id: collectionID,
  181. },
  182. },
  183. );
  184. return E.right(userCollection);
  185. } catch (error) {
  186. return E.left(USER_COLL_NOT_FOUND);
  187. }
  188. }
  189. /**
  190. * Create a new UserCollection
  191. *
  192. * @param user The User object
  193. * @param title The title of new UserCollection
  194. * @param parentUserCollectionID The parent collectionID (null if root collection)
  195. * @param type Type of Collection we want to create (REST/GQL)
  196. * @returns
  197. */
  198. async createUserCollection(
  199. user: AuthUser,
  200. title: string,
  201. parentUserCollectionID: string | null,
  202. type: ReqType,
  203. ) {
  204. const isTitleValid = isValidLength(title, this.TITLE_LENGTH);
  205. if (!isTitleValid) return E.left(USER_COLL_SHORT_TITLE);
  206. // If creating a child collection
  207. if (parentUserCollectionID !== null) {
  208. const parentCollection = await this.getUserCollection(
  209. parentUserCollectionID,
  210. );
  211. if (E.isLeft(parentCollection)) return E.left(parentCollection.left);
  212. // Check to see if parentUserCollectionID belongs to this User
  213. if (parentCollection.right.userUid !== user.uid)
  214. return E.left(USER_NOT_OWNER);
  215. // Check to see if parent collection is of the same type of new collection being created
  216. if (parentCollection.right.type !== type)
  217. return E.left(USER_COLL_NOT_SAME_TYPE);
  218. }
  219. const isParent = parentUserCollectionID
  220. ? {
  221. connect: {
  222. id: parentUserCollectionID,
  223. },
  224. }
  225. : undefined;
  226. const userCollection = await this.prisma.userCollection.create({
  227. data: {
  228. title: title,
  229. type: type,
  230. user: {
  231. connect: {
  232. uid: user.uid,
  233. },
  234. },
  235. parent: isParent,
  236. orderIndex: !parentUserCollectionID
  237. ? (await this.getRootCollectionsCount(user.uid)) + 1
  238. : (await this.getChildCollectionsCount(parentUserCollectionID)) + 1,
  239. },
  240. });
  241. await this.pubsub.publish(`user_coll/${user.uid}/created`, userCollection);
  242. return E.right(userCollection);
  243. }
  244. /**
  245. *
  246. * @param user The User Object
  247. * @param cursor collectionID for pagination
  248. * @param take Number of items we want returned
  249. * @param type Type of UserCollection
  250. * @returns A list of root UserCollections
  251. */
  252. async getUserRootCollections(
  253. user: AuthUser,
  254. cursor: string | null,
  255. take: number,
  256. type: ReqType,
  257. ) {
  258. return this.prisma.userCollection.findMany({
  259. where: {
  260. userUid: user.uid,
  261. parentID: null,
  262. type: type,
  263. },
  264. orderBy: {
  265. orderIndex: 'asc',
  266. },
  267. take: take, // default: 10
  268. skip: cursor ? 1 : 0,
  269. cursor: cursor ? { id: cursor } : undefined,
  270. });
  271. }
  272. /**
  273. *
  274. * @param user The User Object
  275. * @param userCollectionID The User UID
  276. * @param cursor collectionID for pagination
  277. * @param take Number of items we want returned
  278. * @param type Type of UserCollection
  279. * @returns A list of child UserCollections
  280. */
  281. async getUserChildCollections(
  282. user: AuthUser,
  283. userCollectionID: string,
  284. cursor: string | null,
  285. take: number,
  286. type: ReqType,
  287. ) {
  288. return this.prisma.userCollection.findMany({
  289. where: {
  290. userUid: user.uid,
  291. parentID: userCollectionID,
  292. type: type,
  293. },
  294. take: take, // default: 10
  295. skip: cursor ? 1 : 0,
  296. cursor: cursor ? { id: cursor } : undefined,
  297. });
  298. }
  299. /**
  300. * Update the title of a UserCollection
  301. *
  302. * @param newTitle The new title of collection
  303. * @param userCollectionID The Collection Id
  304. * @param userID The User UID
  305. * @returns An Either of the updated UserCollection
  306. */
  307. async renameUserCollection(
  308. newTitle: string,
  309. userCollectionID: string,
  310. userID: string,
  311. ) {
  312. const isTitleValid = isValidLength(newTitle, this.TITLE_LENGTH);
  313. if (!isTitleValid) return E.left(USER_COLL_SHORT_TITLE);
  314. // Check to see is the collection belongs to the user
  315. const isOwner = await this.isOwnerCheck(userCollectionID, userID);
  316. if (O.isNone(isOwner)) return E.left(USER_NOT_OWNER);
  317. try {
  318. const updatedUserCollection = await this.prisma.userCollection.update({
  319. where: {
  320. id: userCollectionID,
  321. },
  322. data: {
  323. title: newTitle,
  324. },
  325. });
  326. this.pubsub.publish(
  327. `user_coll/${updatedUserCollection.userUid}/updated`,
  328. updatedUserCollection,
  329. );
  330. return E.right(updatedUserCollection);
  331. } catch (error) {
  332. return E.left(USER_COLL_NOT_FOUND);
  333. }
  334. }
  335. /**
  336. * Delete a UserCollection from the DB
  337. *
  338. * @param collectionID The Collection Id
  339. * @returns The deleted UserCollection
  340. */
  341. private async removeUserCollection(collectionID: string) {
  342. try {
  343. const deletedUserCollection = await this.prisma.userCollection.delete({
  344. where: {
  345. id: collectionID,
  346. },
  347. });
  348. return E.right(deletedUserCollection);
  349. } catch (error) {
  350. return E.left(USER_COLL_NOT_FOUND);
  351. }
  352. }
  353. /**
  354. * Delete child collection and requests of a UserCollection
  355. *
  356. * @param collectionID The Collection Id
  357. * @returns A Boolean of deletion status
  358. */
  359. private async deleteCollectionData(collection: UserCollection) {
  360. // Get all child collections in collectionID
  361. const childCollectionList = await this.prisma.userCollection.findMany({
  362. where: {
  363. parentID: collection.id,
  364. },
  365. });
  366. // Delete child collections
  367. await Promise.all(
  368. childCollectionList.map((coll) =>
  369. this.deleteUserCollection(coll.id, coll.userUid),
  370. ),
  371. );
  372. // Delete all requests in collectionID
  373. await this.prisma.userRequest.deleteMany({
  374. where: {
  375. collectionID: collection.id,
  376. },
  377. });
  378. // Update orderIndexes in userCollection table for user
  379. await this.updateOrderIndex(
  380. collection.parentID,
  381. { gt: collection.orderIndex },
  382. { decrement: 1 },
  383. );
  384. // Delete collection from UserCollection table
  385. const deletedUserCollection = await this.removeUserCollection(
  386. collection.id,
  387. );
  388. if (E.isLeft(deletedUserCollection))
  389. return E.left(deletedUserCollection.left);
  390. this.pubsub.publish(
  391. `user_coll/${deletedUserCollection.right.userUid}/deleted`,
  392. {
  393. id: deletedUserCollection.right.id,
  394. type: ReqType[deletedUserCollection.right.type],
  395. },
  396. );
  397. return E.right(true);
  398. }
  399. /**
  400. * Delete a UserCollection
  401. *
  402. * @param collectionID The Collection Id
  403. * @param userID The User UID
  404. * @returns An Either of Boolean of deletion status
  405. */
  406. async deleteUserCollection(collectionID: string, userID: string) {
  407. // Get collection details of collectionID
  408. const collection = await this.getUserCollection(collectionID);
  409. if (E.isLeft(collection)) return E.left(USER_COLL_NOT_FOUND);
  410. // Check to see is the collection belongs to the user
  411. if (collection.right.userUid !== userID) return E.left(USER_NOT_OWNER);
  412. // Delete all child collections and requests in the collection
  413. const collectionData = await this.deleteCollectionData(collection.right);
  414. if (E.isLeft(collectionData)) return E.left(collectionData.left);
  415. return E.right(true);
  416. }
  417. /**
  418. * Change parentID of UserCollection's
  419. *
  420. * @param collectionID The collection ID
  421. * @param parentCollectionID The new parent's collection ID or change to root collection
  422. * @returns If successful return an Either of true
  423. */
  424. private async changeParent(
  425. collection: UserCollection,
  426. parentCollectionID: string | null,
  427. ) {
  428. try {
  429. let collectionCount: number;
  430. if (!parentCollectionID)
  431. collectionCount = await this.getRootCollectionsCount(
  432. collection.userUid,
  433. );
  434. collectionCount = await this.getChildCollectionsCount(parentCollectionID);
  435. const updatedCollection = await this.prisma.userCollection.update({
  436. where: {
  437. id: collection.id,
  438. },
  439. data: {
  440. // if parentCollectionID == null, collection becomes root collection
  441. // if parentCollectionID != null, collection becomes child collection
  442. parentID: parentCollectionID,
  443. orderIndex: collectionCount + 1,
  444. },
  445. });
  446. return E.right(updatedCollection);
  447. } catch (error) {
  448. return E.left(USER_COLL_NOT_FOUND);
  449. }
  450. }
  451. /**
  452. * Check if collection is parent of destCollection
  453. *
  454. * @param collection The ID of collection being moved
  455. * @param destCollection The ID of collection into which we are moving target collection into
  456. * @returns An Option of boolean, is parent or not
  457. */
  458. private async isParent(
  459. collection: UserCollection,
  460. destCollection: UserCollection,
  461. ): Promise<O.Option<boolean>> {
  462. // Check if collection and destCollection are same
  463. if (collection === destCollection) {
  464. return O.none;
  465. }
  466. if (destCollection.parentID !== null) {
  467. // Check if ID of collection is same as parent of destCollection
  468. if (destCollection.parentID === collection.id) {
  469. return O.none;
  470. }
  471. // Get collection details of collection one step above in the tree i.e the parent collection
  472. const parentCollection = await this.getUserCollection(
  473. destCollection.parentID,
  474. );
  475. if (E.isLeft(parentCollection)) {
  476. return O.none;
  477. }
  478. // Call isParent again now with parent collection
  479. return await this.isParent(collection, parentCollection.right);
  480. } else {
  481. return O.some(true);
  482. }
  483. }
  484. /**
  485. * Update the OrderIndex of all collections in given parentID
  486. *
  487. * @param parentID The Parent collectionID
  488. * @param orderIndexCondition Condition to decide what collections will be updated
  489. * @param dataCondition Increment/Decrement OrderIndex condition
  490. * @returns A Collection with updated OrderIndexes
  491. */
  492. private async updateOrderIndex(
  493. parentID: string,
  494. orderIndexCondition: Prisma.IntFilter,
  495. dataCondition: Prisma.IntFieldUpdateOperationsInput,
  496. ) {
  497. const updatedUserCollection = await this.prisma.userCollection.updateMany({
  498. where: {
  499. parentID: parentID,
  500. orderIndex: orderIndexCondition,
  501. },
  502. data: { orderIndex: dataCondition },
  503. });
  504. return updatedUserCollection;
  505. }
  506. /**
  507. * Move UserCollection into root or another collection
  508. *
  509. * @param userCollectionID The ID of collection being moved
  510. * @param destCollectionID The ID of collection the target collection is being moved into or move target collection to root
  511. * @param userID The User UID
  512. * @returns An Either of the moved UserCollection
  513. */
  514. async moveUserCollection(
  515. userCollectionID: string,
  516. destCollectionID: string | null,
  517. userID: string,
  518. ) {
  519. // Get collection details of collectionID
  520. const collection = await this.getUserCollection(userCollectionID);
  521. if (E.isLeft(collection)) return E.left(USER_COLL_NOT_FOUND);
  522. // Check to see is the collection belongs to the user
  523. if (collection.right.userUid !== userID) return E.left(USER_NOT_OWNER);
  524. // destCollectionID == null i.e move collection to root
  525. if (!destCollectionID) {
  526. if (!collection.right.parentID) {
  527. // collection is a root collection
  528. // Throw error if collection is already a root collection
  529. return E.left(USER_COLL_ALREADY_ROOT);
  530. }
  531. // Move child collection into root and update orderIndexes for root userCollections
  532. await this.updateOrderIndex(
  533. collection.right.parentID,
  534. { gt: collection.right.orderIndex },
  535. { decrement: 1 },
  536. );
  537. // Change parent from child to root i.e child collection becomes a root collection
  538. const updatedCollection = await this.changeParent(collection.right, null);
  539. if (E.isLeft(updatedCollection)) return E.left(updatedCollection.left);
  540. this.pubsub.publish(
  541. `user_coll/${collection.right.userUid}/moved`,
  542. updatedCollection.right,
  543. );
  544. return E.right(updatedCollection.right);
  545. }
  546. // destCollectionID != null i.e move into another collection
  547. if (userCollectionID === destCollectionID) {
  548. // Throw error if collectionID and destCollectionID are the same
  549. return E.left(USER_COLL_DEST_SAME);
  550. }
  551. // Get collection details of destCollectionID
  552. const destCollection = await this.getUserCollection(destCollectionID);
  553. if (E.isLeft(destCollection)) return E.left(USER_COLL_NOT_FOUND);
  554. // Check if collection and destCollection belong to the same collection type
  555. if (collection.right.type !== destCollection.right.type) {
  556. return E.left(USER_COLL_NOT_SAME_TYPE);
  557. }
  558. // Check if collection and destCollection belong to the same user account
  559. if (collection.right.userUid !== destCollection.right.userUid) {
  560. return E.left(USER_COLL_NOT_SAME_USER);
  561. }
  562. // Check if collection is present on the parent tree for destCollection
  563. const checkIfParent = await this.isParent(
  564. collection.right,
  565. destCollection.right,
  566. );
  567. if (O.isNone(checkIfParent)) {
  568. return E.left(USER_COLL_IS_PARENT_COLL);
  569. }
  570. // Move root/child collection into another child collection and update orderIndexes of the previous parent
  571. await this.updateOrderIndex(
  572. collection.right.parentID,
  573. { gt: collection.right.orderIndex },
  574. { decrement: 1 },
  575. );
  576. // Change parent from null to teamCollection i.e collection becomes a child collection
  577. const updatedCollection = await this.changeParent(
  578. collection.right,
  579. destCollection.right.id,
  580. );
  581. if (E.isLeft(updatedCollection)) return E.left(updatedCollection.left);
  582. this.pubsub.publish(
  583. `user_coll/${collection.right.userUid}/moved`,
  584. updatedCollection.right,
  585. );
  586. return E.right(updatedCollection.right);
  587. }
  588. /**
  589. * Find the number of child collections present in collectionID
  590. *
  591. * @param collectionID The Collection ID
  592. * @returns Number of collections
  593. */
  594. getCollectionCount(collectionID: string): Promise<number> {
  595. return this.prisma.userCollection.count({
  596. where: { parentID: collectionID },
  597. });
  598. }
  599. /**
  600. * Update order of root or child collectionID's
  601. *
  602. * @param collectionID The ID of collection being re-ordered
  603. * @param nextCollectionID The ID of collection that is after the moved collection in its new position
  604. * @param userID The User UID
  605. * @returns If successful return an Either of true
  606. */
  607. async updateUserCollectionOrder(
  608. collectionID: string,
  609. nextCollectionID: string | null,
  610. userID: string,
  611. ) {
  612. // Throw error if collectionID and nextCollectionID are the same
  613. if (collectionID === nextCollectionID)
  614. return E.left(USER_COLL_SAME_NEXT_COLL);
  615. // Get collection details of collectionID
  616. const collection = await this.getUserCollection(collectionID);
  617. if (E.isLeft(collection)) return E.left(USER_COLL_NOT_FOUND);
  618. // Check to see is the collection belongs to the user
  619. if (collection.right.userUid !== userID) return E.left(USER_NOT_OWNER);
  620. if (!nextCollectionID) {
  621. // nextCollectionID == null i.e move collection to the end of the list
  622. try {
  623. await this.prisma.$transaction(async (tx) => {
  624. // Step 1: Decrement orderIndex of all items that come after collection.orderIndex till end of list of items
  625. await tx.userCollection.updateMany({
  626. where: {
  627. parentID: collection.right.parentID,
  628. orderIndex: {
  629. gte: collection.right.orderIndex + 1,
  630. },
  631. },
  632. data: {
  633. orderIndex: { decrement: 1 },
  634. },
  635. });
  636. // Step 2: Update orderIndex of collection to length of list
  637. const updatedUserCollection = await tx.userCollection.update({
  638. where: { id: collection.right.id },
  639. data: {
  640. orderIndex: await this.getCollectionCount(
  641. collection.right.parentID,
  642. ),
  643. },
  644. });
  645. });
  646. this.pubsub.publish(
  647. `user_coll/${collection.right.userUid}/order_updated`,
  648. {
  649. userCollection: this.cast(collection.right),
  650. nextUserCollection: null,
  651. },
  652. );
  653. return E.right(true);
  654. } catch (error) {
  655. return E.left(USER_COLL_REORDERING_FAILED);
  656. }
  657. }
  658. // nextCollectionID != null i.e move to a certain position
  659. // Get collection details of nextCollectionID
  660. const subsequentCollection = await this.getUserCollection(nextCollectionID);
  661. if (E.isLeft(subsequentCollection)) return E.left(USER_COLL_NOT_FOUND);
  662. if (collection.right.userUid !== subsequentCollection.right.userUid)
  663. return E.left(USER_COLL_NOT_SAME_USER);
  664. // Check if collection and subsequentCollection belong to the same collection type
  665. if (collection.right.type !== subsequentCollection.right.type) {
  666. return E.left(USER_COLL_NOT_SAME_TYPE);
  667. }
  668. try {
  669. await this.prisma.$transaction(async (tx) => {
  670. // Step 1: Determine if we are moving collection up or down the list
  671. const isMovingUp =
  672. subsequentCollection.right.orderIndex < collection.right.orderIndex;
  673. // Step 2: Update OrderIndex of items in list depending on moving up or down
  674. const updateFrom = isMovingUp
  675. ? subsequentCollection.right.orderIndex
  676. : collection.right.orderIndex + 1;
  677. const updateTo = isMovingUp
  678. ? collection.right.orderIndex - 1
  679. : subsequentCollection.right.orderIndex - 1;
  680. await tx.userCollection.updateMany({
  681. where: {
  682. parentID: collection.right.parentID,
  683. orderIndex: { gte: updateFrom, lte: updateTo },
  684. },
  685. data: {
  686. orderIndex: isMovingUp ? { increment: 1 } : { decrement: 1 },
  687. },
  688. });
  689. // Step 3: Update OrderIndex of collection
  690. const updatedUserCollection = await tx.userCollection.update({
  691. where: { id: collection.right.id },
  692. data: {
  693. orderIndex: isMovingUp
  694. ? subsequentCollection.right.orderIndex
  695. : subsequentCollection.right.orderIndex - 1,
  696. },
  697. });
  698. });
  699. this.pubsub.publish(
  700. `user_coll/${collection.right.userUid}/order_updated`,
  701. {
  702. userCollection: this.cast(collection.right),
  703. nextUserCollection: this.cast(subsequentCollection.right),
  704. },
  705. );
  706. return E.right(true);
  707. } catch (error) {
  708. return E.left(USER_COLL_REORDERING_FAILED);
  709. }
  710. }
  711. /**
  712. * Generate a JSON containing all the contents of a collection
  713. *
  714. * @param userUID The User UID
  715. * @param collectionID The Collection ID
  716. * @returns A JSON string containing all the contents of a collection
  717. */
  718. private async exportUserCollectionToJSONObject(
  719. userUID: string,
  720. collectionID: string,
  721. ): Promise<E.Left<string> | E.Right<CollectionFolder>> {
  722. // Get Collection details
  723. const collection = await this.getUserCollection(collectionID);
  724. if (E.isLeft(collection)) return E.left(collection.left);
  725. // Get all child collections whose parentID === collectionID
  726. const childCollectionList = await this.prisma.userCollection.findMany({
  727. where: {
  728. parentID: collectionID,
  729. userUid: userUID,
  730. },
  731. orderBy: {
  732. orderIndex: 'asc',
  733. },
  734. });
  735. // Create a list of child collection and request data ready for export
  736. const childrenCollectionObjects: CollectionFolder[] = [];
  737. for (const coll of childCollectionList) {
  738. const result = await this.exportUserCollectionToJSONObject(
  739. userUID,
  740. coll.id,
  741. );
  742. if (E.isLeft(result)) return E.left(result.left);
  743. childrenCollectionObjects.push(result.right);
  744. }
  745. // Fetch all child requests that belong to collectionID
  746. const requests = await this.prisma.userRequest.findMany({
  747. where: {
  748. userUid: userUID,
  749. collectionID,
  750. },
  751. orderBy: {
  752. orderIndex: 'asc',
  753. },
  754. });
  755. const result: CollectionFolder = {
  756. id: collection.right.id,
  757. name: collection.right.title,
  758. folders: childrenCollectionObjects,
  759. requests: requests.map((x) => {
  760. return {
  761. id: x.id,
  762. name: x.title,
  763. ...(x.request as Record<string, unknown>), // type casting x.request of type Prisma.JSONValue to an object to enable spread
  764. };
  765. }),
  766. };
  767. return E.right(result);
  768. }
  769. /**
  770. * Generate a JSON containing all the contents of collections and requests of a team
  771. *
  772. * @param userUID The User UID
  773. * @returns A JSON string containing all the contents of collections and requests of a team
  774. */
  775. async exportUserCollectionsToJSON(
  776. userUID: string,
  777. collectionID: string | null,
  778. reqType: ReqType,
  779. ) {
  780. // Get all child collections details
  781. const childCollectionList = await this.prisma.userCollection.findMany({
  782. where: {
  783. userUid: userUID,
  784. parentID: collectionID,
  785. type: reqType,
  786. },
  787. orderBy: {
  788. orderIndex: 'asc',
  789. },
  790. });
  791. // Create a list of child collection and request data ready for export
  792. const collectionListObjects: CollectionFolder[] = [];
  793. for (const coll of childCollectionList) {
  794. const result = await this.exportUserCollectionToJSONObject(
  795. userUID,
  796. coll.id,
  797. );
  798. if (E.isLeft(result)) return E.left(result.left);
  799. collectionListObjects.push(result.right);
  800. }
  801. // If collectionID is not null, return JSONified data for specific collection
  802. if (collectionID) {
  803. // Get Details of collection
  804. const parentCollection = await this.getUserCollection(collectionID);
  805. if (E.isLeft(parentCollection)) return E.left(parentCollection.left);
  806. if (parentCollection.right.type !== reqType)
  807. return E.left(USER_COLL_NOT_SAME_TYPE);
  808. // Fetch all child requests that belong to collectionID
  809. const requests = await this.prisma.userRequest.findMany({
  810. where: {
  811. userUid: userUID,
  812. collectionID: parentCollection.right.id,
  813. },
  814. orderBy: {
  815. orderIndex: 'asc',
  816. },
  817. });
  818. return E.right(<UserCollectionExportJSONData>{
  819. exportedCollection: JSON.stringify({
  820. id: parentCollection.right.id,
  821. name: parentCollection.right.title,
  822. folders: collectionListObjects,
  823. requests: requests.map((x) => {
  824. return {
  825. id: x.id,
  826. name: x.title,
  827. ...(x.request as Record<string, unknown>), // type casting x.request of type Prisma.JSONValue to an object to enable spread
  828. };
  829. }),
  830. }),
  831. collectionType: parentCollection.right.type,
  832. });
  833. }
  834. return E.right(<UserCollectionExportJSONData>{
  835. exportedCollection: JSON.stringify(collectionListObjects),
  836. collectionType: reqType,
  837. });
  838. }
  839. /**
  840. * Generate a Prisma query object representation of a collection and its child collections and requests
  841. *
  842. * @param folder CollectionFolder from client
  843. * @param userID The User ID
  844. * @param orderIndex Initial OrderIndex of
  845. * @param reqType The Type of Collection
  846. * @returns A Prisma query object to create a collection, its child collections and requests
  847. */
  848. private generatePrismaQueryObj(
  849. folder: CollectionFolder,
  850. userID: string,
  851. orderIndex: number,
  852. reqType: DBReqType,
  853. ): Prisma.UserCollectionCreateInput {
  854. return {
  855. title: folder.name,
  856. user: {
  857. connect: {
  858. uid: userID,
  859. },
  860. },
  861. requests: {
  862. create: folder.requests.map((r, index) => ({
  863. title: r.name,
  864. user: {
  865. connect: {
  866. uid: userID,
  867. },
  868. },
  869. type: reqType,
  870. request: r,
  871. orderIndex: index + 1,
  872. })),
  873. },
  874. orderIndex: orderIndex,
  875. type: reqType,
  876. children: {
  877. create: folder.folders.map((f, index) =>
  878. this.generatePrismaQueryObj(f, userID, index + 1, reqType),
  879. ),
  880. },
  881. };
  882. }
  883. /**
  884. * Create new UserCollections and UserRequests from JSON string
  885. *
  886. * @param jsonString The JSON string of the content
  887. * @param userID The User ID
  888. * @param destCollectionID The Collection ID
  889. * @param reqType The Type of Collection
  890. * @returns An Either of a Boolean if the creation operation was successful
  891. */
  892. async importCollectionsFromJSON(
  893. jsonString: string,
  894. userID: string,
  895. destCollectionID: string | null,
  896. reqType: DBReqType,
  897. ) {
  898. // Check to see if jsonString is valid
  899. const collectionsList = stringToJson<CollectionFolder[]>(jsonString);
  900. if (E.isLeft(collectionsList)) return E.left(USER_COLL_INVALID_JSON);
  901. // Check to see if parsed jsonString is an array
  902. if (!Array.isArray(collectionsList.right))
  903. return E.left(USER_COLL_INVALID_JSON);
  904. // Check to see if destCollectionID belongs to this User
  905. if (destCollectionID) {
  906. const parentCollection = await this.getUserCollection(destCollectionID);
  907. if (E.isLeft(parentCollection)) return E.left(parentCollection.left);
  908. // Check to see if parentUserCollectionID belongs to this User
  909. if (parentCollection.right.userUid !== userID)
  910. return E.left(USER_NOT_OWNER);
  911. // Check to see if parent collection is of the same type of new collection being created
  912. if (parentCollection.right.type !== reqType)
  913. return E.left(USER_COLL_NOT_SAME_TYPE);
  914. }
  915. // Get number of root or child collections for destCollectionID(if destcollectionID != null) or destTeamID(if destcollectionID == null)
  916. const count = !destCollectionID
  917. ? await this.getRootCollectionsCount(userID)
  918. : await this.getChildCollectionsCount(destCollectionID);
  919. // Generate Prisma Query Object for all child collections in collectionsList
  920. const queryList = collectionsList.right.map((x) =>
  921. this.generatePrismaQueryObj(x, userID, count + 1, reqType),
  922. );
  923. const parent = destCollectionID
  924. ? {
  925. connect: {
  926. id: destCollectionID,
  927. },
  928. }
  929. : undefined;
  930. const userCollections = await this.prisma.$transaction(
  931. queryList.map((x) =>
  932. this.prisma.userCollection.create({
  933. data: {
  934. ...x,
  935. parent,
  936. },
  937. }),
  938. ),
  939. );
  940. userCollections.forEach((x) =>
  941. this.pubsub.publish(`user_coll/${userID}/created`, x),
  942. );
  943. return E.right(true);
  944. }
  945. }