musora-content-services 2.3.17 → 2.3.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -564,313 +564,6 @@ export async function postChallengesHideCompletedBanner(contentId) {
564
564
  return await fetchHandler(url, 'post')
565
565
  }
566
566
 
567
- /**
568
- * Duplicates an existing playlist by sending a POST request to the API.
569
- *
570
- * This function calls the `/playlists/duplicate` endpoint, where the server replicates the specified playlist,
571
- * including its items. Optionally, new `name`, `description`, `category`, or `thumbnail_url` parameters can be provided
572
- * to customize the duplicated playlist. If a new name is not provided, the server appends " (Duplicate)" to the original name.
573
- *
574
- * @param {string|number} playlistId - The unique identifier of the playlist to be duplicated.
575
- * @param {Object} [playlistData] - Optional data to customize the duplicated playlist.
576
- * @param {string} [playlistData.name] - New name for the duplicated playlist (default is original name + " (Duplicate)").
577
- * @param {string} [playlistData.description] - New description for the duplicated playlist (defaults to original description).
578
- * @param {string} [playlistData.category] - New category for the duplicated playlist (defaults to original category).
579
- * @param {string} [playlistData.thumbnail_url] - New URL for the duplicated playlist thumbnail (defaults to original thumbnail).
580
- *
581
- * @returns {Promise<Object>} - A promise that resolves to the duplicated playlist data, or rejects with an error if the duplication fails.
582
- *
583
- * The duplicated playlist contains:
584
- * - `name` (string): Name of the new playlist.
585
- * - `description` (string|null): Description of the duplicated playlist.
586
- * - `category` (string|null): Category of the duplicated playlist.
587
- * - `thumbnail_url` (string|null): URL of the playlist thumbnail.
588
- * - `items` (Array): A list of items (e.g., songs, tracks) copied from the original playlist.
589
- *
590
- * @example
591
- * duplicatePlaylist(12345, { name: "My New Playlist" })
592
- * .then(duplicatedPlaylist => console.log(duplicatedPlaylist))
593
- * .catch(error => console.error('Error duplicating playlist:', error));
594
- */
595
- export async function duplicatePlaylist(playlistId, playlistData) {
596
- let url = `/playlists/duplicate/${playlistId}`
597
- return await fetchHandler(url, 'post', null, playlistData)
598
- }
599
-
600
- /**
601
- * Deletes a user’s playlist along with all associated items by sending a DELETE request to the API.
602
- *
603
- * This function calls the `/playlists/playlist` endpoint, where the server verifies the user’s ownership of the specified playlist.
604
- * If the user is authorized, it deletes both the playlist and its associated items.
605
- *
606
- * @param {string|number} playlistId - The unique identifier of the playlist to be deleted.
607
- *
608
- * @returns {Promise<Object>} - A promise that resolves to an object containing:
609
- * - `success` (boolean): Indicates if the deletion was successful (`true` for success).
610
- * - `message` (string): Success confirmation message (e.g., "Playlist and associated items deleted successfully").
611
- *
612
- * If the user is unauthorized or the playlist does not exist, the promise rejects with an error.
613
- *
614
- * @example
615
- * deletePlaylist(12345)
616
- * .then(response => {
617
- * if (response.success) {
618
- * console.log(response.message);
619
- * }
620
- * })
621
- * .catch(error => console.error('Error deleting playlist:', error));
622
- */
623
- export async function deletePlaylist(playlistId) {
624
- let url = `/playlists/playlist/${playlistId}`
625
- return await fetchHandler(url, 'delete')
626
- }
627
-
628
- /**
629
- * Updates a user’s playlist by sending a PUT request with updated data to the API.
630
- *
631
- * This function calls the `/playlists/playlist/{playlistId}` endpoint, where the server validates the incoming data
632
- * and verifies that the authenticated user is the playlist owner. If authorized, it updates the playlist details with the provided data.
633
- *
634
- * @param {string|number} playlistId - The unique identifier of the playlist to be updated.
635
- * @param {Object} updatedData - An object containing the playlist data to update. The possible fields include:
636
- * - `name` (string): The new name of the playlist (max 255 characters).
637
- * - `description` (string): A new description for the playlist (max 1000 characters).
638
- * - `category` (string): The updated category of the playlist (max 255 characters).
639
- * - `private` (boolean): Whether the playlist is private.
640
- * - `thumbnail_url` (string): The URL of the playlist thumbnail.
641
- *
642
- * @returns {Promise<Object>} - A promise that resolves to an object containing:
643
- * - `success` (boolean): Indicates if the update was successful (`true` for success).
644
- * - `message` (string): Success confirmation message if the update is successful.
645
- * - Other fields containing the updated playlist data.
646
- *
647
- * If the user is unauthorized or the data validation fails, the promise rejects with an error.
648
- *
649
- * @example
650
- * updatePlaylist(12345, { name: "My New Playlist Name", description: "Updated description" })
651
- * .then(response => {
652
- * if (response.success) {
653
- * console.log(response.message);
654
- * }
655
- * })
656
- * .catch(error => console.error('Error updating playlist:', error));
657
- */
658
- export async function updatePlaylist(playlistId, updatedData) {
659
- const url = `/playlists/playlist/${playlistId}`
660
- return await fetchHandler(url, 'PUT', null, updatedData)
661
- }
662
-
663
- /**
664
- * Sends a request to "like" a playlist on behalf of the authenticated user.
665
- *
666
- * This function calls the `/playlists/playlist/like` endpoint, where the server validates the `playlist_id` and checks
667
- * if the authenticated user has already liked the playlist. If not, it creates a new "like" entry associated with the playlist.
668
- *
669
- * @param {string|number} playlistId - The unique identifier of the playlist to be liked.
670
- *
671
- * @returns {Promise<Object>} - A promise that resolves with the response from the API. The response contains:
672
- * - `success` (boolean): Indicates if the like action was successful (`true` for success).
673
- * - `message` (string): A success message if the playlist is liked successfully, or a notification if it was already liked.
674
- * - `like` (Object|null): Details of the created "like" entry if the playlist is newly liked, or null if it was already liked.
675
- *
676
- * The `like` object in the response includes:
677
- * - `playlist_id`: The ID of the liked playlist.
678
- * - `user_id`: The ID of the user who liked the playlist.
679
- * - `brand`: The brand associated with the like.
680
- * - `created_at`: Timestamp of when the like was created.
681
- *
682
- * @example
683
- * likePlaylist(12345)
684
- * .then(response => {
685
- * if (response.success) {
686
- * console.log(response.message);
687
- * }
688
- * })
689
- * .catch(error => console.error('Error liking playlist:', error));
690
- */
691
- export async function likePlaylist(playlistId) {
692
- const url = `/playlists/like`
693
- const payload = { playlist_id: playlistId }
694
- return await fetchHandler(url, 'PUT', null, payload)
695
- }
696
-
697
- /**
698
- * Removes a "like" from a playlist for the authenticated user.
699
- *
700
- * This function sends a DELETE request to the `/playlists/like` endpoint, where the server validates the `playlist_id`
701
- * and checks if a like by the authenticated user already exists for the specified playlist. If so, it deletes the like.
702
- *
703
- * @param {string|number} playlistId - The unique identifier of the playlist whose like is to be removed.
704
- *
705
- * @returns {Promise<Object>} - A promise that resolves with the response from the API. The response contains:
706
- * - `success` (boolean): Indicates if the removal was successful (`true` for success).
707
- * - `message` (string): A success message if the playlist like is removed successfully or a notification if the playlist was not previously liked.
708
- *
709
- * @example
710
- * deletePlaylistLike(12345)
711
- * .then(response => {
712
- * if (response.success) {
713
- * console.log(response.message);
714
- * }
715
- * })
716
- * .catch(error => console.error('Error removing playlist like:', error));
717
- */
718
- export async function deletePlaylistLike(playlistId) {
719
- const url = `/playlists/like`
720
- const payload = { playlist_id: playlistId }
721
- return await fetchHandler(url, 'DELETE', null, payload)
722
- }
723
-
724
- /**
725
- * Retrieves details of a specific playlist by its ID.
726
- *
727
- * This function sends a GET request to the `/playlists/playlist` endpoint with a specified playlist ID.
728
- * The server validates the user's access to the playlist and returns playlist details if the user is authorized.
729
- *
730
- * @param {string|number} playlistId - The unique identifier of the playlist to retrieve.
731
- *
732
- * @returns {Promise<Object>} - A promise that resolves to the response from the API, containing:
733
- * - `data` (Object): The playlist details, or an error message if access is denied or the playlist is not found.
734
- *
735
- * @example
736
- * fetchPlaylist(12345)
737
- * .then(response => console.log(response.data))
738
- * .catch(error => console.error('Error fetching playlist:', error));
739
- */
740
- export async function fetchPlaylist(playlistId) {
741
- const url = `/playlists/playlist/${playlistId}`
742
- return await fetchHandler(url, 'GET')
743
- }
744
-
745
- /**
746
- * Retrieves items within a specified playlist by playlist ID.
747
- *
748
- * This function sends a GET request to the `/playlists/playlist-lessons` endpoint to fetch items in the given playlist.
749
- * The server combines data from the playlist and additional metadata from Sanity to enhance item details.
750
- *
751
- * @param {string|number} playlistId - The unique identifier of the playlist whose items are to be fetched.
752
- *
753
- * @returns {Promise<Array<Object>>} - A promise that resolves to an array of playlist items
754
- *
755
- * @example
756
- * fetchPlaylistItems(12345)
757
- * .then(items => console.log(items))
758
- * .catch(error => console.error('Error fetching playlist items:', error));
759
- */
760
- export async function fetchPlaylistItems(playlistId, { sort } = {}) {
761
- const sortString = sort ? `&sort=${sort}` : ''
762
- const url = `/playlists/playlist-lessons?playlist_id=${playlistId}${sortString}`
763
- return await fetchHandler(url, 'GET')
764
- }
765
-
766
- /**
767
- * Updates a playlist item with the provided data.
768
- *
769
- * @param {Object} updatedData - The data to update the playlist item with.
770
- * @param {number} updatedData.user_playlist_item_id - The ID of the playlist item to update.
771
- * @param {number} [updatedData.start_second] - (Optional) The start time in seconds for the item.
772
- * @param {number} [updatedData.end_second] - (Optional) The end time in seconds for the item.
773
- * @param {string} [updatedData.playlist_item_name] - (Optional) The new name for the playlist item.
774
- * @param {number} [updatedData.position] - (Optional) The new position for the playlist item within the playlist.
775
- * @returns {Promise<Object|null>} - A promise that resolves to an object containing:
776
- * - `success` (boolean): Indicates if the update was successful (`true` for success).
777
- * - `data` (Object): The updated playlist item data.
778
- *
779
- * Resolves to `null` if the request fails.
780
- * @throws {Error} - Throws an error if the request fails.
781
- *
782
- * @example
783
- * const updatedData = {
784
- * user_playlist_item_id: 123,
785
- * start_second: 30,
786
- * end_second: 120,
787
- * playlist_item_name: "Updated Playlist Item Name",
788
- * position: 2
789
- * };
790
- *
791
- * updatePlaylistItem(updatedData)
792
- * .then(response => {
793
- * if (response.success) {
794
- * console.log("Playlist item updated successfully:", response.data);
795
- * }
796
- * })
797
- * .catch(error => {
798
- * console.error("Error updating playlist item:", error);
799
- * });
800
- */
801
- export async function updatePlaylistItem(updatedData) {
802
- const url = `/playlists/item`
803
- return await fetchHandler(url, 'POST', null, updatedData)
804
- }
805
-
806
- /**
807
- * Deletes a playlist item and repositions other items in the playlist if necessary.
808
- *
809
- * @param {Object} payload - The data required to delete the playlist item.
810
- * @param {number} payload.user_playlist_item_id - The ID of the playlist item to delete.
811
- * @returns {Promise<Object|null>} - A promise that resolves to an object containing:
812
- * - `success` (boolean): Indicates if the deletion was successful (`true` for success).
813
- * - `message` (string): A success message if the item is deleted successfully.
814
- * - `error` (string): An error message if the deletion fails.
815
- *
816
- * Resolves to `null` if the request fails.
817
- * @throws {Error} - Throws an error if the request fails.
818
- *
819
- * @example
820
- * const payload = {
821
- * user_playlist_item_id: 123
822
- * };
823
- *
824
- * deletePlaylistItem(payload)
825
- * .then(response => {
826
- * if (response.success) {
827
- * console.log("Playlist item deleted successfully:", response.message);
828
- * } else {
829
- * console.error("Error:", response.error);
830
- * }
831
- * })
832
- * .catch(error => {
833
- * console.error("Error deleting playlist item:", error);
834
- * });
835
- */
836
- export async function deletePlaylistItem(payload) {
837
- const url = `/playlists/item`
838
- return await fetchHandler(url, 'DELETE', null, payload)
839
- }
840
-
841
- /**
842
- * Fetches detailed data for a specific playlist item, including associated Sanity and Assignment information if available.
843
- *
844
- * @param {Object} payload - The request payload containing necessary parameters.
845
- * @param {number} payload.user_playlist_item_id - The unique ID of the playlist item to fetch.
846
- * @returns {Promise<Object|null>} - A promise that resolves to an object with the fetched playlist item data, including:
847
- * - `success` (boolean): Indicates if the data retrieval was successful (`true` on success).
848
- * - `data` (Object): Contains the detailed playlist item data enriched with Sanity and Assignment details, if available.
849
- *
850
- * Resolves to `null` if the request fails.
851
- * @throws {Error} - Throws an error if the request encounters issues during retrieval.
852
- *
853
- * @example
854
- * const payload = { user_playlist_item_id: 123 };
855
- *
856
- * fetchPlaylistItem(payload)
857
- * .then(response => {
858
- * if (response?.success) {
859
- * console.log("Fetched playlist item data:", response.data);
860
- * } else {
861
- * console.log("Failed to fetch playlist item data.");
862
- * }
863
- * })
864
- * .catch(error => {
865
- * console.error("Error fetching playlist item:", error);
866
- * });
867
- */
868
- export async function fetchPlaylistItem(payload) {
869
- const playlistItemId = payload.user_playlist_item_id
870
- const url = `/playlists/item/${playlistItemId}`
871
- return await fetchHandler(url)
872
- }
873
-
874
567
  export async function postContentComplete(contentId) {
875
568
  let url = `/api/content/v1/user/progress/complete/${contentId}`
876
569
  return postDataHandler(url)
@@ -881,150 +574,6 @@ export async function postContentReset(contentId) {
881
574
  return postDataHandler(url)
882
575
  }
883
576
 
884
- /**
885
- * Retrieves the count of lessons and assignments associated with a specific content ID.
886
- *
887
- * @param {number} contentId - The ID of the content for which to count lessons and assignments.
888
- *
889
- * @returns {Promise<Object|null>} - A promise that resolves to an object containing the counts:
890
- * - `lessons_count` (number): The number of lessons associated with the content.
891
- * - `soundslice_assignments_count` (number): The number of Soundslice assignments associated with the content.
892
- *
893
- * @example
894
- * const contentId = 123;
895
- *
896
- * countAssignmentsAndLessons(contentId)
897
- * .then(response => {
898
- * if (response) {
899
- * console.log("Lessons count:", response.lessons_count);
900
- * console.log("Soundslice assignments count:", response.soundslice_assignments_count);
901
- * } else {
902
- * console.log("Failed to retrieve counts.");
903
- * }
904
- * })
905
- * .catch(error => {
906
- * console.error("Error fetching assignments and lessons count:", error);
907
- * });
908
- */
909
- export async function countAssignmentsAndLessons(contentId) {
910
- const url = `/playlists/count-lessons-and-assignments/${contentId}`
911
- return await fetchHandler(url)
912
- }
913
-
914
- /**
915
- * Pins a playlist to the user's playlist menu.
916
- *
917
- * @param {number} playlistId - The ID of the playlist to pin.
918
- * @returns {Promise<Object>} - A promise that resolves to an object containing:
919
- * - `success` (boolean): Indicates if the pinning operation was successful (`true` for success).
920
- * - `message` (string): A success message if the playlist was pinned successfully.
921
- * - `error` (string): An error message if the pinning operation fails.
922
- *
923
- * Resolves to an error message if the request fails.
924
- * @throws {Error} - Throws an error if the request fails.
925
- *
926
- * @example
927
- * const playlistId = 123;
928
- *
929
- * pinPlaylist(playlistId)
930
- * .then(response => {
931
- * if (response.success) {
932
- * console.log("Playlist pinned successfully:", response.message);
933
- * } else {
934
- * console.error("Error:", response.error);
935
- * }
936
- * })
937
- * .catch(error => {
938
- * console.error("Error pinning playlist:", error);
939
- * });
940
- */
941
- export async function pinPlaylist(playlistId) {
942
- const url = `/playlists/pin/${playlistId}`
943
- return await fetchHandler(url, 'PUT')
944
- }
945
-
946
- /**
947
- * Unpins a playlist
948
- *
949
- * @param {number} playlistId - The ID of the playlist to unpin.
950
- * @returns {Promise<Object>} - A promise that resolves to an object containing:
951
- * - `success` (boolean): Indicates if the unpinning operation was successful (`true` for success).
952
- * - `message` (string): A success message if the playlist was unpinned successfully.
953
- * - `error` (string): An error message if the unpinning operation fails.
954
- *
955
- * Resolves to an error message if the request fails.
956
- * @throws {Error} - Throws an error if the request fails.
957
- *
958
- * @example
959
- * const playlistId = 123;
960
- *
961
- * unpinPlaylist(playlistId)
962
- * .then(response => {
963
- * if (response.success) {
964
- * console.log("Playlist unpinned successfully:", response.message);
965
- * } else {
966
- * console.error("Error:", response.error);
967
- * }
968
- * })
969
- * .catch(error => {
970
- * console.error("Error unpinning playlist:", error);
971
- * });
972
- */
973
- export async function unpinPlaylist(playlistId) {
974
- const url = `/playlists/unpin/${playlistId}`
975
- return await fetchHandler(url, 'PUT')
976
- }
977
-
978
- /**
979
- * Fetches the list of pinned playlists for the authenticated user.
980
- *
981
- * @param {string} brand - The brand associated with the playlists to fetch.
982
- * @returns {Promise<Object>} - A promise that resolves to an object containing:
983
- * - `success` (boolean): Indicates if the fetching operation was successful (`true` for success).
984
- * - `data` (Array): An array of pinned playlists.
985
- * - `error` (string): An error message if the fetching operation fails.
986
- *
987
- * Resolves to an error message if the request fails.
988
- * @throws {Error} - Throws an error if the request fails.
989
- *
990
- * @example
991
- * const brand = "drumeo";
992
- *
993
- * fetchPinnedPlaylists(brand)
994
- * .then(response => {
995
- * if (response.success) {
996
- * console.log("Pinned playlists:", response.data);
997
- * } else {
998
- * console.error("Error:", response.error);
999
- * }
1000
- * })
1001
- * .catch(error => {
1002
- * console.error("Error fetching pinned playlists:", error);
1003
- * });
1004
- */
1005
- export async function fetchPinnedPlaylists(brand) {
1006
- const url = `/playlists/my-pinned-playlists?brand=${brand}`
1007
- return await fetchHandler(url, 'GET')
1008
- }
1009
-
1010
- /**
1011
- * Report playlist endpoint
1012
- *
1013
- * @param playlistId
1014
- * @param issue
1015
- * @returns {Promise<any|null>}
1016
- */
1017
- export async function reportPlaylist(playlistId, { issue } = {}) {
1018
- const issueString = issue ? `?issue=${issue}` : ''
1019
- const url = `/playlists/report/${playlistId}${issueString}`
1020
- return await fetchHandler(url, 'PUT')
1021
- }
1022
-
1023
- export async function playback(playlistId) {
1024
- const url = `/playlists/play/${playlistId}`
1025
- return await fetchHandler(url, 'GET')
1026
- }
1027
-
1028
577
  /**
1029
578
  * Set a user's StudentView Flag
1030
579
  *
@@ -1193,8 +742,11 @@ export async function reportComment(commentId, issue) {
1193
742
  return await postDataHandler(url, data)
1194
743
  }
1195
744
 
1196
- export async function fetchUserPractices(currentVersion) {
1197
- const url = `/api/user/practices/v1/practices`;
745
+ export async function fetchUserPractices({ currentVersion, userId } = {}) {
746
+ const params = new URLSearchParams();
747
+ if (userId) params.append('user_id', userId);
748
+ const query = params.toString() ? `?${params.toString()}` : '';
749
+ const url = `/api/user/practices/v1/practices${query}`;
1198
750
  const response = await fetchDataHandler(url, currentVersion);
1199
751
  const { data, version } = response;
1200
752
  const userPractices = data;
@@ -1236,18 +788,17 @@ export async function logUserPractice(practiceDetails) {
1236
788
  const url = `/api/user/practices/v1/practices`
1237
789
  return await fetchHandler(url, 'POST', null, practiceDetails)
1238
790
  }
1239
- export async function fetchUserPracticeMeta(practiceIds) {
791
+ export async function fetchUserPracticeMeta(practiceIds, userId = null) {
1240
792
  if (practiceIds.length == 0) {
1241
793
  return []
1242
794
  }
1243
- let idsString = ''
1244
- if (practiceIds && practiceIds.length > 0) {
1245
- idsString = '?'
1246
- practiceIds.forEach((id, index) => {
1247
- idsString += `practice_ids[]=${id}${index < practiceIds.length - 1 ? '&' : ''}`
1248
- })
795
+ const params = new URLSearchParams();
796
+ practiceIds.forEach(id => params.append('practice_ids[]', id));
797
+
798
+ if (userId !== null) {
799
+ params.append('user_id', userId);
1249
800
  }
1250
- const url = `/api/user/practices/v1/practices${idsString}`
801
+ const url = `/api/user/practices/v1/practices?${params.toString()}`
1251
802
  return await fetchHandler(url, 'GET', null)
1252
803
  }
1253
804
 
@@ -1274,7 +1274,7 @@ export async function fetchLessonContent(railContentId) {
1274
1274
  chapter_timecode,
1275
1275
  "chapter_thumbnail_url": chapter_thumbnail_url.asset->url
1276
1276
  },
1277
- artist->,
1277
+ 'artist': { 'name': artist->name, 'thumbnail': artist->thumbnail_url.asset->url},
1278
1278
  "instructors":instructor[]->name,
1279
1279
  "instructor": instructor[]->{
1280
1280
  "id":railcontent_id,
@@ -7,6 +7,7 @@ import { DataContext, UserActivityVersionKey } from './dataContext.js'
7
7
  import {fetchByRailContentIds} from "./sanity";
8
8
  import {lessonTypesMapping} from "../contentTypeConfig";
9
9
  import { convertToTimeZone, getMonday, getWeekNumber, isSameDate, isNextDay } from './dateUtils.js';
10
+ import {globalConfig} from "./config";
10
11
 
11
12
  const recentActivity = [
12
13
  { id: 5,title: '3 Easy Classical Songs For Beginners', action: 'Comment', thumbnail: 'https://cdn.sanity.io/images/4032r8py/production/8a7fb4d7473306c5fa51ba2e8867e03d44342b18-1920x1080.jpg', summary: 'Just completed the advanced groove lesson! I’m finally feeling more confident with my fills. Thanks for the clear explanations and practice tips! ', date: '2025-03-25 10:09:48' },
@@ -82,35 +83,51 @@ export async function getUserWeeklyStats() {
82
83
  }
83
84
 
84
85
  /**
85
- * Retrieves user activity statistics for a specified month, including daily and weekly activity data.
86
+ * Retrieves user activity statistics for a specified month and user, including daily and weekly activity data.
87
+ * If no parameters are provided, defaults to the current year, current month, and the logged-in user.
88
+ *
89
+ * @param {Object} [params={}] - Parameters for fetching user statistics.
90
+ * @param {number} [params.year=new Date().getFullYear()] - The year for which to retrieve the statistics.
91
+ * @param {number} [params.month=new Date().getMonth()] - The 0-based month index (0 = January).
92
+ * @param {number} [params.day=1] - The starting day (not used for grid calc, but kept for flexibility).
93
+ * @param {number} [params.userId=globalConfig.sessionConfig.userId] - The user ID for whom to retrieve stats.
94
+ *
95
+ * @returns {Promise<Object>} A promise that resolves to an object containing:
96
+ * - `dailyActiveStats`: Array of daily activity data for the calendar grid.
97
+ * - `weeklyActiveStats`: Array of weekly streak summaries.
98
+ * - `practiceDuration`: Total number of seconds practiced in the month.
99
+ * - `currentDailyStreak`: Count of consecutive active days.
100
+ * - `currentWeeklyStreak`: Count of consecutive active weeks.
101
+ * - `daysPracticed`: Total number of active days in the month.
86
102
  *
87
- * @param {number} [year=new Date().getFullYear()] - The year for which to retrieve the statistics.
88
- * @param {number} [month=new Date().getMonth()] - The month (0-indexed) for which to retrieve the statistics.
89
- * @returns {Promise<Object>} - A promise that resolves to an object containing user activity statistics.
103
+ * @example
104
+ * // Get stats for current user and month
105
+ * getUserMonthlyStats().then(console.log);
90
106
  *
91
107
  * @example
92
- * // Retrieve user activity statistics for the current month
93
- * getUserMonthlyStats()
94
- * .then(stats => console.log(stats))
95
- * .catch(error => console.error(error));
108
+ * // Get stats for March 2024
109
+ * getUserMonthlyStats({ year: 2024, month: 2 }).then(console.log);
96
110
  *
97
111
  * @example
98
- * // Retrieve user activity statistics for March 2024
99
- * getUserMonthlyStats(2024, 2)
100
- * .then(stats => console.log(stats))
101
- * .catch(error => console.error(error));
112
+ * // Get stats for another user
113
+ * getUserMonthlyStats({ userId: 123 }).then(console.log);
102
114
  */
103
- export async function getUserMonthlyStats(year = new Date().getFullYear(), month = new Date().getMonth(), day = 1) {
104
- let data = await userActivityContext.getData()
105
- let practices = data?.[DATA_KEY_PRACTICES] ?? {}
106
- let sortedPracticeDays = Object.keys(practices)
107
- .map(dateStr => {
108
- const [y, m, d] = dateStr.split('-').map(Number);
109
- const newDate = new Date();
110
- newDate.setFullYear(y, m - 1, d);
111
- return newDate;
112
- })
113
- .sort((a, b) => a - b);
115
+ export async function getUserMonthlyStats( params = {}) {
116
+ const now = new Date();
117
+ const {
118
+ year = now.getFullYear(),
119
+ month = now.getMonth(),
120
+ day = 1,
121
+ userId = globalConfig.sessionConfig.userId,
122
+ } = params;
123
+ let practices = {}
124
+ if(userId !== globalConfig.sessionConfig.userId) {
125
+ let data = await fetchUserPractices({userId});
126
+ practices = data?.["data"]?.[DATA_KEY_PRACTICES]?? {}
127
+ }else {
128
+ let data = await userActivityContext.getData()
129
+ practices = data?.[DATA_KEY_PRACTICES] ?? {}
130
+ }
114
131
 
115
132
  // Get the first day of the specified month and the number of days in that month
116
133
  let firstDayOfMonth = new Date(year, month, 1)
@@ -184,10 +201,6 @@ export async function getUserMonthlyStats(year = new Date().getFullYear(), month
184
201
  }
185
202
  }
186
203
 
187
- export async function getUserPractices() {
188
- let data = await userActivityContext.getData()
189
- return data?.[DATA_KEY_PRACTICES] ?? []
190
- }
191
204
  /**
192
205
  * Records user practice data and updates both the remote and local activity context.
193
206
  *
@@ -414,20 +427,34 @@ export async function restorePracticeSession(date) {
414
427
  /**
415
428
  * Retrieves and formats a user's practice sessions for a specific day.
416
429
  *
417
- * @param {string} day - The date for which practice sessions should be retrieved (format: YYYY-MM-DD).
418
- * @returns {Promise<Object>} - A promise that resolves to an object containing the practice sessions and total practice duration.
430
+ * @param {Object} params - Parameters for fetching practice sessions.
431
+ * @param {string} params.day - The date for which practice sessions should be retrieved (format: YYYY-MM-DD).
432
+ * @param {number} [params.userId=globalConfig.sessionConfig.userId] - Optional user ID to retrieve sessions for a specific user. Defaults to the logged-in user.
433
+ * @returns {Promise<Object>} - A promise that resolves to an object containing:
434
+ * - `practices`: An array of formatted practice session data.
435
+ * - `practiceDuration`: Total practice duration (in seconds) for the given day.
436
+ *
437
+ * @example
438
+ * // Get practice sessions for the current user on a specific day
439
+ * getPracticeSessions({ day: "2025-03-31" })
440
+ * .then(response => console.log(response))
441
+ * .catch(error => console.error(error));
419
442
  *
420
443
  * @example
421
- * // Get practice sessions for a specific day
422
- * getPracticeSessions("2025-03-31")
444
+ * // Get practice sessions for another user
445
+ * getPracticeSessions({ day: "2025-03-31", userId: 456 })
423
446
  * .then(response => console.log(response))
424
447
  * .catch(error => console.error(error));
425
448
  */
426
- export async function getPracticeSessions(day) {
427
- const userPracticesIds = await getUserPracticeIds(day);
449
+ export async function getPracticeSessions(params ={}) {
450
+ const {
451
+ day,
452
+ userId = globalConfig.sessionConfig.userId,
453
+ } = params;
454
+ const userPracticesIds = await getUserPracticeIds(day, userId);
428
455
  if (!userPracticesIds.length) return { data: { practices: [], practiceDuration: 0} };
429
456
 
430
- const meta = await fetchUserPracticeMeta(userPracticesIds);
457
+ const meta = await fetchUserPracticeMeta(userPracticesIds, userId);
431
458
  if (!meta.data.length) return { data: { practices: [], practiceDuration: 0 } };
432
459
  const practiceDuration = meta.data.reduce((total, practice) => total + (practice.duration_seconds || 0), 0);
433
460
  const contentIds = meta.data.map(practice => practice.content_id).filter(id => id !== null);
@@ -547,17 +574,21 @@ function getStreaksAndMessage(practices) {
547
574
  };
548
575
  }
549
576
 
550
-
551
- async function getUserPracticeIds(day = new Date().toISOString().split('T')[0]) {
552
- let data = await userActivityContext.getData();
553
- let practices = data?.[DATA_KEY_PRACTICES] ?? {};
577
+ async function getUserPracticeIds(day = new Date().toISOString().split('T')[0], userId = null) {
578
+ let practices = {};
579
+ if(userId !== globalConfig.sessionConfig.userId) {
580
+ let data = await fetchUserPractices({userId});
581
+ practices = data?.["data"]?.[DATA_KEY_PRACTICES]?? {}
582
+ }else {
583
+ let data = await userActivityContext.getData()
584
+ practices = data?.[DATA_KEY_PRACTICES] ?? {}
585
+ }
554
586
  let userPracticesIds = [];
555
587
  Object.keys(practices).forEach(date => {
556
588
  if (date === day) {
557
589
  practices[date].forEach(practice => userPracticesIds.push(practice.id));
558
590
  }
559
591
  });
560
-
561
592
  return userPracticesIds;
562
593
  }
563
594
 
@@ -652,7 +683,6 @@ function calculateStreaks(practices, includeStreakMessage = false) {
652
683
  streakMessage = streakMessages.restartStreak;
653
684
  }
654
685
  }
655
-
656
686
  }
657
687
 
658
688
  return { currentDailyStreak, currentWeeklyStreak, streakMessage };