All files / src/templates/Category bicycle.tsx

0% Statements 0/36
0% Branches 0/32
0% Functions 0/10
0% Lines 0/34

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                                                                                                                                                                                                                                                                                                                                                                                                                             
import React, { useEffect, useMemo, useReducer, 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 { format, getNextDay, now } from '../../helpers';
import { CategoryMap, CategoryToggle } from './parts';
import { gql, useQuery } from '@apollo/client';
 
const styles = require('./Category.module.css');
 
export const query = graphql`
  query BicycleCategory($slug: String!, $strapiId: Int!, $locationIds: [Int]!) {
    category: strapiCategory(slug: {eq: $slug}) {
      name
      slug
      locations {
        value
        name
        portId
      }
    }
    products: allStrapiProduct(
      filter: {categories: {elemMatch: {id: {eq: $strapiId}}}, location: {id: {in: $locationIds}}}
    ) {
      totalCount
      nodes {
        productId
        productType
        name
        name_nl
        sku
        slug
        short_description
        description
        thumbnail {
          childImageSharp {
            gatsbyImageData(
              layout: CONSTRAINED,
              width: 500,
              aspectRatio: 1.25,
              formats: JPG,
              placeholder: BLURRED,
              transformOptions: {fit: CONTAIN},
              backgroundColor: "#FFFFFF"
            )
          }
        }
        location {
          value
          coordinates {
            lat
            lon
          }
        }
        coordinates {
          lat
          lon
        }
        magentoData {
          price {
            regularPrice {
              amount {
                value
              }
            }
          }
        }
      }
    }
  }
`
 
const AVAILABILITY_QUERY = gql`
  query Availability($dateFrom: String!, $dateTo: String!) {
    bicycleProductsAvailability(
      dateFrom: $dateFrom
      dateTo: $dateTo
    )
  }
`;
 
const BicycleCategory = ({ data, pageContext }) => {
  const { t } = useTranslation();
 
  const category = data.category;
  const products = data.products.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
  });
  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.bicycleProductsAvailability.includes(product.productId))
      : [],
    [availability]);
 
  const filteredProducts = useMemo(() => {
    let tempProducts = availableProducts.slice();
 
    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.sortId]);
 
  const totalCount = useMemo(() => filteredProducts.length, [filteredProducts]);
 
  useEffect(() => {
    if (availabilityError) {
      setErrorMessage(t('request.error.wrongDateRange'));
    }
  }, [availabilityError]);
 
  useEffect(() => {
    if (loading) setErrorMessage('');
  }, [loading]);
 
  const productsSection = useMemo(() =>
    <Products
      products={filteredProducts}
      preloader={loading}
      startDate={filters.startDate}
      endDate={filters.endDate}
    />,
    [filters.startDate, filters.endDate, filteredProducts, loading]);
 
  console.groupCollapsed('Filters');
  console.log(filters);
  console.groupEnd();
 
  return (
    <div>
      <Layout classes={styles.CategoryLayout}>
        <Helmet>
          <title>{category.name} | {t('sitename')}</title>
        </Helmet>
        <h1 className="sr-only">{t('parking.title')}</h1>
        <Link to={
          `/fahrradverleih-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('bicycle.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}
              loading={loading}
              maxInterval={31}
            />
 
            <div className={`${styles.CategoryHeader}`}>
              {!loading && <div>{totalCount} {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={products}
              center={pageContext.location
                ? [pageContext.location.coordinates.lat, pageContext.location.coordinates.lon]
                : undefined}
              zoom={pageContext.location ? 12 : 9}
              open={showMap}
            />
          </div>
        </div>
 
        <CategoryToggle on={showMap} onClick={() => setShowMap(!showMap)} />
      </Layout>
    </div>
  )
}
 
export default BicycleCategory;