diff --git a/backend/models/list.model.js b/backend/models/list.model.js index f009e67..e872b28 100644 --- a/backend/models/list.model.js +++ b/backend/models/list.model.js @@ -10,18 +10,24 @@ exports.getUnboughtItems = async () => { gl.bought, ENCODE(gl.item_image, 'base64') as item_image, gl.image_mime_type, - ARRAY_AGG(DISTINCT COALESCE(gh_user.name, creator.name)) FILTER (WHERE COALESCE(gh_user.name, creator.name) IS NOT NULL) as added_by_users, + ( + SELECT ARRAY_AGG(u.name ORDER BY gh.added_on DESC) + FROM ( + SELECT gh.added_by, gh.added_on, + ROW_NUMBER() OVER (PARTITION BY gh.list_item_id ORDER BY gh.added_on DESC) as rn + FROM grocery_history gh + WHERE gh.list_item_id = gl.id + ) gh + JOIN users u ON gh.added_by = u.id + WHERE gh.rn <= gl.quantity + ) as added_by_users, gl.modified_on as last_added_on, ic.item_type, ic.item_group, ic.zone FROM grocery_list gl - LEFT JOIN users creator ON gl.added_by = creator.id - LEFT JOIN grocery_history gh ON gl.id = gh.list_item_id - LEFT JOIN users gh_user ON gh.added_by = gh_user.id LEFT JOIN item_classification ic ON gl.id = ic.id WHERE gl.bought = FALSE - GROUP BY gl.id, gl.item_name, gl.quantity, gl.bought, gl.item_image, gl.image_mime_type, gl.modified_on, ic.item_type, ic.item_group, ic.zone ORDER BY gl.id ASC` ); return result.rows; @@ -119,15 +125,21 @@ exports.getRecentlyBoughtItems = async () => { gl.bought, ENCODE(gl.item_image, 'base64') as item_image, gl.image_mime_type, - ARRAY_AGG(DISTINCT COALESCE(gh_user.name, creator.name)) FILTER (WHERE COALESCE(gh_user.name, creator.name) IS NOT NULL) as added_by_users, + ( + SELECT ARRAY_AGG(u.name ORDER BY gh.added_on DESC) + FROM ( + SELECT gh.added_by, gh.added_on, + ROW_NUMBER() OVER (PARTITION BY gh.list_item_id ORDER BY gh.added_on DESC) as rn + FROM grocery_history gh + WHERE gh.list_item_id = gl.id + ) gh + JOIN users u ON gh.added_by = u.id + WHERE gh.rn <= gl.quantity + ) as added_by_users, gl.modified_on as last_added_on FROM grocery_list gl - LEFT JOIN users creator ON gl.added_by = creator.id - LEFT JOIN grocery_history gh ON gl.id = gh.list_item_id - LEFT JOIN users gh_user ON gh.added_by = gh_user.id WHERE gl.bought = TRUE AND gl.modified_on >= NOW() - INTERVAL '24 hours' - GROUP BY gl.id, gl.item_name, gl.quantity, gl.bought, gl.item_image, gl.image_mime_type, gl.modified_on ORDER BY gl.modified_on DESC` ); return result.rows;