All files / src/templates/Category experience.tsx

0% Statements 0/55
0% Branches 0/50
0% Functions 0/17
0% Lines 0/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import React, { useEffect, useMemo, useReducer, useRef, useState } from 'react';
import { graphql } from 'gatsby';
import { Helmet } from 'react-helmet';
import { Layout, SvgIcon, Filter, Products, filterReducer } from '../../components';
import { useTranslation } from 'react-i18next';
import { LocalizedLink as Link } from 'gatsby-theme-i18n';
import { gql, useQuery } from '@apollo/client';
import { DEFAULT_COORDS } from '../../configs/config';
import { format, getNextDay, now } from '../../helpers';
import { CategoryMap, CategoryToggle } from './parts';
 
const styles = require('./Category.module.css');
 
export const query = graphql`
  query ExperienceCategory($slug: String!, $strapiId: Int!, $locationIds: [Int]!) {
    category: strapiCategory(slug: {eq: $slug}) {
      name
      slug
      locations {
        value
        name
        portId
      }
    }
    experienceCategories: allStrapiExperienceCategory {
      nodes {
        value
        label
      }
    }
    experienceThemes: allStrapiExperienceAttribute {
      nodes {
        value
        label
      }
    }
    products: allStrapiProduct(
      filter: {categories: {elemMatch: {id: {eq: $strapiId}}}, location: {id: {in: $locationIds}}}
    ) {
      totalCount
      nodes {
        productType
        productId
        name
        name_nl
        sku
        slug
        short_description
        description
        thumbnail {
          childImageSharp {
            gatsbyImageData(layout: CONSTRAINED, aspectRatio: 1.25, formats: JPG, placeholder: BLURRED)
          }
        }
        location {
          value
          coordinates {
            lat
            lon
          }
        }
        coordinates {
          lat
          lon
        }
        experience_categories {
          label
          value
        }
        experience_attributes {
          label
          value
        }
        duration {
          hours
          minutes
        }
        magentoData {
          price {
            regularPrice {
              amount {
                value
              }
            }
          }
        }
      }
    }
  }
`
 
const AVAILABILITY_QUERY = gql`
  query Availability($dateFrom: String!, $dateTo: String!) {
    experiencesAvailability(
      dateFrom: $dateFrom
      dateTo: $dateTo
    )
  }
`;
 
const ExperienceCategory = ({ data, pageContext }) => {
  const { t } = useTranslation();
 
  const category = data.category;
  const products = data.products.nodes;
  const experienceCategories = data.experienceCategories.nodes;
  const experienceThemes = data.experienceThemes.nodes;
 
  const [showMap, setShowMap] = useState(false);
 
  const [filters, updateFilters] = useReducer(filterReducer, {
    locationId: pageContext.location ? pageContext.location.value : '',
    startDate: format(now, 'yyyy-MM-dd'),
    endDate: format(getNextDay(now), 'yyyy-MM-dd'),
    sortId: null,
    categoryIds: [],
    themeIds: []
  });
  const [errorMessage, setErrorMessage] = useState('');
 
  const { data: availability, loading, error: availabilityError } = useQuery(AVAILABILITY_QUERY, {
    variables: {
      dateFrom: filters.startDate,
      dateTo: filters.endDate
    },
    skip: !filters.startDate || !filters.endDate,
    context: { client: 'strapi' }
  });
 
  const availableProducts = useMemo(() =>
    availability
      ? products.filter(product => availability.experiencesAvailability.includes(product.productId))
      : [],
    [availability]);
 
  const filteredProducts = useMemo(() => {
    let tempProducts = availableProducts.slice();
 
    if (filters.locationId) {
      tempProducts = tempProducts.filter(product => product.location.value === filters.locationId);
    }
 
    if (filters.categoryIds?.length || filters.themeIds?.length) {
      tempProducts = tempProducts.filter(product =>
        (filters.categoryIds?.length ? product.experience_categories.some(cat => filters.categoryIds?.includes(cat.value)) : true) &&
        (filters.themeIds?.length ? product.experience_attributes.some(attr => filters.themeIds?.includes(attr.value)) : true)
      );
    }
 
    return filters.sortId
      ? tempProducts.sort((productA, productB) => {
        const aPrice = productA.magentoData.price.regularPrice.amount.value;
        const bPrice = productB.magentoData.price.regularPrice.amount.value;
        const res = filters.sortId === 1 ? 1 : -1;
 
        return aPrice < bPrice ? -res : aPrice > bPrice ? res : 0;
      })
      : tempProducts;
  }, [
    availableProducts,
    filters.locationId,
    filters.sortId,
    filters.categoryIds,
    filters.themeIds
  ]);
 
  const totalCount = useMemo(() => filteredProducts.length, [filteredProducts]);
 
  const [resProducts, setResProducts] = useState<any[]>([]);
 
  const applyFilters = (isGlobal) => {
    if (isGlobal) firstTime.current = true;
    else setResProducts(filteredProducts);
  }
 
  const firstTime = useRef(true);
 
  useEffect(() => {
    if (firstTime.current && filteredProducts.length) {
      setResProducts(filteredProducts);
      firstTime.current = false;
    }
  }, [filteredProducts]);
 
  useEffect(() => {
    firstTime.current = true;
  }, []);
 
  useEffect(() => {
    if (availabilityError) {
      setErrorMessage(t('request.error.wrongDateRange'));
    }
  }, [availabilityError]);
 
  useEffect(() => {
    if (loading) setErrorMessage('');
  }, [loading]);
 
  const productsSection = useMemo(() =>
    <Products
      products={resProducts}
      preloader={loading}
      startDate={filters.startDate}
      endDate={filters.endDate}
    />,
    [filters.startDate, filters.endDate, resProducts, loading]);
 
  return (
    <div>
      <Layout classes={styles.CategoryLayout}>
        <Helmet>
          <title>{category.name} | {t('sitename')}</title>
        </Helmet>
        <h1 className="sr-only">{t('parking.title')}</h1>
        <Link to={
          `/aktivitaeten-buchen?${filters.locationId ? 'location=' + filters.locationId : ''}&startDate=${filters.startDate}&endDate=${filters.endDate}`
        } className="backlink">
          <SvgIcon icon={{ name: 'chevron-left', width: 20, height: 20, fill: '#144154' }} />
          <span>{t('experience.book')}</span>
        </Link>
 
        <div className={styles.Category}>
          <div className={`${styles.CategoryLeft} ${!showMap ? styles.show : ''}`}>
            <Filter
              slug={category.slug}
              locations={category.locations}
              quantity={totalCount}
              fixed={showMap}
              filters={filters}
              updateFilters={updateFilters}
              config={{
                category: {
                  options: experienceCategories
                },
                theme: {
                  options: experienceThemes
                }
              }}
              loading={loading}
              onConfirm={applyFilters}
              maxInterval={31}
            />
 
            <div className={`${styles.CategoryHeader}`}>
              {!loading && <div>{resProducts.length} {t('results')}</div>}
            </div>
            <hr className="hr only-sm" />
            {errorMessage && <p className="errorText">{errorMessage}</p>}
            {productsSection}
          </div>
 
          <div className={`${styles.CategoryRight} ${showMap ? styles.show : ''}`}>
            <CategoryMap
              products={resProducts}
              center={pageContext.location
                ? [pageContext.location.coordinates.lat, pageContext.location.coordinates.lon]
                : DEFAULT_COORDS}
              zoom={pageContext.location ? 12 : 7}
              open={showMap}
            />
          </div>
        </div>
 
        <CategoryToggle on={showMap} onClick={() => setShowMap(!showMap)} />
      </Layout>
    </div>
  )
}
 
export default ExperienceCategory;