How to build easier logic for displaying banners? [closed]

I need your review and help to build the correct logic for displaying the banner to users.

Banner display rules:

Banners should be displayed according to the structure of the filtered banners object.

Display priority:

  1. If the user came to the site with some utm tag, then first we show filtered banners from the utm banner group (filteredBanners.utm)
  2. Otherwise from the default group (filtered banners)

Impression priority by user type:

  1. New visitors (newUsers)
  2. Visitors (oldUsers)
  3. Everyone (users)

When is a user not considered a new user?

Since we now have two groups of banners (utm, default), we need to determine whether the user has watched all the banners from the category (newUsers) based on the group (utm, default). For example, if a user has watched all the banners from the newUsers category from the utm group, then he is no longer considered a new user only for the utm group. Therefore, each group must have its own new user definition identifier.

Category: newUsers

Banners from the newUsers category will be shown only once and will not be re-displayed the next time the user visits.

Categories: oldUsers and users

After completely viewing banners from the oldUsers and users categories, you need to reset the history of viewed banners in order to redisplay them on the next visit.

Problem:

I can’t correctly store data about already viewed banners. If the user manually deletes one of the viewed banners from the local storage then that deleted banner cannot be shown again manually by the user. When the page is reloaded, the list of banners from the server may be updated and new banners may arrive, and in such cases, I also could not properly display the new incoming banners. Help me build easier logic for displaying banners correctly, please.

Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Banners</title>
</head>
<body>
    <div id="container" style="display: none;">
        <pre id="banner"></pre>
        <div>
            <button id="btn">Handle Next</button>
        </div>
    </div>
    <script>
        const banners = [{
                "id": 1,
                "title": "UTM query based banner for all users",
                "image": "/banners/banner.jpg",
                "details": {
                    "user": "users",
                    "utm": "OFF-50"
                },
                "order": 4
            },
            {
                "id": 4,
                "title": "UTM query based banner for new users",
                "image": "/banners/banner.jpg",
                "details": {
                    "user": "new_users",
                    "utm": "FRIDAY"
                },
                "order": 2
            },
            {
                "id": 13,
                "title": "UTM query based banner for old users",
                "image": "/banners/banner.jpg",
                "details": {
                    "user": "old_users",
                    "utm": "FREE"
                },
                "order": 7
            },
            {
                "id": 3,
                "title": "Default banner for old users",
                "image": "/banners/banner.jpg",
                "details": {
                    "user": "old_users"
                },
                "order": 3
            },
            {
                "id": 9,
                "title": "Default second banner for old users",
                "image": "/banners/banner.jpg",
                "details": {
                    "user": "old_users"
                },
                "order": 1
            },
            {
                "id": 40,
                "title": "Default banner for all users",
                "image": "/banners/banner.jpg",
                "details": {
                    "user": "users"
                },
                "order": 8
            },
            {
                "id": 21,
                "title": "Default second banner for all users",
                "image": "/banners/banner.jpg",
                "details": {
                    "user": "users"
                },
                "order": 17
            },
            {
                "id": 11,
                "title": "Default third banner for all users",
                "image": "/banners/banner.jpg",
                "details": {
                    "user": "users"
                },
                "order": 5
            },
            {
                "id": 14,
                "title": "Default banner for new users",
                "image": "/banners/banner.jpg",
                "details": {
                    "user": "new_users"
                },
                "order": 6
            },
            {
                "id": 33,
                "title": "Default second banner for new users",
                "image": "/banners/banner.jpg",
                "details": {
                    "user": "new_users"
                },
                "order": 9
            },
        ];

        const getFilteredBanners = () => {
            if (!banners?.length) {
                return [];
            }

            const filterByUTM = (items) => {
                const params = new Proxy(new URLSearchParams(window.location.search), {
                    get: (searchParams, prop) => searchParams.get(prop),
                });

                let utmSource = params.utm_source;

                return items.filter(
                    (item) =>
                    item?.details?.utm?.length &&
                    utmSource?.length &&
                    utmSource.includes(item.details?.utm)
                );
            }

            const filterByUser = (items, user, ignoreUTM = false) =>
                items.filter((item) => item?.details?.user === user && (ignoreUTM ? !item?.details?.utm : true));

            const sortItems = (a, b) =>
                a?.order > -1 && b?.order > -1 ? a.order - b.order : 0;

            return {
                utm: {
                    newUsers: filterByUser(filterByUTM(banners), 'new_users').sort(sortItems),
                    oldUsers: filterByUser(filterByUTM(banners), 'old_users').sort(sortItems),
                    users: filterByUser(filterByUTM(banners), 'users').sort(sortItems),
                },
                default: {
                    newUsers: filterByUser(banners, "new_users", true).sort(sortItems),
                    oldUsers: filterByUser(banners, "old_users", true).sort(sortItems),
                    users: filterByUser(banners, "users", true).sort(sortItems),
                },
            };
        };

        const findObjKey = (key, obj) => {
            try {
                return typeof obj === "object" && obj !== null ?
                    key.split(".").reduce((a, b) => a[b], obj) :
                    false;
            } catch {
                return false;
            }
        };
        const arraysEqual = (newValues, oldValues) => {
            for (var i = 0; i < newValues.length; ++i) {
                if (!oldValues.includes(newValues[i])) return false;
            }
            return true;
        };

        var isWasReset = false

        const getNextBanner = async () => {
            const filteredBanners = getFilteredBanners()

            const params = new Proxy(new URLSearchParams(window.location.search), {
                get: (searchParams, prop) => searchParams.get(prop),
            });

            const utmSource = params.utm_source;

            start: for (let bannerGroup in filteredBanners) {
                const bannerState = JSON.parse(localStorage.getItem("banner")) || {};

                if (!Object.keys(bannerState)?.length) {
                    localStorage.removeItem("visitedAt");
                }

                const visitedAt = localStorage.getItem("visitedAt") ?
                    Date.parse(localStorage.getItem("visitedAt")) :
                    null;

                // Skip UTM banners if no utm_source is present in query string
                if (bannerGroup === "utm" && !utmSource?.length) continue;

                for (let userType in filteredBanners[bannerGroup]) {
                    // Skip new users if visitedAt exists
                    if (visitedAt && userType === "newUsers") continue;
                    // Skip old users if visitedAt doesn't exist
                    if (!visitedAt && userType === "oldUsers") continue;

                    if (userType === "newUsers") {
                        if (filteredBanners[bannerGroup]["newUsers"].length) {
                            const newUserBanners = filteredBanners[bannerGroup]["newUsers"];
                            const localIds = findObjKey(bannerGroup + "." + userType, bannerState) || [];
                            const ids = newUserBanners.map((i) => i.id);
                            const isEqualValues = arraysEqual(ids, localIds);
                            if (!isEqualValues) {
                                localStorage.removeItem("visitedAt");
                            } else {
                                if (isEqualValues) {
                                    localStorage.setItem("visitedAt", new Date().toISOString());
                                    continue start;
                                }
                            }
                        } else {
                            localStorage.removeItem("visitedAt");
                            localStorage.setItem(
                                "banner",
                                JSON.stringify({
                                    ...bannerState,
                                    [bannerGroup]: {
                                        ...(bannerState[bannerGroup] || {}),
                                        [userType]: [],
                                    },
                                })
                            );
                        }
                    }

                    for (let i = 0; i < filteredBanners[bannerGroup][userType].length; i++) {
                        const item = filteredBanners[bannerGroup][userType][i];
                        const viewedList = findObjKey(bannerGroup + "." + userType, bannerState) || [];

                        if (viewedList && Array.isArray(viewedList) && viewedList.includes(item.id)) continue;

                        localStorage.setItem(
                            "banner",
                            JSON.stringify({
                                ...bannerState,
                                [bannerGroup]: {
                                    ...(bannerState[bannerGroup] || {}),
                                    [userType]: [...viewedList, item.id],
                                },
                            })
                        );

                        if (userType === "newUsers") {
                            const newUserBanners = filteredBanners[bannerGroup]["newUsers"];
                            const ids = newUserBanners.map((i) => i.id);
                            const isEqualValues = arraysEqual(ids, [...viewedList, item.id]);
                            if (isEqualValues) {
                                localStorage.setItem("visitedAt", new Date().toISOString());
                            }
                        }

                        if (bannerGroup === "default") {
                            if (userType === "oldUsers" || userType === "users") {
                                const oldUsersBanners = filteredBanners[bannerGroup]["oldUsers"];
                                const usersBanners = filteredBanners[bannerGroup]["users"];

                                if (usersBanners.length && userType === "users") {
                                    const ids = usersBanners.map((i) => i.id);
                                    const isEqualValues = arraysEqual(ids, [...viewedList, item.id]);

                                    if (isEqualValues) {
                                        localStorage.setItem(
                                            "banner",
                                            JSON.stringify({
                                                ...bannerState,
                                                [bannerGroup]: {
                                                    ...(bannerState[bannerGroup] || {}),
                                                    oldUsers: [],
                                                    users: [],
                                                },
                                            })
                                        );

                                        isWasReset = true;
                                    }
                                } else if (
                                    !usersBanners.length &&
                                    oldUsersBanners.length &&
                                    userType === "oldUsers"
                                ) {
                                    const ids = oldUsersBanners.map((i) => i.id);
                                    const isEqualValues = arraysEqual(ids, [...viewedList, item.id]);

                                    if (isEqualValues) {
                                        localStorage.setItem(
                                            "banner",
                                            JSON.stringify({
                                                ...bannerState,
                                                [bannerGroup]: {
                                                    ...(bannerState[bannerGroup] || {}),
                                                    oldUsers: [],
                                                    users: [],
                                                },
                                            })
                                        );

                                        isWasReset = true;
                                    }
                                }
                            }
                        }

                        return item;
                    }
                }
            }

        }

        const handleShowBanner = async () => {
            const bannerContainer = document.getElementById('container')
            const bannerEl = document.getElementById('banner')
            if (isWasReset) {
                bannerContainer.style.display = 'none'
                return;
            }

            const banner = await getNextBanner();

            if (banner?.id) {
                bannerContainer.style.display = 'block'
                bannerEl.innerHTML = JSON.stringify(banner, null, 2)
            } else {
                bannerContainer.style.display = 'none'
            }
        };
        document.addEventListener('DOMContentLoaded', async () => {
            await handleShowBanner()

            const button = document.getElementById('btn')
            button.onclick = async () => {
                await handleShowBanner()
            }
        }, false);
    </script>
</body>
</html>

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật