Skip to content

Commit

Permalink
refactor: adjusted sorting options for helpful-links
Browse files Browse the repository at this point in the history
  • Loading branch information
corypride committed Jan 13, 2025
1 parent 2b86bea commit 063d484
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 56 deletions.
18 changes: 6 additions & 12 deletions backend/src/database/helpful_links.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package database
import (
"UnlockEdv2/src/models"
"fmt"
"strings"
)

type HelpfulLinkResp struct {
Expand All @@ -19,13 +20,6 @@ func (db *DB) GetHelpfulLinks(page, perPage int, search, orderBy string, onlyVis
tx := db.Model(&models.HelpfulLink{}).Select("helpful_links.*, EXISTS(?) as is_favorited", subQuery)
var total int64

validOrder := map[string]bool{
"title ASC": true,
"title DESC": true,
"created_at ASC": true,
"created_at DESC": true,
}

if onlyVisible {
tx = tx.Where("visibility_status = ?", true)
}
Expand All @@ -34,11 +28,11 @@ func (db *DB) GetHelpfulLinks(page, perPage int, search, orderBy string, onlyVis
search = "%" + search + "%"
tx = tx.Where("LOWER(title) LIKE ?", search)
}

if valid, ok := validOrder[orderBy]; ok && valid {
switch strings.ToLower(orderBy) {
case "most_popular":
tx = tx.Order("COUNT(f.id) DESC")
default:
tx = tx.Order(orderBy)
} else {
tx = tx.Order("created_at DESC")
}

if err := tx.Count(&total).Error; err != nil {
Expand All @@ -52,7 +46,7 @@ func (db *DB) GetHelpfulLinks(page, perPage int, search, orderBy string, onlyVis

func (db *DB) AddHelpfulLink(link *models.HelpfulLink) error {
if db.Where("url = ?", link.Url).First(&models.HelpfulLink{}).RowsAffected > 0 {
return NewDBError(fmt.Errorf("Link already exists"), "helpful_links")
return NewDBError(fmt.Errorf("link already exists"), "helpful_links")
}
if err := db.Create(link).Error; err != nil {
return newCreateDBError(err, "helpful_links")
Expand Down
3 changes: 2 additions & 1 deletion backend/src/handlers/helpful_links_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,14 @@ func (srv *Server) changeSortOrder(w http.ResponseWriter, r *http.Request, log s

func (srv *Server) handleGetHelpfulLinks(w http.ResponseWriter, r *http.Request, log sLog) error {
search := r.URL.Query().Get("search")
orderBy := r.URL.Query().Get("order_by")
onlyVisible := r.URL.Query().Get("visibility") == "true"
if !userIsAdmin(r) {
onlyVisible = true
}
userID := srv.getUserID(r)
page, perPage := srv.getPaginationInfo(r)
total, links, err := srv.Db.GetHelpfulLinks(page, perPage, search, HelpfulSortOrder[srv.getFacilityID(r)], onlyVisible, userID)
total, links, err := srv.Db.GetHelpfulLinks(page, perPage, search, orderBy, onlyVisible, userID)
if err != nil {
return newInternalServerServiceError(err, "error fetching helpful links")
}
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/Components/LibraryLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
Library,
ServerResponseMany,
UserRole,
FilterLibrariesAdmin
FilterLibrariesVidsandHelpfulLinksAdmin
} from '@/common';
import DropdownControl from '@/Components/inputs/DropdownControl';
import SearchBar from '@/Components/inputs/SearchBar';
Expand Down Expand Up @@ -33,7 +33,7 @@ export default function LibaryLayout({
LibraryAdminVisibility['All Libraries']
);
const [orderBy, setOrderBy] = useState<string>(
FilterLibrariesAdmin['Date Added (Newest First)']
FilterLibrariesVidsandHelpfulLinksAdmin['Date Added (Newest First)']
);
let role = user.role;
if (studentView) {
Expand Down Expand Up @@ -106,7 +106,7 @@ export default function LibaryLayout({
/>
<DropdownControl
label="Filter by"
enumType={FilterLibrariesAdmin}
enumType={FilterLibrariesVidsandHelpfulLinksAdmin}
setState={setOrderBy}
/>
</>
Expand Down
47 changes: 11 additions & 36 deletions frontend/src/Pages/HelpfulLinksManagement.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
HelpfulLink,
FilterLibrariesVidsandHelpfulLinksAdmin,
ModalType,
ServerResponseOne,
ToastState,
Expand All @@ -20,8 +21,8 @@ import { useDebounceValue } from 'usehooks-ts';
import useSWR from 'swr';
import { AxiosError } from 'axios';
import API from '@/api/api';
import SortByPills from '@/Components/pill-labels/SortByPills';
import { isAdministrator, useAuth } from '@/useAuth';
import DropdownControl from '@/Components/inputs/DropdownControl';

export default function HelpfulLinksManagement() {
const { user } = useAuth();
Expand All @@ -33,17 +34,19 @@ export default function HelpfulLinksManagement() {
const [pageQuery, setPageQuery] = useState<number>(1);
const [searchTerm, setSearchTerm] = useState<string>('');
const searchQuery = useDebounceValue(searchTerm, 500);
const [sortQuery, setSortQuery] = useState<string>(
FilterLibrariesVidsandHelpfulLinksAdmin['Date Added (Newest First)']
);
const { toaster } = useToast();

const { data, mutate, error, isLoading } = useSWR<
ServerResponseOne<HelpfulLinkAndSort>,
AxiosError
>(
`/api/helpful-links?search=${searchQuery[0]}&page=${pageQuery}&per_page=${perPage}`
`/api/helpful-links?search=${searchQuery[0]}&page=${pageQuery}&per_page=${perPage}&order_by=${sortQuery}`
);
const helpfulLinks = data?.data.helpful_links ?? [];
const meta = data?.data.meta;
let globalSortOrder = data?.data.sort_order;

function updateLinks() {
addLinkModal.current?.close();
Expand Down Expand Up @@ -87,28 +90,6 @@ export default function HelpfulLinksManagement() {
void mutate();
};

async function updateGlobalSort(sort: string) {
const response = await API.put<
{ message: string },
{ sort_order: string }
>('helpful-links/sort', { sort_order: sort });
if (response.success) {
globalSortOrder = sort;
void mutate();
}
toaster(
response.message,
response.success ? ToastState.success : ToastState.error
);
}

const sortPills = [
{ name: 'Date Added ↓', value: 'created_at DESC' },
{ name: 'Date Added ↑', value: 'created_at ASC' },
{ name: 'Title (A-Z)', value: 'title ASC' },
{ name: 'Title (Z-A)', value: 'title DESC' }
];

return (
<>
<div className="flex flex-row justify-between">
Expand All @@ -118,17 +99,11 @@ export default function HelpfulLinksManagement() {
searchTerm={searchTerm}
changeCallback={handleChange}
/>
<h3 className="ml-2">Order:</h3>
{sortPills.map((label) => (
<SortByPills
key={label.value + label.name}
label={label}
updateSort={() =>
void updateGlobalSort(label.value)
}
isSelected={label.value === globalSortOrder}
/>
))}
<DropdownControl
label="Order by"
setState={setSortQuery}
enumType={FilterLibrariesVidsandHelpfulLinksAdmin}
/>
</div>
{/* add links button */}
<div
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/Pages/VideoManagement.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
Video,
ServerResponseMany,
UserRole,
FilterLibrariesAdmin
FilterLibrariesVidsandHelpfulLinksAdmin
} from '../common';
import AddVideosForm from '@/Components/forms/AddVideosForm';
import Modal from '@/Components/Modal';
Expand Down Expand Up @@ -36,7 +36,7 @@ export default function VideoManagement() {
const [perPage, setPerPage] = useState(12);
const [pageQuery, setPageQuery] = useState(1);
const [sortQuery, setSortQuery] = useState<string>(
FilterLibrariesAdmin['Date Added (Newest First)']
FilterLibrariesVidsandHelpfulLinksAdmin['Date Added (Newest First)']
);
const navigate = useNavigate();
const { toaster } = useToast();
Expand Down Expand Up @@ -111,7 +111,7 @@ export default function VideoManagement() {
<DropdownControl
label="Order by"
setState={setSortQuery}
enumType={FilterLibrariesAdmin}
enumType={FilterLibrariesVidsandHelpfulLinksAdmin}
/>
</div>
<button
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -820,7 +820,7 @@ export enum LibraryAdminVisibility {
'Featured' = 'featured'
}

export enum FilterLibrariesAdmin {
export enum FilterLibrariesVidsandHelpfulLinksAdmin {
'Most Popular' = 'most_popular',
'Title (A to Z)' = 'title ASC',
'Title (Z to A)' = 'title DESC',
Expand Down

0 comments on commit 063d484

Please sign in to comment.